$ npm install --save @nestjs/passport passport passport-local
$ npm install --save-dev @types/passport-local
$ nest g module auth
$ nest g service auth
import { forwardRef, Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { UsersModule } from '../users/users.module';
import { JwtModule } from '@nestjs/jwt';
import { JwtStrategy } from './jwt/jwt.strategy';
@Module({
imports: [
//* JwtService를 사용하기위해서 import 해준다.
JwtModule.register({
secret: process.env.SECRET_KEY,
signOptions: { expiresIn: '1y' },
}),
forwardRef(() => UsersModule),
],
providers: [AuthService, JwtStrategy],
exports: [AuthService],
})
export class AuthModule {}
export class UsersController {
constructor(
private readonly userService: UsersService,
private readonly authService: AuthService,
) {}
@Post('login')
async logIn(@Body() userLoginDTO: UserLogInDTO) {
console.log(userLoginDTO);
return await this.authService.verifyUser(userLoginDTO);
}
}
@Injectable()
export class AuthService {
constructor(
private userService: UsersService,
private jwtService: JwtService,
) {}
async verifyUser(userLoginDto: UserLogInDTO) {
const { email, password } = userLoginDto;
//* 해당하는 email이 있는가
const user = await this.userService.findUserByEmail(email);
if (!user) {
throw new UnauthorizedException('이메일과 비밀번호를 확인해주세요');
}
//* password 일치하는가
const isPasswordValidated: boolean = await bcrypt.compare(
password,
user.password,
);
if (!isPasswordValidated) {
throw new UnauthorizedException('이메일과 비밀번호를 확인해주세요.');
}
const payload = { email: email, sub: user.id };
return {
token: this.jwtService.sign(payload),
};
}
}
https://jwt.io/ 에서 확인 가능하다.
https://docs.nestjs.com/security/authentication#jwt-functionality