Skip to content

Instantly share code, notes, and snippets.

@cristopher-rodrigues
Last active October 28, 2015 20:04
Show Gist options
  • Select an option

  • Save cristopher-rodrigues/f8685751f2d7c95966db to your computer and use it in GitHub Desktop.

Select an option

Save cristopher-rodrigues/f8685751f2d7c95966db to your computer and use it in GitHub Desktop.
user model mongoose with password
var mongoose = require("mongoose"),
Schema = mongoose.Schema,
bcrypt = require("bcrypt"),
SALT_WORK_FACTOR = 10;
var UserSchema = new Schema({
username: { type: String, required: true, index: { unique: true } },
password: { type: String, required: true }
});
UserSchema.pre(save, function(next) {
var user = this;
if (!user.isModified('password')) return next();
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment