๐ ๊ณต๋ถํ๋ ์ง์ง์ํ์นด๋ ์ฒ์์ด์ง?
[Nest JS ๋ก CRUD ๊ฒ์ํ ๋ง๋ค๊ธฐ] (25) ๋น๋ฐ๋ฒํธ ์ํธํ ํ๊ธฐ ๋ณธ๋ฌธ
๐ฉ๐ป ๋ฐฑ์๋(Back-End)/Nest js
[Nest JS ๋ก CRUD ๊ฒ์ํ ๋ง๋ค๊ธฐ] (25) ๋น๋ฐ๋ฒํธ ์ํธํ ํ๊ธฐ
์ง์ง์ํ์นด 2023. 6. 8. 17:20728x90
๋ฐ์ํ
<๋ณธ ๋ธ๋ก๊ทธ๋ 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
๋ฐ์ํ
'๐ฉโ๐ป ๋ฐฑ์๋(Back-End) > Nest js' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Comments