-
-
Save jkantr/14c3e0e9277a9b3e36d2ce7244704f5c to your computer and use it in GitHub Desktop.
Login Controller for Express Route
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
const Promise = require('bluebird'); | |
const bcrypt = require('bcrypt'); | |
const User = require('../models/user'); | |
const { LoginError } = require('../errors'); | |
function checkPassword(password, hash) { | |
return Promise.try(() => { | |
return bcrypt.compare(password, hash); | |
}).then((result) => { | |
if (!result) { | |
throw new LoginError('invalid password'); | |
} | |
}) | |
} | |
function authenticateUser(username, password) { | |
return Promise.try(() => { | |
// this will return a single object, not an array. it will also throw if the username is invalid | |
return User.findOne({ username }); | |
}).tap((user) => { | |
return checkPassword(password, user.password); | |
}).then((user) => { | |
// return something actually related to the user here? | |
}) | |
} | |
function login(req, res, next) { | |
const { username, password } = req.body; | |
Promise.try(() => { | |
return authenticateUser(username, password); | |
}).then((user) => { | |
res.json({ | |
message: 'successful login', | |
/* add some user data? */ | |
}); | |
}).catch(InvalidLogin, (err) => { // catches only instances of InvalidLogin | |
return res.status(403).json({ message: 'invalid login' }); | |
}).catch(next); // everything else goes to global error handler | |
} | |
module.exports = login; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment