mongoose hash password onsave

Solutions on MaxInterview for mongoose hash password onsave by the best coders in the world

showing results for - "mongoose hash password onsave"
Adalyn
28 Feb 2020
1UserSchema.pre('save', function(next) {
2    var user = this;
3
4    // only hash the password if it has been modified (or is new)
5    if (!user.isModified('password')) return next();
6
7    // generate a salt
8    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
9        if (err) return next(err);
10
11        // hash the password using our new salt
12        bcrypt.hash(user.password, salt, function(err, hash) {
13            if (err) return next(err);
14            // override the cleartext password with the hashed one
15            user.password = hash;
16            next();
17        });
18    });
19});
20     
21UserSchema.methods.comparePassword = function(candidatePassword, cb) {
22    bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
23        if (err) return cb(err);
24        cb(null, isMatch);
25    });
26};