ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Bcrypt를 이용한 비밀번호 암호화
    Study/Node, React 기초 강의_John Ahn 2023. 2. 19. 01:24

    데이터베이스 관리자도 회원의 비밀번호를 모르게 하기 위해 Bcrypt를 사용한다.

     

    Bcrypt 설치

    npm install bcrypt --save

     

     

    Bcrypt을 이용한 암호화

    Bcrypt를 이용하여 암호화하기 위해 User.js에 userSchema.pref를 구현한다.

    userSchema.pre는 index.js의 app.post에서 user.save가 실행되기 전에 실행된다.

     

    < User.js >

    // mongoose를 요청함
    const mongoose = require('mongoose');
    
    // bcrypt를 요청
    const bcrypt = require('bcrypt');
    
    // Salt를 이용해서 비밀번호를 암호화 해야하기 때문에 saltRounds를 설정
    const saltRounds = 10
    
    // Schema 설정
    const userSchema = mongoose.Schema({
        name: {
            type: String,
            maxlength: 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
        }
    })
    
    // user 정보를 저장하기전에 비밀번호를 암호화시킨다.
    userSchema.pre('save', function (next) {
        // userSchema를 가져옴
        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()
                })
            })
        }
    })
    
    
    // Schema를 모듈로 감싸 줌
    const User = mongoose.model('User', userSchema)
    
    // 모듈을 다른 곳에서도 사용할 수 있도록 하는 코드
    module.exports = { User }

     

    TEST

    PostMan에 데이터를 입력한다.

     

     

    mongodb에서 결과를 확인한다.

     

    < 결과 >

    'Study > Node, React 기초 강의_John Ahn' 카테고리의 다른 글

    토큰 생성  (0) 2023.02.19
    로그인 기능 구현  (0) 2023.02.19
    비밀 설정 정보 관리  (0) 2023.02.19
    Nodemon  (0) 2023.02.14
    BodyParser & PostMan & 회원 가입 기능  (0) 2023.02.13
Designed by Tistory.