[Inflearn][JohnAhn] 노드 리액트 기초 (10)

ann·2023년 11월 1일
0
  • schema로 mongodb에 받은 password 암호화 하기

    1. npm install bcrypt --save 설치
    index.js=============================
    app.post('/register', (req, res) => {
      const user = new User(req.body)
    
      user
        .save() 
        // 세이브로 넘어가기 전에 models/User.js의 userSchema.pre 코드가 실행 됨
        .then(() => {
            res.status(200).json({
                success: true
            })
        })
        .catch((err) => {
            res.json({
                success: false, err
            })
        })
    })
    models/User.js==========================
    userSchema.pre('save', function( next ) {
    // save 전에 실행되고, next 호출되면 index.js의 save 이어서 수행
        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() // index.js의 register Router의 save로 돌아감
                })
            })
        } else {
            next()
        }
    })

    (bcrypt 공식문서 링크텍스트)

    • 이때 models/User.js의 userSchema.pre 안의 bcrypt는 const bcrypt = require('bcrypt')로 불러와야 하고, bcrypt는 특정 길이의 salt를 생성하고 그 salt로 password를 암호화 시키는 것임. 따라서 const saltRounds = 10가 필요함.
    • if(user.isModified('password'))가 있는 이유는, 정보를 변경하는 것이 name이나 email일 수도 있는데 그때마다 password도 바뀌기 때문에, password를 바꿀 때만 bcrypt가 실행되도록 함.

0개의 댓글