Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Connect middleware directly?

I have a express route like this:

app.get('/', auth.authOrDie, function(req, res) {
    res.send();
});

where authOrDie function is defined like that (in my auth.js module):

exports.authOrDie = function(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    } else {
        res.send(403);
    }
});

Now, when the user is not authenticated, I would like to verify if the http request has a Authorization (Basic) header. To do that, I would like to use the great connect middleware basicAuth().

As you know, Express is built on top of Connect, so I can use express.basicAuth.

The basicAuth is generally used like that:

app.get('/', express.basicAuth(function(username, password) {
    // username && password verification...
}), function(req, res) {
    res.send();
});

But, I would like to use it in my authOrDie function like that:

exports.authOrDie = function(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    } else if {
        // express.basicAuth ??? ******
    } else {
        res.send(403);
    }
});

****** How can I call the basicAuth function with the good parameters (req ? res ? next ? ...).

Thanks.

like image 704
Sandro Munda Avatar asked Feb 17 '23 21:02

Sandro Munda


1 Answers

Calling the express.basicAuth function returns the middleware function to call, so you'd invoke it directly like this:

exports.authOrDie = function(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    } else {
        return express.basicAuth(function(username, password) {
            // username && password verification...
        })(req, res, next);
    }
});
like image 109
JohnnyHK Avatar answered Feb 21 '23 08:02

JohnnyHK