John Anderson John Anderson - 1 month ago 9
Node.js Question

Returning value to authentication function doesn't seem to work properly

I am trying to check the authentication status with req.isAuthenticated() and then return ensureAuthenticated as true or false. My issue is nothing is logged in the console it seems like my ensureAuthenticated function is not running correctly.

app.get('/', ensureAuthenticated, function (req, res) {

if (ensureAuthenticated()) {
console.log('logged in')
} else {
console.log('not logged')
}

});



function ensureAuthenticated(req, res, next) {

Authenticate();

function Authenticate() {
if (req.isAuthenticated()) {
return true;
} else {
return false;
}
}

return Authenticate;
}

Answer

You aren't returning your value from ensureAuthenticated. Assuming everything in this is synchronous, then you can do this:

function ensureAuthenticated(req, res, next) {

    function Authenticate() {
        if (req.isAuthenticated()) {
            return true;
        } else {
            return false;
        }
    }

    return Authenticate();
}

Or, you can get rid of the internal function entirely:

function ensureAuthenticated(req, res, next) {
    return req.isAuthenticated();
}

But, it's unclear what you think you're accomplishing by returning true or false from your middleware handler. What are you actually trying to accomplish with the ensureAuthenticated handler?

You can see middleware examples here in the Express doc. A typical middleware handler will either send a response or will call next() to pass control down the chain to the next handler.

Comments