Skip to content

Instantly share code, notes, and snippets.

@joepie91

joepie91/.js Secret

Created October 7, 2015 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joepie91/71ad72d16233d4e6075f to your computer and use it in GitHub Desktop.
Save joepie91/71ad72d16233d4e6075f to your computer and use it in GitHub Desktop.
var expressPromiseRouter = require("express-promise-router");
var router = expressPromiseRouter();
var Promise = require("bluebird");
function authenticate(email, password) {
return Promise.try(function() {
return knex('users').where('email', email);
}).then(function(rows) {
if (rows.length === 0) {
throw new Error('cannot find user');
}
var user = rows[0];
return Promise.try(function() {
return scrypt.verifyHash(password, user.password);
}).then(function(valid) {
// valid is always true, if we get to this point.
return user;
});
});
}
router.post('/login', function (req, res) {
return Promise.try(function() {
return authenticate(req.body.email, req.body.password);
})
.then(function(user) {
// Regenerate session when signing in
// to prevent fixation
req.session.regenerate(function () {
// Store the user's primary key
// in the session store to be retrieved,
// or in this case the entire user object
req.session.user = user;
req.session.success = 'Login successful!';
res.redirect('/cards');
});
})
.catch(scrypt.PasswordError, function(error) {
req.session.error = 'Authentication failed, please check your username and password.';
res.redirect('/login');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment