Node.js - (5) Bcrypt로 비밀번호를 암호화 하기

Apeachicetea·2021년 12월 1일
0

Node.js

목록 보기
4/5

Bcrypt 설치

npm install bcrypt

User.js

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const saltRounds = 10;

const userSchema = mongoose.Schema({
  name: {
    type: String,
    maxlngth: 50
  },
  email: {
    type: String,
    trim: true,
    unique: 1
  },
  password: {
    type: String,
    minlength: 5
  },
  lastname: {
    type: String,
    maxlength: 50
  },
  role: {
    type: Number,
    default: 0
  },
  image: String,
  token: {
    type: String
  },
  tokenExp: {
    type: Number
  }
})

userSchema.pre('save', function(next){
  //비밀번호를 암호화 시킨다. 
  var user = this;
  if(user.isModified('password')){
    bcrypt.genSalt(saltRounds, function(err, salt) {
      if(err) return next(err);
  
      bcrypt.hash(user.password, salt, function(err, hash) {
          // Store hash in your password DB.
          if(err) return next(err)
          user.password = hash
          next();
      });
    });
  }
})

const User = mongoose.model('User', userSchema)
//userSchema를 DB에 User라는 이름의 collection에 등록하라는 뜻

module.exports = { User }


POSTMAN으로 POST 요청 후 데이터 확인해보기

아래와 같이 비밀번호가 암호화 되있는 것을 확인할 수 있다.

profile
웹 프론트엔드 개발자

0개의 댓글