본문 바로가기
프로젝트/유튜브 클론코딩

user authentication 1: hash

by 두 그루 2023. 2. 20.

mongodb와 mongoose를 이용해서 User model을 만들고, join 페이지에서 필요 정보를 전달받아 User를 create했다.

터미널을 이용해 저장된 user collection을 확인하면 위처럼 정보를 확인할 수 있다. 하지만 사진처럼 사용자의 비밀번호가 드러나면 안되니 hashing을 이용할 필요가 있다.

 

npm에서 설치 가능한 bcrypt를 이용해서 hashing하는 방법을 기록한다. 아래 링크를 참고하면 된다.

https://www.npmjs.com/package/bcrypt

 

bcrypt

A bcrypt library for NodeJS.. Latest version: 5.1.0, last published: 4 months ago. Start using bcrypt in your project by running `npm i bcrypt`. There are 3754 other projects in the npm registry using bcrypt.

www.npmjs.com

 

먼저, bcrypt를 이용할 프로젝트에서 bcrypt를 설치한다. (node.js + npm 기준)

npm i bcrypt

 

다음으로, User model(예시)을 저장할 때 hashing할 것이니 아래와 같이 import > hashing한다.

import bcrypt from "bcrypt";
import mongoose from "mongoose";

const userSchema = mongoose.Schema({
  email: { type: String, required: true, unique: true },
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  name: { type: String, required: true },
  location: String,
});

userSchema.pre("save", async function () {
  this.password = await bcrypt.hash(this.password, 5);
});

const User = mongoose.model("User", userSchema);

export default User;

코드를 더 자세히 설명하자면, mongoose를 이용해 User.js 파일을 만들어 User 모델을 만들었다. User 모델이 저장되기 전에 비밀번호를 hashing하도록 pre 메소드를 이용했다. 그리고 bcrypt를 통해 입력받은 비밀번호를 5번 hashing하고, 그 값으로 비밀번호를 대체했다.

 

예시로 hash 전의 비밀번호와 후의 비밀번호를 terminal에 출력하여 확인했을 땐 다음과 같은 값이 나왔다.

 

 

 

save 이전 실행 메소드

https://soaringwave.tistory.com/69

github 소스 코드

https://github.com/soaringwave/wetube/commit/ead09c02a0e14b61be3560920cd7bad8f32112e3

댓글