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.

Revisions

  1. Ryan revised this gist Sep 26, 2014. 2 changed files with 28 additions and 0 deletions.
    File renamed without changes.
    28 changes: 28 additions & 0 deletions auth.js
    Original 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');
    }
    });
  2. Ryan created this gist Sep 26, 2014.
    49 changes: 49 additions & 0 deletions gistfile1.js
    Original 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);