๐Ÿ˜Ž ๊ณต๋ถ€ํ•˜๋Š” ์ง•์ง•์•ŒํŒŒ์นด๋Š” ์ฒ˜์Œ์ด์ง€?

[Nest JS ๋กœ CRUD ๊ฒŒ์‹œํŒ ๋งŒ๋“ค๊ธฐ] (25) ๋น„๋ฐ€๋ฒˆํ˜ธ ์•”ํ˜ธํ™” ํ•˜๊ธฐ ๋ณธ๋ฌธ

๐Ÿ‘ฉ‍๐Ÿ’ป ๋ฐฑ์—”๋“œ(Back-End)/Nest js

[Nest JS ๋กœ CRUD ๊ฒŒ์‹œํŒ ๋งŒ๋“ค๊ธฐ] (25) ๋น„๋ฐ€๋ฒˆํ˜ธ ์•”ํ˜ธํ™” ํ•˜๊ธฐ

์ง•์ง•์•ŒํŒŒ์นด 2023. 6. 8. 17:20
728x90
๋ฐ˜์‘ํ˜•

<๋ณธ ๋ธ”๋กœ๊ทธ๋Š” John Ahn ์˜ ์œ ํŠœ๋ธŒ๋ฅผ ์ฐธ๊ณ ํ•ด์„œ ๊ณต๋ถ€ํ•˜๋ฉฐ ์ž‘์„ฑํ•˜์˜€์Šต๋‹ˆ๋‹ค :-)>

=> ๋”ฐ๋ผํ•˜๋ฉด์„œ ๋ฐฐ์šฐ๋Š” NestJS

 

๐Ÿงธ ๋น„๋ฐ€๋ฒˆํ˜ธ ์•”ํ˜ธํ™” ํ•˜๊ธฐ 

์œ ์ €๋ฅผ ์ƒ์„ฑํ•  ๋•Œ ๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ๊ทธ๋Œ€๋กœ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ์ €์žฅ๋จ

๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์•”ํ˜ธํ™”ํ•ด์„œ ์ €์žฅํ•˜๊ธฐ

 

๐ŸŽ€ bcryptjs

bcrypt ๋กœ ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์•”ํ˜ธํ™” ํ•œ ํ›„ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ์ €์žฅํ•˜๊ธฐ

npm install bcryptjs --save

 

๐Ÿงธ ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์ €์žฅํ•˜๋Š” ๋ฐฉ๋ฒ•

1) ์›๋ณธ ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ๊ทธ๋Œ€๋กœ ์ €์žฅ

2) ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์•”ํ˜ธํ™” ํ‚ค์™€ ํ•จ๊ป˜ ์•”ํ˜ธํ™” (์–‘๋ฐฉํ–ฅ)

3) SHA256 ๋“ฑ hash ๋กœ ์•”ํ˜ธํ™”ํ•ด์„œ ์ €์žฅ (๋‹จ๋ฐฉํ–ฅ)

 

๐ŸŽ€ user.repository.ts

import { EntityRepository, Repository } from "typeorm";
import { User } from "./user.entity";
import { AuthCredentialsDto } from "./dto/auth-credential.dto";
import { ConflictException, InternalServerErrorException } from "@nestjs/common";
import * as bcrypt from "bcryptjs";
@EntityRepository(User)
export class UserRepository extends Repository<User> {
    async createUser(authCredentialsDto: AuthCredentialsDto): Promise<void> {
        const { username, password } = authCredentialsDto;

        // bcrypt ๋กœ ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์•”ํ˜ธํ™” ํ•œ ํ›„ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ์ €์žฅํ•˜๊ธฐ
        const salt = await bcrypt.genSalt();
        const hashedPassword = await bcrypt.hash(password, salt);
        const user = this.create({ username, password: hashedPassword});
        
        // ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋ ˆ๋ฒจ์—์„œ ๋งŒ์•ฝ ๊ฐ™์€ ์ด๋ฆ„์„ ๊ฐ€์ง„ ์œ ์ €๊ฐ€ ์žˆ๋‹ค๋ฉด ์—๋Ÿฌ ๋˜์ง€๊ธฐ 
        try {
            await this.save(user);
        } catch (error) {
            if (error.code === "23505") {
                throw new ConflictException("Existing username");
            } else {
                throw new InternalServerErrorException();
            }
        }
    }
}

 

728x90
๋ฐ˜์‘ํ˜•
Comments