mirror of
https://github.com/docmost/docmost.git
synced 2025-11-16 23:01:11 +10:00
implement jwt auth
This commit is contained in:
@ -12,7 +12,7 @@ import { AppDataSource } from './database/typeorm.config';
|
||||
EnvironmentModule,
|
||||
TypeOrmModule.forRoot({
|
||||
...AppDataSource.options,
|
||||
entities: ['dist/src/**/*.entity.ts'],
|
||||
entities: ['dist/src/**/*.entity.{ts,js}'],
|
||||
migrations: ['dist/src/**/migrations/*.{ts,js}'],
|
||||
autoLoadEntities: true,
|
||||
}),
|
||||
|
||||
18
server/src/core/auth/auth.controller.spec.ts
Normal file
18
server/src/core/auth/auth.controller.spec.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AuthController } from './auth.controller';
|
||||
|
||||
describe('AuthController', () => {
|
||||
let controller: AuthController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AuthController],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<AuthController>(AuthController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
26
server/src/core/auth/auth.controller.ts
Normal file
26
server/src/core/auth/auth.controller.ts
Normal file
@ -0,0 +1,26 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Post,
|
||||
} from '@nestjs/common';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { AuthService } from './services/auth.service';
|
||||
import { CreateUserDto } from '../user/dto/create-user.dto';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private authService: AuthService) {}
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('login')
|
||||
async login(@Body() loginInput: LoginDto) {
|
||||
return await this.authService.login(loginInput);
|
||||
}
|
||||
|
||||
@Post('register')
|
||||
async register(@Body() createUserDto: CreateUserDto) {
|
||||
return await this.authService.register(createUserDto);
|
||||
}
|
||||
}
|
||||
29
server/src/core/auth/auth.module.ts
Normal file
29
server/src/core/auth/auth.module.ts
Normal file
@ -0,0 +1,29 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './services/auth.service';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { EnvironmentService } from '../../environment/environment.service';
|
||||
import { TokenService } from './services/token.service';
|
||||
import { UserService } from '../user/user.service';
|
||||
import { UserRepository } from '../user/repositories/user.repository';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
JwtModule.registerAsync({
|
||||
useFactory: async (environmentService: EnvironmentService) => {
|
||||
return {
|
||||
global: true,
|
||||
secret: environmentService.getJwtSecret(),
|
||||
signOptions: {
|
||||
expiresIn: environmentService.getJwtTokenExpiresIn(),
|
||||
},
|
||||
};
|
||||
},
|
||||
inject: [EnvironmentService],
|
||||
}),
|
||||
],
|
||||
exports: [TokenService],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, TokenService, UserService, UserRepository],
|
||||
})
|
||||
export class AuthModule {}
|
||||
11
server/src/core/auth/dto/login.dto.ts
Normal file
11
server/src/core/auth/dto/login.dto.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class LoginDto {
|
||||
@IsNotEmpty()
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
password: string;
|
||||
}
|
||||
30
server/src/core/auth/guards/JwtGuard.ts
Normal file
30
server/src/core/auth/guards/JwtGuard.ts
Normal file
@ -0,0 +1,30 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { TokenService } from '../services/token.service';
|
||||
|
||||
@Injectable()
|
||||
export class JwtGuard implements CanActivate {
|
||||
constructor(private tokenService: TokenService) {}
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const token: string = await this.tokenService.extractTokenFromHeader(
|
||||
request,
|
||||
);
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Invalid jwt token');
|
||||
}
|
||||
|
||||
try {
|
||||
request['user'] = await this.tokenService.verifyJwt(token);
|
||||
} catch (error) {
|
||||
throw new UnauthorizedException('Could not verify jwt token');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
18
server/src/core/auth/services/auth.service.spec.ts
Normal file
18
server/src/core/auth/services/auth.service.spec.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let service: AuthService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [AuthService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<AuthService>(AuthService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
44
server/src/core/auth/services/auth.service.ts
Normal file
44
server/src/core/auth/services/auth.service.ts
Normal file
@ -0,0 +1,44 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { LoginDto } from '../dto/login.dto';
|
||||
import { User } from '../../user/entities/user.entity';
|
||||
import { CreateUserDto } from '../../user/dto/create-user.dto';
|
||||
import { UserService } from '../../user/user.service';
|
||||
import { TokenService } from './token.service';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private userService: UserService,
|
||||
private tokenService: TokenService,
|
||||
) {}
|
||||
|
||||
async login(loginDto: LoginDto) {
|
||||
const user: User = await this.userService.findByEmail(loginDto.email);
|
||||
const invalidCredentialsMessage = 'email or password does not match';
|
||||
|
||||
if (
|
||||
!user ||
|
||||
!(await this.userService.compareHash(loginDto.password, user.password))
|
||||
) {
|
||||
throw new UnauthorizedException(invalidCredentialsMessage);
|
||||
}
|
||||
|
||||
user.lastLoginAt = new Date();
|
||||
|
||||
const token: string = await this.tokenService.generateJwt(user);
|
||||
|
||||
return { user, token };
|
||||
}
|
||||
|
||||
async register(createUserDto: CreateUserDto) {
|
||||
const user: User = await this.userService.create(createUserDto);
|
||||
|
||||
const token: string = await this.tokenService.generateJwt(user);
|
||||
|
||||
return { user, token };
|
||||
}
|
||||
}
|
||||
18
server/src/core/auth/services/token.service.spec.ts
Normal file
18
server/src/core/auth/services/token.service.spec.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { TokenService } from './token.service';
|
||||
|
||||
describe('TokenService', () => {
|
||||
let service: TokenService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [TokenService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<TokenService>(TokenService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
33
server/src/core/auth/services/token.service.ts
Normal file
33
server/src/core/auth/services/token.service.ts
Normal file
@ -0,0 +1,33 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { EnvironmentService } from '../../../environment/environment.service';
|
||||
import { User } from '../../user/entities/user.entity';
|
||||
import { FastifyRequest } from 'fastify';
|
||||
|
||||
@Injectable()
|
||||
export class TokenService {
|
||||
constructor(
|
||||
private jwtService: JwtService,
|
||||
private environmentService: EnvironmentService,
|
||||
) {}
|
||||
async generateJwt(user: User): Promise<string> {
|
||||
const payload = {
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
};
|
||||
return await this.jwtService.signAsync(payload);
|
||||
}
|
||||
|
||||
async verifyJwt(token: string) {
|
||||
return await this.jwtService.verifyAsync(token, {
|
||||
secret: this.environmentService.getJwtSecret(),
|
||||
});
|
||||
}
|
||||
|
||||
async extractTokenFromHeader(
|
||||
request: FastifyRequest,
|
||||
): Promise<string | undefined> {
|
||||
const [type, token] = request.headers.authorization?.split(' ') ?? [];
|
||||
return type === 'Bearer' ? token : undefined;
|
||||
}
|
||||
}
|
||||
@ -1,7 +1,8 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UserModule } from './user/user.module';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [UserModule],
|
||||
imports: [UserModule, AuthModule],
|
||||
})
|
||||
export class CoreModule {}
|
||||
|
||||
@ -1 +1,23 @@
|
||||
export class CreateUserDto {}
|
||||
import {
|
||||
IsEmail,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MinLength,
|
||||
} from 'class-validator';
|
||||
|
||||
export class CreateUserDto {
|
||||
@IsOptional()
|
||||
@MinLength(3)
|
||||
@IsString()
|
||||
name: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
@MinLength(8)
|
||||
@IsString()
|
||||
password: string;
|
||||
}
|
||||
|
||||
@ -1,10 +1,12 @@
|
||||
import {
|
||||
BeforeInsert,
|
||||
Column,
|
||||
CreateDateColumn,
|
||||
Entity,
|
||||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
|
||||
@Entity('users')
|
||||
export class User {
|
||||
@ -46,4 +48,15 @@ export class User {
|
||||
|
||||
@UpdateDateColumn()
|
||||
updatedAt: Date;
|
||||
|
||||
toJSON() {
|
||||
delete this.password;
|
||||
return this;
|
||||
}
|
||||
|
||||
@BeforeInsert()
|
||||
async hashPassword() {
|
||||
const saltRounds = 12;
|
||||
this.password = await bcrypt.hash(this.password, saltRounds);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,4 +1,17 @@
|
||||
import { Repository } from 'typeorm';
|
||||
import { DataSource, Repository } from 'typeorm';
|
||||
import { User } from '../entities/user.entity';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
export class UserRepository extends Repository<User> {}
|
||||
@Injectable()
|
||||
export class UserRepository extends Repository<User> {
|
||||
constructor(private dataSource: DataSource) {
|
||||
super(User, dataSource.createEntityManager());
|
||||
}
|
||||
async findByEmail(email: string) {
|
||||
return this.findOneBy({ email: email });
|
||||
}
|
||||
|
||||
async findById(userId: string) {
|
||||
return this.findOneBy({ id: userId });
|
||||
}
|
||||
}
|
||||
|
||||
@ -6,32 +6,33 @@ import {
|
||||
Patch,
|
||||
Param,
|
||||
Delete,
|
||||
UseGuards,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Req, UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { UserService } from './user.service';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
import { JwtGuard } from '../auth/guards/JwtGuard';
|
||||
import { FastifyRequest } from 'fastify';
|
||||
import { User } from './entities/user.entity';
|
||||
|
||||
@UseGuards(JwtGuard)
|
||||
@Controller('user')
|
||||
export class UserController {
|
||||
constructor(private readonly userService: UserService) {}
|
||||
|
||||
@Post()
|
||||
create(@Body() createUserDto: CreateUserDto) {
|
||||
return this.userService.create(createUserDto);
|
||||
}
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Get('me')
|
||||
async getUser(@Req() req: FastifyRequest) {
|
||||
const jwtPayload = req['user'];
|
||||
const user: User = await this.userService.findById(jwtPayload.sub);
|
||||
|
||||
@Get(':id')
|
||||
findOne(@Param('id') id: string) {
|
||||
return this.userService.findOne(+id);
|
||||
}
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('Invalid user');
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
|
||||
return this.userService.update(+id, updateUserDto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
remove(@Param('id') id: string) {
|
||||
return this.userService.remove(+id);
|
||||
return { user };
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,10 +3,12 @@ import { UserService } from './user.service';
|
||||
import { UserController } from './user.controller';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { User } from './entities/user.entity';
|
||||
import { UserRepository } from './repositories/user.repository';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([User])],
|
||||
imports: [TypeOrmModule.forFeature([User]), AuthModule],
|
||||
controllers: [UserController],
|
||||
providers: [UserService],
|
||||
providers: [UserService, UserRepository],
|
||||
})
|
||||
export class UserModule {}
|
||||
|
||||
@ -1,30 +1,44 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { User } from './entities/user.entity';
|
||||
import { UserRepository } from './repositories/user.repository';
|
||||
import { plainToClass } from 'class-transformer';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
|
||||
@Injectable()
|
||||
export class UserService {
|
||||
constructor(@InjectRepository(User) private userRepository: UserRepository) {}
|
||||
create(createUserDto: CreateUserDto) {
|
||||
return 'This action adds a new user';
|
||||
constructor(private userRepository: UserRepository) {}
|
||||
async create(createUserDto: CreateUserDto): Promise<User> {
|
||||
const existingUser: User = await this.findByEmail(createUserDto.email);
|
||||
|
||||
if (existingUser) {
|
||||
throw new BadRequestException('A user with this email already exists');
|
||||
}
|
||||
|
||||
const user: User = plainToClass(User, createUserDto);
|
||||
user.locale = 'en';
|
||||
user.lastLoginAt = new Date();
|
||||
|
||||
return this.userRepository.save(user);
|
||||
}
|
||||
|
||||
findAll() {
|
||||
return `This action returns all user`;
|
||||
findById(userId: string) {
|
||||
return this.userRepository.findById(userId);
|
||||
}
|
||||
|
||||
findOne(id: number) {
|
||||
return `This action returns a #${id} user`;
|
||||
async findByEmail(email: string) {
|
||||
return this.userRepository.findByEmail(email);
|
||||
}
|
||||
|
||||
update(id: number, updateUserDto: UpdateUserDto) {
|
||||
return `This action updates a #${id} user`;
|
||||
}
|
||||
|
||||
remove(id: number) {
|
||||
return `This action removes a #${id} user`;
|
||||
async compareHash(
|
||||
plainPassword: string,
|
||||
passwordHash: string,
|
||||
): Promise<boolean> {
|
||||
return await bcrypt.compare(plainPassword, passwordHash);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
import { DataSource } from 'typeorm';
|
||||
import * as dotenv from 'dotenv';
|
||||
dotenv.config();
|
||||
export const AppDataSource = new DataSource({
|
||||
export const AppDataSource: DataSource = new DataSource({
|
||||
type: 'postgres',
|
||||
url:
|
||||
process.env.DATABASE_URL ||
|
||||
'postgresql://postgres:password@localhost:5432/dc?schema=public',
|
||||
entities: ['src/**/*.entity.ts'],
|
||||
entities: ['src/**/*.entity.{ts,js}'],
|
||||
migrations: ['src/**/migrations/*.{ts,js}'],
|
||||
subscribers: [],
|
||||
synchronize: process.env.NODE_ENV === 'development',
|
||||
|
||||
@ -4,6 +4,7 @@ import {
|
||||
FastifyAdapter,
|
||||
NestFastifyApplication,
|
||||
} from '@nestjs/platform-fastify';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create<NestFastifyApplication>(
|
||||
@ -14,6 +15,13 @@ async function bootstrap() {
|
||||
}),
|
||||
);
|
||||
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
stopAtFirstError: true,
|
||||
}),
|
||||
);
|
||||
|
||||
await app.listen(3000);
|
||||
}
|
||||
bootstrap();
|
||||
|
||||
Reference in New Issue
Block a user