Skip to content

Instantly share code, notes, and snippets.

@artcommacode
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save artcommacode/99ffec5caee45e9554e4 to your computer and use it in GitHub Desktop.

Select an option

Save artcommacode/99ffec5caee45e9554e4 to your computer and use it in GitHub Desktop.
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, async = require('async')
, _ = require('underscore')
, bcrypt = require('bcrypt');
var UserSchema = new Schema(require('./schema'));
UserSchema.pre('save', function (next) {
var user = this;
if (!user.isModified('password')) return next();
user.encryptPassword(user.password, function (error, hash) {
if (hash) user.password = hash;
next(error);
});
});
UserSchema.methods.authenticate = function (password, callback) {
bcrypt.compare(password, this.password, callback);
};
UserSchema.methods.encryptPassword = function (password, callback) {
bcrypt.genSalt(10, function (error, salt) {
bcrypt.hash(password, salt, callback);
});
};
UserSchema.statics.login = function (user, callback) {
var password = user.password
, User = mongoose.model('User');
async.waterfall([
function (callback) {
User.findOne({email: user.email}, callback);
},
function (returnedUser, callback) {
if (!returnedUser) return callback(new Error('Authentication failed.'));
user = returnedUser;
user.authenticate(password, callback);
},
function (matched, callback) {
if (!matched) return callback(new Error('Authentication failed.'));
user.lastLoggedIn = Date.now();
user.save(callback);
}
], callback);
};
module.exports = mongoose.model('User', UserSchema);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment