Skip to content

Instantly share code, notes, and snippets.

@thebigredgeek
Created May 19, 2020 20:16
Show Gist options
  • Save thebigredgeek/08959b5a7cb771963de2e17d17045ff1 to your computer and use it in GitHub Desktop.
Save thebigredgeek/08959b5a7cb771963de2e17d17045ff1 to your computer and use it in GitHub Desktop.
JWT Tenant Secret Middleware
const model = require('./model'); // our fake model
const verifyJWT = async (req, res, next) => {
// Extract the authorization header
const header = req.get('Authorization');
let err
, secret
, id;
// If no authorization header is present,
// send back an error
if (!header) {
res.status(401).send({
message: "Authorization required"
});
return false;
}
// Let's assume the token is sent using
// the standard Bearer <token> schema.
// In this case, we need to extract the
// <token> portion of the string by
// splitting it on the space between
// it and Bearer.
const token = header.split(' ')[1];
// If there is not token, this a malformed
// authentication header so we need to send
// back an error message.
if (!token) {
res.status(400).send({
message: 'Authentication header must be Bearer <token> format'
});
return false;
}
// Extract the user id
// from the JWT without verifying
[err, { id }] = await to(jwt.decode(token, JWT_SECRET));
// If the JWT is invalid,
// send back an error message
if (err || !id) {
res.status(401).send({
message: 'Invalid JWT token'
});
return false;
}
// pull the secret out
// of storage using the user
// id
[err, secret] = await to(model.getSecretByUserId(id));
// If we weren't able to find a secret
// then this is an invalid JWT
if(err) {
res.status(401).send({
message: 'Invalid JWT token'
});
return false;
}
// Verify the JWT using the secret
[err] = await to(jwt.verify(token, secret));
// If there is an error
// then the JWT is invalid
if (err) {
res.status(401).send({
message: 'Invalid JWT token'
});
return false;
}
// Set the user id on the
// request object so that our
// route handle can access it.
req.userId = id;
if (next) {
// If we aren't composing middleware,
// there should be a next function
return next();
}
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment