-
-
Save joepie91/71ad72d16233d4e6075f to your computer and use it in GitHub Desktop.
This file contains 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 characters
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