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
import * as bcrypt from 'bcryptjs';
import * as mongoose from 'mongoose';
const userSchema = new mongoose.Schema({
username: String,
email: { type: String, unique: true, lowercase: true, trim: true },
password: String,
role: String
});
// Before saving the user, hash the password
userSchema.pre('save', function(next) {
const user = this;
if (!user.isModified('password')) { return next(); }
bcrypt.genSalt(10, function(err, salt) {
if (err) { return next(err); }
bcrypt.hash(user.password, salt, function(error, hash) {
if (error) { return next(error); }
user.password = hash;
next();
});
});
});
userSchema.methods.comparePassword = function(candidatePassword, callback) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) { return callback(err); }
callback(null, isMatch);
});
};
// Omit the password when returning a user
userSchema.set('toJSON', {
transform: function(doc, ret, options) {
delete ret.password;
return ret;
}
});
const User = mongoose.model('User', userSchema);
export default User;