Backend ๐Ÿ“š/Node.js

[Node] ๋น„๋ฐ€๋ฒˆํ˜ธ ์•”ํ˜ธํ™” - Bcrypt

leejaejae 2024. 8. 1. 15:06

0. ๋“ค์–ด๊ฐ€๊ธฐ ์•ž์„œ!

- ํ˜„์žฌ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ์ €์žฅ๋œ ๋น„๋ฐ€๋ฒˆํ˜ธ๋Š” ๋„ˆ๋ฌด ์•ˆ์ „ํ•˜์ง€ ์•Š์Œ
- ๊ทธ๋ž˜์„œ Bcrypt๋ฅผ ์‹œ์šฉํ•ด ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์•”ํ˜ธํ™”ํ•ด์„œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ์ €์žฅํ•ด์•ผํ•จ

 

1. Bcrypt ๋‹ค์šด๋ฐ›๊ธฐ

npm install bcrypt --save

 

2. User.js ์ˆ˜์ •

1) ์•”ํ˜ธํ™” ํ•  ํƒ€์ด๋ฐ

// index.js

...
app.post('/register', async (req, res) => {
  const user = new User(req.body)

  // save ์ „์— ๋น„๋ฐ€๋ฒˆํ˜ธ ์•”ํ˜ธํ™”

  const result = await user.save().then(()=>{
    res.status(200).json({
      success: true
    })
  }).catch((err)=>{
    res.json({ success: false, err })
  })
})
...

- ์œ ์ € ์ •๋ณด๋“ค(Account, Password ๋“ฑ๋“ฑ)์„ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ์ €์žฅํ•˜๊ธฐ ์ „์— ์•”ํ˜ธํ™”ํ•ด์•ผ ํ•จ!


2) User.js ์ˆ˜์ •

// User.js

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');  // ๋‹ค์šด ๋ฐ›์€ bcrypt ๋ถˆ๋Ÿฌ์˜ค๊ธฐ
const saltRounds = 10;  // salt ๊ธ€์ž ์ˆ˜


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: Number
    }, 
    tokenExp: {  
        type: Number
    }
})

userSchema.pre('save', function(next) {  // userModel์— user์ •๋ณด๋ฅผ ์ €์žฅํ•˜๊ธฐ ์ „์— ์ฒ˜๋ฆฌ๋จ
    var user = this;
    
    if(user.isModified('password')){  // password๊ฐ€ ๋ณ€ํ™˜๋  ๋•Œ๋งŒ ์•”ํ˜ธํ™”
        // ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์•”ํ˜ธํ™” ์‹œํ‚ค๊ธฐ
        bcrypt.genSalt(saltRounds, function(err, salt){  // salt ๋งŒ๋“ค๊ธฐ
            if(err) return next(err)

            bcrypt.hash(user.password, salt, function(err, hash) {  
                if(err) return next(err)
                user.password = hash  // ์•”ํ˜ธํ™” ํ‚ค ๋งŒ๋“œ๋Š” ๋ฐ ์„ฑ๊ณตํ–ˆ์œผ๋ฉด, ์›๋ž˜ ๋น„๋ฐ€๋ฒˆํ˜ธ๋ž‘ hash ๋ฐ”๊พธ๊ณ 
                next()  // index.js๋กœ ๋Œ์•„๊ฐ€๊ธฐ
            })
        })
    } else {  // ๋น„๋ฐ€๋ฒˆํ˜ธ ๋ง๊ณ  ๋‹ค๋ฅธ ๊ฑธ ๋ฐ”๊ฟ€ ๊ฒฝ์šฐ
        next()  // next() ์—†์œผ๋ฉด ๊ณ„์† ๋จธ๋ฌผ๊ฒŒ ๋จ
    }
})  



const User = mongoose.model('User', userSchema)  

module.exports = { User }

- salt ์ด์šฉํ•ด์„œ hash password(์•”ํ˜ธํ™”๋œ ๋น„๋ฐ€๋ฒˆํ˜ธ) ๋งŒ๋“ค๊ณ 
- ๋น„๋ฐ€๋ฒˆํ˜ธ ๋ฐ”๊ฟ€ ๋•Œ๋งŒ ์ž‘๋™ํ•  ์ˆ˜ ์žˆ๊ฒŒ ์กฐ๊ฑด ๊ฑธ์–ด์คŒ

 

3. ๊ฒฐ๊ณผ ๐ŸŽ‰

 

- ์•”ํ˜ธํ™”๋œ ๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ์ €์žฅ๋˜๋Š” ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Œ


โ˜… ๋”ฐ๋ผํ•˜๋ฉฐ ๋ฐฐ์šฐ๋Š” ๋…ธ๋“œ, ๋ฆฌ์•กํŠธ ์‹œ๋ฆฌ์ฆˆ - ๊ธฐ๋ณธ๊ฐ•์˜ ํด๋ก ์ฝ”๋”ฉ ์ž…๋‹ˆ๋‹ค.