Created
November 1, 2014 23:11
-
-
Save jvaill/1ebe05969330cd4ce265 to your computer and use it in GitHub Desktop.
Auth token middleware for Connect.
This file contains 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
var _ = require('underscore'); | |
/* | |
* Auth token middleware for Connect. | |
* | |
* Looks at the `X-Auth-Token` header and compares it against `authToken`. | |
* | |
* `authToken` can be a string or a function that takes an input authentication | |
* token and returns a boolean that indicates whether authentication succeeds. | |
*/ | |
module.exports = function authToken(authToken) { | |
if (!authToken) { | |
throw new Error( | |
'`authToken` must be a string or a function that takes an input ' + | |
'authentication token and returns a boolean that indicates ' + | |
'whether authentication succeeds.' | |
); | |
} | |
function unauthorized(res, message) { | |
res.status(401).send({message: message}).end(); | |
}; | |
return function(req, res, next) { | |
var reqAuthToken = req.headers['x-auth-token']; | |
// Bail early if the auth token was not sent with the request. | |
if (!reqAuthToken) { | |
return unauthorized( | |
res, | |
'Authentication token must be sent via the X-Auth-Token header.' | |
); | |
} | |
// Validate auth token. | |
var isAuthorized = false; | |
if (_.isString(authToken)) { | |
isAuthorized = (reqAuthToken == authToken); | |
} | |
else if (_.isFunction(authToken)) { | |
isAuthorized = authToken(reqAuthToken); | |
} | |
// Bad auth token. | |
if (!isAuthorized) { | |
return unauthorized(res, 'Bad authentication token'); | |
} | |
// Good auth token. | |
return next(); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment