Last active
August 29, 2015 14:06
-
-
Save artcommacode/99ffec5caee45e9554e4 to your computer and use it in GitHub Desktop.
Revisions
-
Ryan revised this gist
Sep 26, 2014 . 2 changed files with 28 additions and 0 deletions.There are no files selected for viewing
File renamed without changes.This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,28 @@ 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'); } }); -
Ryan created this gist
Sep 26, 2014 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,49 @@ 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);