1.创建sign-in.dto.ts
同样的,定义sign-in的数据类型:
import { IsEmail, IsString, MinLength } from 'class-validator';
export class SignInDto {
@IsEmail()
email: string;
@IsString()
@MinLength(6)
password: string;
}
2.在auth.service.ts中实现登录的逻辑
async signIn(email: string, pass: string): Promise<any> {
const user = await this.usersService.findOne(email);
if (!user) {
throw new NotFoundException('User not found');
}
const isPasswordValid = await bcrypt.compare(pass, user.password);
if (!isPasswordValid) {
throw new UnauthorizedException('Invalid credentials');
}
const { password, ...result } = user;
return result;
}
注意,同样的这里最后的返回值应当是jwt鉴权后的token,这里暂且搁置。
3.在auth.controller.ts中将路由和登录逻辑匹配
@Post('login')
SignIn(@Body() signInDto: SignInDto) {
return this.authService.signIn(signInDto.email, signInDto.password);
}