[TypeOrm & Nestjs] entity ์์ BeforeInsert ๋ก hash password ๊ตฌํํ๊ธฐ
Nestjs์ TypeORM ์์ ๋น๋ฐ๋ฒํธ๋ฅผ hash ์ฒ๋ฆฌ์ entity ์์ @Beforeinsert, @Beforeupdate ๋ฐ์ฝ๋ ์ดํฐ๋ฅผ ์ฌ์ฉํด ๊ตฌํํ๋ ๋ฐฉ๋ฒ์ ์ ๋ฆฌํฉ๋๋ค.
์๋๋ auth.service.ts ์์ hashPassword ํจ์๋ฅผ ๋ง๋ค์ด์ ์ผ๋๋ฐ, user.service.ts ์์๋ ํด๋น hashPassword ํจ์๋ฅผ ์ฌ์ฉํด์ผ ํ๋ ์ํฉ์ด๋ค. ํด๋น ํจ์ 1๊ฐ ๋๋ฌธ์ user service ๊ฐ Auth service ์ ์์กดํ๊ฒ ํ๋ ๊ฒ์ด ์ซ์ด์, ๋น๋ฐ๋ฒํธ๊ฐ ๋ค์ด์๋ user entity ์ insert ๋ update ๋ฅผ ํ ๋ ๋น๋ฐ๋ฒํธ๋ฅผ ์๋์ผ๋ก Hash ํด์ค ์ ์๋ ๋ฐฉ๋ฒ์ ์ฐพ์๋ณด์๋ค.
๊ธฐ์กด ์ฝ๋
// src/domain/auth/auth.service.ts import * as bcrypt from 'bcrypt' private async hashPassword(password: string): Promise<string> { const salt = await bcrypt.genSalt(); const hashedPassword = await bcrypt.hash(password, salt); return hashedPassword; }
๋ชฉํ
users.entity.ts ์์ @BeforeInsert decorator ๋ฅผ ์ฌ์ฉํด ๋ฐ์ดํฐ๋ฅผ ๋ฃ๊ธฐ์ ์ password ๋ฅผ hash ํ๋ค.
์ฑ๊ณตํ๋ฉด auth.service.ts ์ ๋ง๋ค์๋ hashPassword ํจ์๋ฅผ ์ ๊ฑฐํ๊ณ user service ์ auth service ๊ฐ ์์กด๋๋ ๋ฎ์ถ ์ ์๋ค.
@Entity('users') @Unique(['email', 'provider']) export class Users { private ulid: ULID; constructor() { this.ulid = monotonicFactory(); } @PrimaryColumn({ name: 'user_id', comment: 'Universally Unique Lexicographically Sortable Identifier of user.', }) userId: string; @Column({ comment: 'user email' }) email: string; @Column({ type: 'varchar', comment: 'user password', nullable: true }) password: string; ... @CreateDateColumn({ name: 'created_at', type: 'timestamp with time zone', comment: 'user created date', }) createdAt: Date; @UpdateDateColumn({ name: 'updated_at', type: 'timestamp with time zone', comment: 'user updated date', }) updatedAt: Date; @DeleteDateColumn({ name: 'deleted_at', type: 'timestamp with time zone', comment: 'user deleted date', }) deletedAt: Date; ... @BeforeInsert() generateUlid() { this.userId = this.ulid(); } @BeforeInsert() async hashPassword(): Promise<void> { const salt = await bcrypt.genSalt(); this.password = await bcrypt.hash(this.password, salt); } }
๊ธฐ์กด ์ ์ ์ ๋น๋ฐ๋ฒํธ๋ง ์ ๋ฐ์ดํธ๋ฅผ ํ ๋๋ ๋ฐ์ฝ๋ ์ดํฐ ๋ฐ๊ฟ์ค์ผ ํจ
@BeforeUpdate() async hashPassword(): Promise<void> { const salt = await bcrypt.genSalt(); this.password = await bcrypt.hash(this.password, salt); }
๐ก๐ฉ๐ปโ๐ป๐ฉ๐ปโ๐ป
@BeforeInsert, @BeforeUpdate ๋ TypeORM ์ ๋ฆฌ์ค๋์ด๋ค.
repository.save ๊ฐ ์คํ๋ ๋ ๋ถ๋ ค์ง๋ค.
this.password ๋ save ์ create ๋ฅผ ํตํด ์์ฑ๋ entity instance ์ password ๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
const newUserEntityInstance = this.userRepository.create(newUser) this.userRepository.save(newUserEntityInstance)