'NodeJS Session Management in Main

I'm newish to NodeJS and ExpressJS and am trying to get the session management flow in main.js worked out.

What I currently have that's working:

    app.get('*', function(req, res){
    var page = getPage();

    session_.initSession( req, res, function( ){
        loggedIn = false;
        if( req.session && typeof req.session.username !== "undefined" ){
            loggedIn = true;
            userFName = req.session.first_name;
            userLName = req.session.last_name;
        }
        if( !loggedIn ){
            res.render('pages/login', { message: "<div class='notice centered' style='width: 40%;'>Please login</div>" });
            returnFlag = true;
            return;
        } else {
            if (page.length < 1){
                // render index page here ...
                returnFlag = true;
                return;
            }

            // render 'test' page
            if( page == 'test' ){
                // do test functions here...

                returnFlag = true;
                return;
            }
        }
    });

    if( returnFlag == true ){
        return;
    } 

    res.render('partials/home', { message: "404 not found (unknown page GET request)" });
    return;
});

app.post('*', files, function(req, res){
    var page = getPage();

    if( page == 'test' ){
        // do test functions here...

        returnFlag = true;
        return;
    }

    if( returnFlag == true ){
        return;
    } 

    res.render('partials/home', { message: "404 not found (unknown page POST request)" });
    return;
});

The problem with this is that POST requests are being processed even when no session is in place. I've tried adding app.all/use blocks above the app.get and app.post code blocks to set up a session, but then the app.get/post blocks were not getting processed. What is the optimal way to architect this so all requests get filtered through session management and then on to page request blocks if a proper session is in place?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source