Use connect.basicAuth and another middleware at a time

advertisements

The code below is 2 middlewares to do some minimum security for my API.

// API
var apiRouteV1 = '/api/v1';
app.use(apiRouteV1, express.basicAuth(function(email, token, callback){
    User.authenticateWithEmailAndToken(email, token, callback);
}));
app.use(apiRouteV1, function(req, res, next) {
    if(req.remoteUser._shop.toString() !== req.shop._id.toString())
        next(Error.http(401, 'Wrong user for this shop'));
    next();
});

I'd like to merge both of them. Is is possible? Thanks!


You can combine them into your own middleware that just calls both, e.g.

function apiAuth(){
    var basicAuth = express.basicAuth(function(email, token, callback){
        User.authenticateWithEmailAndToken(email, token, callback);
    });
    var shopAuth = function(req, res, next) {
        if(req.remoteUser._shop.toString() !== req.shop._id.toString()){
            next(Error.http(401, 'Wrong user for this shop'));
        }
        else {
            next();
        }
    };

    return function(req, res, next){
        basicAuth(req, res, function(err){
          if (err) return next(err);

          shopAuth(req, res, next);
        });
    };
}

var apiRouteV1 = '/api/v1';
app.use(apiRouteV1, apiAuth());

Also note that your original 'Wrong user' checking middleware would call next twice in the case of an error, and I have fixed that.