Skip to content

Instantly share code, notes, and snippets.

@artcommacode
Last active August 29, 2015 14:06
Show Gist options
  • Save artcommacode/99ffec5caee45e9554e4 to your computer and use it in GitHub Desktop.
Save artcommacode/99ffec5caee45e9554e4 to your computer and use it in GitHub Desktop.
this.routes.get('/auth/login', function (req, res, next) {
res.render('authentication/views/login', {
controller: 'authentication',
action: 'login'
});
});
this.routes.post('/auth/login', function (req, res, next) {
mongoose.model('User').login(req.body.user, function (error, user) {
if (error) {
req.flash('error', error.message);
res.redirect('back');
} else {
req.session.user = user;
res.redirect('/admin/pages');
}
});
});
this.routes.get('*', function (req, res, next) {
if (req.session && req.session.user) {
res.locals.user = req.session.user;
next();
} else {
req.flash('error', 'Please log in.');
res.redirect('/admin/auth/login');
}
});
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