Last active
January 28, 2019 13:18
-
-
Save paulobunga/bd2530d0106ec1c814bf3714a8f2c198 to your computer and use it in GitHub Desktop.
Auth middleware, checks if user is logged in or not
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 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