Created
September 15, 2020 00:41
-
-
Save conorbarclay/1562c2573ee096c72a84719b7ac2c4ca to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Middleware to check a user token | |
* @param {Object} req Express request object | |
* @param {Object} res Express response object | |
* @param {Function} next Express response object | |
*/ | |
function authCheck(req, res, next) { | |
const token = req.signedCookies.token | |
if (token && token !== 'null') { | |
jwt.verify(token, jwtSecret, (err) => { | |
if (err) { | |
res.statusCode = 401 | |
res.send({error: 'invalidAuth', errorMessage: 'Invalid authentication'}) | |
} else { | |
next() | |
} | |
}) | |
} else { | |
res.statusCode = 401 | |
res.send({error: 'missingAuth', errorMessage: 'Missing authentication'}) | |
} | |
} |
This file contains hidden or 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
/** | |
* Check an email and password against DB | |
* @param {Object} req Express request object | |
* @param {Object} res Express response object | |
*/ | |
function login(req, res) { | |
let {email, password} = req.body | |
email = email.toLowerCase() | |
if (email && password) { | |
User.find({where: {email}, plain: true}) | |
.then(dbUser => { | |
if (dbUser) { | |
argon2.verify(dbUser.passwordHash, password) | |
.then(success => { | |
if (success) { | |
let token = jwt.sign({ | |
data: {authed: true}, | |
exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24), // Signin is valid for 24 hours | |
}, jwtSecret) | |
res.cookie('token', token, { | |
httpOnly: true, | |
secure: true, | |
}) | |
res.send({success: true}) | |
} else { | |
res.statusCode = 401 | |
res.send({error: 'loginBadPassword', errorMessage: 'Incorrect Password'}) | |
} | |
}) | |
.catch(err => { | |
console.error(err) | |
res.statusCode = 500 | |
res.send({error: 'loginHashVerifyUnkown', errorMessage: 'Unkown error attempting login'}) | |
}) | |
} else { | |
res.statusCode = 400 | |
res.send({error: 'loginNoUser', errorMessage: 'That email is not associated with an account'}) | |
} | |
}) | |
.catch(({errors}) => { | |
console.error(errors) | |
res.statusCode = 500 | |
res.send({error: 'loginUnkown', errorMessage: 'Unkown error attempting login'}) | |
}) | |
} else { | |
res.statusCode = 400 | |
res.send({error: 'loginMissingParams', errorMessage: 'Missing required email or password'}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment