koque
koque

Reputation: 2256

Node: Check for null value is not working

In the following function, I parse the request header and obtain the value of the currentUser. I log the value of currentUser and and get the following:

console.log('currentUser', currentUser)
currentUser null

But the following conditional statement of the currentUser does not evaluate to null and subsequent lines are executed:

if (!currentUser) {
    console.log('\n user not logged in');
    res.status(401).json('User not logged in');
}

Error:

TypeError: Cannot read property 'token' of null
at exports.authenticate (sandbox2\nghd09\backend\app\controllers\user.server.controller.js:47:40)
at Layer.handle [as handle_request] (sandbox2\nghd09\node_modules\express\lib\router\layer.js:95:5)

Entire function:

exports.authenticate = function (req, res, next) {
    var headerExists = req.headers.authorization;
    console.log('authenticate called', headerExists)
    var currentUser = req.headers.authorization.split(' ')[1];
    console.log('currentUser', currentUser)

    if (!currentUser) {
        console.log('\n user not logged in');
        res.status(401).json('User not logged in');
    }

    // if (currentUser) {
    var token = JSON.parse(currentUser).token;
    console.log('\ntoken', token)
    jwt.verify(token, config.sessionSecret, function (err, decoded) {
        if (err) {
            console.log(err);
            res.status(401).json('Unauthorized');
        } else {
            req.user = decoded.username;
            req.password = decoded.password;
            next();
        }
    })
    // }
}

I have followed the recommendations of several Stackoverflow's answers but without success.

Upvotes: 2

Views: 1807

Answers (2)

Estus Flask
Estus Flask

Reputation: 222979

Since currentUser is a result of split, it can be either a string or undefined. It can be logged as null only if it is 'null' string. The confusion comes from the fact that null and 'null' are indistinguishable when being output with console.log.

But the following conditional statement of the currentUser does not evaluate to null

This is possible only if currentUser is 'null' string (or any object that has custom toString method that returns 'null' string).

If currentUser is 'null', JSON.parse(currentUser) evaluates to null, this way Cannot read property 'token' of null error is possible.

and subsequent lines are executed

if (currentUser) { is currently commented, so they will be executed regardless of currentUser.

The problem likely should be addressed by performing JSON.parse beforehand:

var currentUser = req.headers.authorization.split(' ')[1];
if (currentUser !== undefined) {
   currentUser = JSON.parse(currentUser);
}

if (!currentUser) {
    console.log('\n user not logged in');
    res.status(401).json('User not logged in');
}

The fact that there was null in authorization header is an another problem that possibly should be additionally addressed.

Upvotes: 3

John
John

Reputation: 1704

Within the null check

if (!currentUser) {
  console.log('\n user not logged in');
  res.status(401).json('User not logged in');
  //return next();   // should return next here to stop current function
}

Just print out log, but not terminating the execution. The codes below would still be executed.

Upvotes: 0

Related Questions