Showing
3 changed files
with
24 additions
and
0 deletions
1 | const mongoose = require('mongoose'); | 1 | const mongoose = require('mongoose'); |
2 | +const bcrypt = require('bcrypt'); | ||
3 | +const saltRounds = 10; | ||
2 | const userSchema = mongoose.Schema({ | 4 | const userSchema = mongoose.Schema({ |
3 | name : { | 5 | name : { |
4 | type : String, | 6 | type : String, |
... | @@ -31,6 +33,27 @@ const userSchema = mongoose.Schema({ | ... | @@ -31,6 +33,27 @@ const userSchema = mongoose.Schema({ |
31 | 33 | ||
32 | }) | 34 | }) |
33 | 35 | ||
36 | +// password 암호화 | ||
37 | +userSchema.pre('save', function(next){ | ||
38 | + var user = this; | ||
39 | + | ||
40 | + if(user.isModified('password')){ | ||
41 | + | ||
42 | + bcrypt.genSalt(saltRounds, function(err, salt){ | ||
43 | + if(err)return next(err) | ||
44 | + | ||
45 | + bcrypt.hash(user.password, salt, function(err, hash){ | ||
46 | + if(err) return next(err) | ||
47 | + user.password = hash | ||
48 | + //hash 값으로 변경해서 저장 | ||
49 | + next() | ||
50 | + }) | ||
51 | + }) | ||
52 | + } | ||
53 | + | ||
54 | +}) | ||
55 | + | ||
56 | + | ||
34 | const User = mongoose.model('Users', userSchema) | 57 | const User = mongoose.model('Users', userSchema) |
35 | 58 | ||
36 | 59 | ... | ... |
This diff is collapsed. Click to expand it.
... | @@ -15,6 +15,7 @@ | ... | @@ -15,6 +15,7 @@ |
15 | "author": "seungho", | 15 | "author": "seungho", |
16 | "license": "ISC", | 16 | "license": "ISC", |
17 | "dependencies": { | 17 | "dependencies": { |
18 | + "bcrypt": "^4.0.1", | ||
18 | "body-parser": "^1.19.0", | 19 | "body-parser": "^1.19.0", |
19 | "express": "^4.17.1", | 20 | "express": "^4.17.1", |
20 | "mongoose": "^5.9.15" | 21 | "mongoose": "^5.9.15" | ... | ... |
-
Please register or login to post a comment