Skip to content

Instantly share code, notes, and snippets.

@zacharyhill
Created January 22, 2018 22:58
Show Gist options
  • Save zacharyhill/a80f11210989177ea199e00d881f56c3 to your computer and use it in GitHub Desktop.
Save zacharyhill/a80f11210989177ea199e00d881f56c3 to your computer and use it in GitHub Desktop.
Login Controller for Express Route
const bcrypt = require('bcrypt');
// const jwt = require('jsonwebtoken');
const User = require('../models/user');
async function authenticateUser(username, password) {
const users = await User.find({ username });
if (users.length) {
const user = users[0];
const samePassword = await checkPassword(password, user.password);
return samePassword;
}
else {
throw new Error('incorrect username');
}
}
async function checkPassword(password, hash) {
const result = await bcrypt.compare(password, hash);
return result;
}
async function login(req, res) {
/*
** below we authenticate our user before sending them a token
*/
const user = {
username: req.body.username,
password: req.body.password,
};
const authenticated = await authenticateUser(user.username, user.password);
res.json({
message: 'check console',
authenticated,
});
}
module.exports = login;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment