-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuser.js
50 lines (45 loc) · 1.23 KB
/
user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
const userSchema = new mongoose.Schema({
username: String,
password: String,
email: String,
gender: String,
address: String,
sessions: [{type: mongoose.Schema.Types.ObjectId, ref: 'Session'}]
});
// Before saving the user, hash the password
userSchema.pre('save', function (next) {
const user = this;
if (!user.isModified('password')) {
return next();
}
bcrypt.genSalt(10, (err, salt) => {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, (error, hash) => {
if (error) {
return next(error);
}
user.password = hash;
next();
});
});
});
userSchema.methods.comparePassword = function (candidatePassword, callback) {
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
if (err) {
return callback(err);
}
callback(null, isMatch);
});
};
// Omit the password when returning a user
userSchema.set('toJSON', {
transform: (doc, ret, options) => {
delete ret.password;
return ret;
}
});
module.exports = mongoose.model('User', userSchema);