Skip to content

Instantly share code, notes, and snippets.

@anshulrgoyal
Created May 21, 2019 18:30
Show Gist options
  • Save anshulrgoyal/a24b7b639cc7026eb842af5c0219e082 to your computer and use it in GitHub Desktop.
Save anshulrgoyal/a24b7b639cc7026eb842af5c0219e082 to your computer and use it in GitHub Desktop.
Middleware for jwt validation
/**
* authenticator - check for token and add user to req
*
* @param {Object} req the req object contains all the info about request
* @param {Object} res the res object contains many methods to respond to request
* @param {Object} next to pass ther control to next middleware
*
* @returns {undefined}
*/
async function authenticator(req, res, next) {
if ("authorization" in req.headers) {
// get the bearer and token
const [bearer, token] = req.headers["authorization"].split(" ");
if (bearer === "Bearer") {
if (token) {
try {
const payload = await jwtHelper.verify(token);
const userDetials = await User.findById(payload.userId);
if (userDetials) {
req.user = userDetials;
next();
} else {
res.status(401).json({
errorDetails: "User Not Found",
errorType: ERROR_TYPES.DB_ERROR,
message: "Your not Authorization."
});
}
} catch (error) {
res.status(401).json({
errorDetails: error.message || error,
errorType: ERROR_TYPES.JWT_ERROR,
message: "Your not Authorization."
});
}
} else {
res.status(401).json({
errorDetails: "please add authentication header with token",
errorType: ERROR_TYPES.JWT_ERROR,
message: "Your not Authorization."
});
}
} else {
res.status(401).json({
errorDetails: "please add authentication header with bearer",
errorType: ERROR_TYPES.JWT_ERROR,
message: "Your not Authorization."
});
}
} else {
res.status(401).json({
errorDetails: "please add authentication header",
errorType: ERROR_TYPES.JWT_ERROR,
message: "Your not Authorization."
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment