Last active
May 24, 2019 11:24
-
-
Save sueleybyte/64d119dc87c4c665b0bfb2f20289e64c to your computer and use it in GitHub Desktop.
Middleware for checking JWT
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 jwt = require("jsonwebtoken"); | |
/** | |
* Check JWT | |
*/ | |
function checkJWT(options) { | |
return (request, response, next) => { | |
// Check for paths to ignore | |
if (options.unless.includes(request.path)) return next(); | |
let {authorization} = request.headers; | |
// Authorization header is missing | |
if (!authorization) return response.sendStatus(500); | |
// String: Bearer <token> | |
// Array: [0] [1] | |
let token = authorization.split(/\s/)[1]; | |
// Check token | |
jwt.verify(token, options.secret, (error, decoded) => { | |
// Error | |
if (error) return response.status(500).send(error.message); | |
// Pass the user data | |
response.locals.user = decoded; | |
// Pass the token | |
response.locals.token = token; | |
// Call next middleware/route | |
next(); | |
}); | |
}; | |
} | |
module.exports = checkJWT; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment