I've got a route in my Express 3.0 app defined like this:
app.post('/:app/find', auth, function(req, res){
I'd like it restricted using HTTP authorization. My auth
function just looks like this:
var auth = express.basicAuth(function(user, pass, callback){
callback(null, user === 'user' && pass === 'pass');
});
I'd like the auth
function to do a database lookup based on req.params.app
from the URL, and authenticate users accordingly. The problem is that I'm not sure how to access that yet, since the function defined in app.post
hasn't been called yet when auth
is run. Where can I get it? Is there a different implementation of HTTP auth I should be using?
There isn't a proper way of doing that with express.basicAuth
(I also looked at some other modules that provide similar functionality, but they never seem to pass req
to the authentication function either), but you could create a middleware which instantiates it for every request that you want to authenticate:
var express = require('express');
var app = express();
var basicAuth = express.basicAuth;
var auth = function(req, res, next) {
...here you can access 'req'...
basicAuth(function(user, pass, callback) {
...here you can use variables set in the block above...
callback(null, user === 'user' && pass === 'pass');
})(req, res, next);
};
app.get('/', auth, function(req, res) {
res.send('authenticated!');
});
app.listen(3012);