Reputation: 5210
I'm setting up dynamic routes and using basicAuth (when a user/pass has been configured). Here's what I have:
var basicAuth = express.basicAuth,
auth = function(req, res, next) {
if (config.hasOwnProperty(req.params.project)) {
var auth = config[req.params.project].auth;
if (auth) {
basicAuth(function(user, pass, callback) {
// Check credentials
callback(null, user === auth.user && pass === auth.pass);
})(req, res, next);
} else {
// No authentication
return true;
}
}
};
Then, my route looks like this:
app.get("/:project", auth, function (req, res) {
...
});
It's getting the config from a file which either contains the auth
object with auth.user
and auth.pass
or is set to false
. When set to false
I'd like to (obviously) skip authentication.
The basicAuth is working when turned on, but I can't figure out how to dynamically bypass it.
Upvotes: 0
Views: 3086
Reputation: 161457
Connect doesn't check the return value of the middleware, so returning true
doesn't mean anything. You need to call the next
function so that Connect knows to continue.
var basicAuth = express.basicAuth,
auth = function(req, res, next) {
if (config.hasOwnProperty(req.params.project)) {
var auth = config[req.params.project].auth;
if (auth) {
basicAuth(function(user, pass, callback) {
// Check credentials
callback(null, user === auth.user && pass === auth.pass);
})(req, res, next);
} else {
// No authentication
next();
}
}
};
Also, it looks like the basicAuth
callback can be synchronous, so it's probably cleaner to do this:
basicAuth(function(user, pass) {
// Check credentials
return user === auth.user && pass === auth.pass;
})(req, res, next);
Finally, basicAuth
has another alternate form, so you can just do:
basicAuth(auth.user, auth.pass)(req, res, next);
Upvotes: 2