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. ๊ฒฐ๊ณผ ๐
- ์ํธํ๋ ๋น๋ฐ๋ฒํธ๊ฐ ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ์ ์ฅ๋๋ ๊ฒ์ ํ์ธํ ์ ์์
โ ๋ฐ๋ผํ๋ฉฐ ๋ฐฐ์ฐ๋ ๋ ธ๋, ๋ฆฌ์กํธ ์๋ฆฌ์ฆ - ๊ธฐ๋ณธ๊ฐ์ ํด๋ก ์ฝ๋ฉ ์ ๋๋ค.
'Backend ๐ > Node.js' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Node] Auth ๊ธฐ๋ฅ, ๋ก๊ทธ์์ ๋ง๋ค๊ธฐ - JWT Vertify (0) | 2024.08.06 |
---|---|
[Node] ๋ก๊ทธ์ธ ๊ธฐ๋ฅ, ํ ํฐ ์์ฑ - Bcrypt, Jsonwebtoken (0) | 2024.08.01 |
[Node] ๋น๋ฐ ์ค์ ์ ๋ณด ๊ด๋ฆฌ (0) | 2024.08.01 |
[Node] BodyParser, PostMan, ํ์ ๊ฐ์ ๊ธฐ๋ฅ (+ Nodemon) (0) | 2024.07.31 |
[Node] GIT ์ค์น, Github ์ฐ๊ฒฐ (0) | 2024.07.31 |