Skip to content

Instantly share code, notes, and snippets.

@fnakstad
Created October 10, 2013 08:05
Show Gist options
  • Save fnakstad/6914738 to your computer and use it in GitHub Desktop.
Save fnakstad/6914738 to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, passport = require('passport')
, bcrypt = require('bcrypt')
, check = require('validator').check
, Validator = require('validator').Validator;
var userSchema = new Schema({
email: { type: String, unique: true, required: true },
salt: { type: String, required: true },
hash: { type: String, required: true }
})
userSchema.virtual('password').get(function() {
return this._password;
}).set(function(password) {
this._password = password;
var salt = this.salt = bcrypt.genSaltSync(10);
this.hash = bcrypt.hashSync(password, salt);
});
userSchema.path("email").validate(function(value) {
try {
check(value).isEmail();
return true;
} catch(e) {
return false;
}
}, 'Invalid email');
// Authentication
userSchema.method('verifyPassword', function(password, callback) {
bcrypt.compare(password, this.hash, callback);
});
userSchema.static('authenticate', function(email, password, callback) {
this.findOne({ email: email }, function(err, user) {
if(err) { return callback(err); }
if(!user) { return callback(null, false); }
user.verifyPassword(password, function(err, passwordCorrect) {
if(err) { return callback(err); }
if(!passwordCorrect) { return callback(null, false); }
return callback(null, user);
})
});
});
module.exports = mongoose.model('User', userSchema);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment