Everyauth and Client-side Authentication Check

I’m writing a web application built using node.js and mongodb deployed via CloudFoundry. I’m using EveryAuth to authenticate users using Facebook. One tricky issue I faced was bypassing the client-side login screen if the user had already recently authenticated using Facebook. While this is pretty easy using the client-side Facebook javascript SDK, it was less so in my case. I’ve never used Facebook’s javascript SDK, but it seems what I wanted to do could be accomplished with a simple call to FB.getLoginStatus.

My solution was to emulate the FB.getLoginStatus call. In node.js, I created the following route:

// User Collection: Determine if user already logged in
    app.get('/peAPI/user/checkAuth', function(req, res)
    {
        if (checkAuth(req, res))
        {
            return res.send({loggedIn: false});
        }
        else
        {
            return res.send({loggedIn: true});
        }
    });

Here’s the implementation of checkAuth:

    /**
     * checkAuth: Checks to see if user is authorized and logged in.
     * @param {} req contains request information
     * @param {} res contains response information
     * @returns {Boolean}
     */
    function checkAuth(req, res)
    {
        if (app.requireAuth === true && req.loggedIn === false)
        {
            return true;
        }
        return false;
    }

EveryAuth automatically manages the requireAuth and loggedIn fields, making this function very simple to implement.

In the client, I just need to do the following check:

        // If previously logged in (Check via server code), show main menu
        peDS.checkAuth(function(authInfo) {
            if (authInfo.loggedIn)
                peDC.showMainMenu();
        });

where, checkAuth‘s implementation is:

    peDS.checkAuth = function(setCheckAuthCallback)
    {
        var request = new XMLHttpRequest();
        request.onload = function()
        {
            if (request.status === 200)
            {
                var authData = JSON.parse(request.responseText);
                
                setCheckAuthCallback(authData);
                return;
            }
            else
            {
                mhLog.log(mhLog.LEVEL.PRODUCTION, "Checking user authorization failed with error code: " + request.status);
            }
        };

        request.open("GET", "/peAPI/user/checkAuth");
        request.send(null);
    }

If you are using EveryAuth to authenticate your users with Facebook, Twitter, LinkedIn or whatever, perhaps the above method can help you reduce the number of times your users have to see a “login” screen.