Created
June 6, 2018 13:40
-
-
Save danielkhan/266c52f0f437a908847fb1049b36d9e9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
UserSchema.pre('save', function preSave(next) { | |
const user = this; | |
// only hash the password if it has been modified (or is new) | |
if (!user.isModified('password')) return next(); | |
// generate a salt | |
return bcrypt.genSalt(10, (err, salt) => { | |
if (err) return next(err); | |
// hash the password using our new salt | |
return bcrypt.hash(user.password, salt, (hasherr, hash) => { | |
if (hasherr) return next(hasherr); | |
// override the cleartext password with the hashed one | |
user.password = hash; | |
return next(); | |
}); | |
}); | |
}); | |
UserSchema.methods.comparePassword = function comparePassword(candidatePassword) { | |
return bcrypt.compare(candidatePassword, this.password); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment