본문 바로가기

Nest JS - 회원 API 구현 (hashing & ConflictException) 본문

개발/nest.js

Nest JS - 회원 API 구현 (hashing & ConflictException)

자전하는명왕성 2023. 2. 10. 00:14

미래의 나에게

bcrypt 라이브러리 설치

yarn add bcrypt
yarn add --dev @types/bcrypt

이번 포스팅에서는 이전에 포스팅했던 product API 구현과 다른 부분에 대해 다룬다. 

 

Create //  Hashing & ConflictException 

// users.service.ts

async create({ createUserInput }: IUsersServiceCreate): Promise<User> {
    const { password, email, ...rest } = createUserInput;
    const user = await this.findOneByEmail({ email });
    if (user) throw new ConflictException('이미 등록된 이메일입니다.'); // 콘플릭트익셉션

    const hashedPassword = await bcrypt.hash(password, 10); // 해싱

    const result = await this.usersRepository.save({
      ...rest,
      password: hashedPassword,
      email,
    });
    console.log(result);
    return result;
  }

로직에 대해 설명하면, 먼저 createUserInput 값을 받아온 뒤, 구조분해할당으로 이메일 값의 유무를 확인한다.

 

ConflictException

이때 ConflictException 을 던져주는데, 이는 상태코드와 메시지를 반환해주는 기능이다.

다음은 아래와 같이 구현했다.

// filter.ts
import { Catch, ExceptionFilter, HttpException } from '@nestjs/common';

@Catch(HttpException) // @Catch 활용
export class HttpExceptionFilter implements ExceptionFilter { // nest 내 기능
  catch(exception: HttpException) {
    const status = exception.getStatus(); // 예외 코드
    const message = exception.message; // 예외 내용

    console.log('===================================');
    console.log('😤 예외가 발생했습니다. 😤');
    console.log('예외 내용 :', message);
    console.log('예외 코드 :', status);
    console.log('===================================');
  }
}

// main.ts
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './commons/filter/http-exception.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalFilters(new HttpExceptionFilter()); // 추가한 부분 //
  await app.listen(3000);
}
bootstrap();

 

Hashing (해싱)

해싱은 비밀번호와 같은 중요 정보를 암호화하는 과정이다.

해싱 과정에 Salt 과정이 들어가는데,

이 부분에서 복호화를 어렵게 하기 위한 과정이 추가된다.

해싱은 bcrypt 라이브러리를 통해 이루어지며

bcrypt.hash('암호화할 변수', 해싱할 횟수) 가 들어간다.

2023.02.05 - [코딩/알쓸코잡] - 암호화 (단방향, 양방향)

 

 

생성 및 ConflictException 산출 이미지

 

비밀번호의 경우는, API 를 통해 노출시킬 이유가 없기 때문에,

플레이그라운드에서는 나타나지 않게 하였다.

해싱하여 DB에 저장한 결과

Comments