Jason Martocci
Jason Martocci

Reputation: 119

Redirect if session is not available node.js

I am trying to write code for my route that if the session.user_id is undefined redirect back to the home page. For some reason the redirect doesnt execute and the mysql condition is fired and it crashes the server because the session.user_id is undefined and it cant load the game without that data.

Is there a way to use a universal redirect on all routes that if session is not available redirect back to login?

                router.get('/game', function(req,res) {

                console.log(req.session.user_id);

                if (req.session.user_id === "undefined") {

                res.redirect('/');

                }else {

                var condition = 'userId = ' + req.session.user_id;

                projectX.allGameData(condition, function(data){

                var hbsObject = {heroes : data, logged_in: req.session.logged_in, isUser: req.session.isUser, isAdmin: req.session.isAdmin}

                res.render('game', hbsObject);

                });

                };

                });

Upvotes: 1

Views: 1240

Answers (3)

Iceman
Iceman

Reputation: 6145

//Inject authHandler as middleware
router.get('/my/route/', authHandler, (req, res) => {
    //secure point, the authHandle went thru
});
function authHandler(req, res, next) {
    if (req.session.user_id) {
        next();
    }
    res.redirect('/login/');
}

Add a function to handle the Auth check and then inject is a middleware to your router.

Upvotes: 0

Mohit Bhardwaj
Mohit Bhardwaj

Reputation: 10083

You should either use: if (req.session.user_id === undefined)

OR if ( typeof req.session.user_id === "undefined")

Apart from that, it's usually better to have a middleware function that checks for user session. This way, you can just insert the call to this middleware in all your routes, which require the user to be logged in:

router.get('/game', checkUserSession, function(req,res) {
  // Your code here
});

function checkUserSession( req, res, next )
{
    if( req.session.user_id )
    {
        next();
    }
    else
    {
        res.redirect('/homepage');
    }
}//checkUserSession()

Upvotes: 1

robertklep
robertklep

Reputation: 203359

I assume the value is undefined, and not "undefined" (which is a string containing the word "undefined"):

if (req.session.user_id === undefined) {
  ...
}

Upvotes: 1

Related Questions