I'm writing and API with Express JS that uses JSON web tokens for authorization. Is there are more readable way to show the user the correct error message? How would you refactor the following authorization middleware?
module.exports.authorize = function (request, response, next) {
var apiToken = request.headers['x-api-token'];
if(apiToken) {
var decoded = token.verify(apiToken);
if(decoded) {
if(decoded.exp <= moment().format('x')) {
next();
} else {
var expiredTokenError = new Error('Token has expired');
expiredTokenError.status = 419;
return next(expiredTokenError);
}
} else {
var invalidTokenError = new Error('Token is invalid');
invalidTokenError.status = 401;
return next(invalidTokenError);
}
} else {
var notFoundError = new Error('Token not found');
notFoundError.status = 404;
return next(notFoundError);
}
};