Skip to content

Instantly share code, notes, and snippets.

@danielkhan
Created June 6, 2018 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielkhan/266c52f0f437a908847fb1049b36d9e9 to your computer and use it in GitHub Desktop.
Save danielkhan/266c52f0f437a908847fb1049b36d9e9 to your computer and use it in GitHub Desktop.
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