mirror of
https://github.com/docmost/docmost.git
synced 2025-11-25 01:41:12 +10:00
implement jwt auth
This commit is contained in:
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user