Skip to content

Instantly share code, notes, and snippets.

@mphuget
Created March 5, 2020 09:20
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 mphuget/9cff85bbaf6e0b09ed55e8527f2e2e53 to your computer and use it in GitHub Desktop.
Save mphuget/9cff85bbaf6e0b09ed55e8527f2e2e53 to your computer and use it in GitHub Desktop.
pre function for UserSchema
// Hash the password before we even save it to the database
UserSchema.pre('save', function(next) {
let user = this;
if (!user.isModified('local.password'))
return next();
bcrypt.genSalt(10, function(err, salt) {
if (err)
return next(err);
bcrypt.hash(user.local.password, salt, null, function(err, hash) {
if (err)
return next(err);
user.local.password = hash;
next();
});
});
})
// compare password in the database and the one that the user type in
UserSchema.methods.comparePassword = function(password) {
let user = this;
return bcrypt.compareSync(password, user.local.password);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment