Skip to content

Instantly share code, notes, and snippets.

@paulobunga
Last active January 28, 2019 13:18
Show Gist options
  • Save paulobunga/bd2530d0106ec1c814bf3714a8f2c198 to your computer and use it in GitHub Desktop.
Save paulobunga/bd2530d0106ec1c814bf3714a8f2c198 to your computer and use it in GitHub Desktop.
Auth middleware, checks if user is logged in or not
const jwt = require('jsonwebtoken');
exports.isAuthenticated = (req, res, next) => {
//Get the request headers and check if we have an authorization header with our token
if (req.headers && req.headers.authorization && req.headers.authorization.split(' ')[0] === 'JWT') {
//Check the token for validity
var token = req.headers.authorization.split(' ')[1];
jwt.verify(token, 'our-jwt-secret-goes-here', (err, payload) => {
if (err) {
res.status(401).json({
message: 'Unauthorized user!'
});
} else {
req.user = {...payload}
next();
}
});
} else {
res.status(401).json({
message: 'Unauthorized user!'
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment