Skip to content

Instantly share code, notes, and snippets.

@artcommacode
Created July 29, 2014 22:07
Show Gist options
  • Save artcommacode/81fbb870154f0accbb31 to your computer and use it in GitHub Desktop.
Save artcommacode/81fbb870154f0accbb31 to your computer and use it in GitHub Desktop.
sUser.pre('save', function (next) {
var self = this
, now = Date.now()
this.updatedAt = now
if (this.isNew) this.createdAt = now
if (!this.isModified('password')) return next();
co(function *() {
self.password = yield self.encryptPassword(self.password)
next()
})()
})
sUser.methods.encryptPassword = function *(password) {
var salt = yield thunkify(bcrypt.genSalt)(10)
return yield thunkify(bcrypt.hash)(password, salt, null)
}
@artcommacode
Copy link
Author

UserSchema.pre('save', function (next) {
  var user = this;
  user.updatedAt = Date.now();
  if (user.isNew) user.createdAt = Date.now();
  if (!user.isModified('password')) return next();
  user.encryptPassword(user.password, function (error, hash) {
    if (hash) user.password = hash;
    next(error);
  });
});

UserSchema.methods.encryptPassword = function (password, callback) {
  bcrypt.genSalt(10, function (error, salt) {
    bcrypt.hash(password, salt, callback);
  });
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment