Nest.js - JWT

김세겸·2023년 3월 7일
0

NestJS

목록 보기
15/18
post-thumbnail

1. 설치

$ npm install --save @nestjs/jwt passport-jwt
$ npm install --save-dev @types/passport-jwt

2. 적용

1. jwt module 등록

import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { AuthService } from './auth.service';

@Module({
  imports: [
    JwtModule.register({
      secret: process.env.JWT_SECRET,
      signOptions: { expiresIn: '1y' },
    }),
  ],
  providers: [AuthService],
  exports: [AuthService]
})
export class AuthModule {}

2. auth.service.ts

import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';
import { User } from 'src/users/users.entity';
import { UsersRepository } from 'src/users/users.repository';
import { LoginDto } from './dto/login.dto';

@Injectable()
export class AuthService {
    constructor(
        private jwtService: JwtService,
        private readonly usersRepository: UsersRepository
    ){}

    async jwtLogIn(dto: LoginDto) {
        const {email, password} = dto;

        const user: User = await this.usersRepository.findUserByEmail(email);
        console.log(user);
        
        if(!user) {
            throw new UnauthorizedException('이메일과 비밀번호를 확인해주세요.');
        }

        const isPasswordValidated: boolean = await bcrypt.compare(password, user.password);
        console.log(isPasswordValidated);
        
        if(!isPasswordValidated) {
            throw new UnauthorizedException('이메일과 비밀번호를 확인해주세요.');
        }
        const payload = {
            email: email, sub: user.id, user_type: user.user_type
        }
        return {access_token: this.jwtService.sign(payload)}
    }
}

3. 순환종속성 해결

현재 user.module가 auth.module를 import하고 auth.module이 user.module을 import하고 있어서 순환종속성에 걸려 "Nest cannot create the module instance"에러를 내고 있다.
Nest.js공식문서에 따르면 forwardRef()를 사용하라고 나와있다.

// auth.module
@Module({
  imports: [
    JwtModule.register({
      secret: process.env.JWT_SECRET,
      signOptions: { expiresIn: '1y' },
    }),
    forwardRef(() => UsersModule)
  ],
  providers: [AuthService],
  exports: [AuthService]
})
export class AuthModule {}

//users.module
@Module({
  imports: [TypeOrmModule.forFeature([User]), EmailModule, forwardRef(() => AuthModule)],
  providers: [UsersService, UsersRepository],
  controllers: [UsersController],
  exports: [UsersRepository]
})

0개의 댓글