Skip to content

Instantly share code, notes, and snippets.

@sueleybyte
Last active May 24, 2019 11:24
Show Gist options
  • Save sueleybyte/64d119dc87c4c665b0bfb2f20289e64c to your computer and use it in GitHub Desktop.
Save sueleybyte/64d119dc87c4c665b0bfb2f20289e64c to your computer and use it in GitHub Desktop.
Middleware for checking JWT
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