Skip to content

Instantly share code, notes, and snippets.

@arekgotfryd
Created February 28, 2018 21:18
Show Gist options
  • Save arekgotfryd/b7d096edf71f1e006b446f4a206bf757 to your computer and use it in GitHub Desktop.
Save arekgotfryd/b7d096edf71f1e006b446f4a206bf757 to your computer and use it in GitHub Desktop.
UserSchema.pre("save", function(next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified("password")) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
next();
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment