주뇽's 저장소

#7 Bcrypt로 비밀번호 암호화(ReactJS) 본문

웹개발/React

#7 Bcrypt로 비밀번호 암호화(ReactJS)

뎁쭌 2023. 1. 8. 18:49
728x90
반응형

본 정리는 인프런 John Ahn 따라하며 배우는 노드, 리액트 시리즈 - 기본 강의를 참고하였습니다.

현재 비밀번호는 데이터베이스에 그대로 노출되기 때문에 관리해야함

스크린샷 2022-12-28 오후 8 30 54스크린샷 2022-12-27 오후 10 11 49

  • 다음명령어로 bycrypt 설치
  • npm install bcrypt --save

Bycrypt로 비밀번호 암호화 하는 순서

  1. 먼저 Register Route에서 save하기전 (index.js)
  2. 유저 정보들을 데이터 베이스에 저장하기 전 암호화
    1. Salt
      • salt를 생성하고 이용해서 비밀번호를 암호화
    • Models/User.js 파일 수정
      • 전체 코드
      • const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const saltRounds = 10; // 10자리를 이용하여 생성 const userSchema = mongoose.Schema({ name:{ type : String, maxlength : 50, }, email:{ type : String, trim : true, // space를 없애주는 역할 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){ if(err) return next(err) user.password = hash // 암호화된 비밀번호로 교체 next() }) }) } }) const User = mongoose.model('User', userSchema) //스키마를 모델로 감싸줌 module.exports = {User} //다른곳에서 사용할 수 있게 하기위해
    • 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){ if(err) return next(err) user.password = hash // 암호화된 비밀번호로 교체 next() }) }) } else{ next() } })

포스트맨에서 POST 요청 후 데이터베이스에서 확인

암호화가 제대로된걸 확인할 수 있다.

스크린샷 2022-12-27 오후 10 37 02

'웹개발 > React' 카테고리의 다른 글

#8 로그인 기능JWS(ReactJS)  (0) 2023.01.08
#6 비밀 설정 정보 관리(ReactJS)  (0) 2023.01.08
#5 Nodemon 설치(ReactJS)  (0) 2023.01.08