Created
May 2, 2017 01:47
-
-
Save roshanca/2a752795f9b850eb8a8c6519a4921a15 to your computer and use it in GitHub Desktop.
Handle user's authentication with token
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
const bcrypt = require('bcrypt') | |
const jwt = require('jsonwebtoken') | |
const config = require('../config/security') | |
function hashPassword(password) { | |
return new Promise((resolve, reject) => { | |
bcrypt.genSalt(config.saltRounds) | |
.then(salt => { | |
return bcrypt.hash(password, salt) | |
}) | |
.then(resolve) | |
.catch(reject) | |
}) | |
} | |
function getSessionToken(user) { | |
return new Promise((resolve, reject) => { | |
const payload = { | |
sub: user.email, | |
role: user.role | |
} | |
jwt.sign( | |
payload, | |
config.secret, | |
{ expiresIn: config.sessionExpiresIn }, | |
function callback(err, token) { | |
if (err) { | |
reject(err) | |
return | |
} | |
resolve(token) | |
} | |
) | |
}) | |
} | |
function authenticate(role) { | |
return function (req, res, next) { | |
if (!req.headers.authorization) { | |
res.status(401).json({ message: 'You are not authorized' }) | |
return | |
} | |
const token = req.headers.authorization | |
jwt.verify(token, config.secret, function callback(err, payload) { | |
if (err) { | |
if (err.name === 'TokenExpiredError') { | |
res.status(401).json({ message: 'Token Expired' }) | |
} else { | |
res.status(401).json({ message: 'Authentication failed' }) | |
} | |
return | |
} | |
if (!role || role === payload.role) { | |
// pass some user details through in case they are needed | |
req.user = { | |
email: payload.sub, | |
role: payload.role | |
} | |
next() | |
} else { | |
res.status(401).send({ message: 'You are not authorized' }) | |
} | |
}) | |
} | |
} | |
module.exports = { | |
hashPassword, | |
validatePassword: bcrypt.compare, | |
getSessionToken, | |
authenticate | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment