javascriptruby-on-railsfacebookfacebooker2

Facebooker2 current_facebook_user nil when logged in on Facebook


I've been trying to use Facebooker2 as a means to login via Facebook in Rails. However, Facebooker2's current_facebook_user function is somehow returning nil even though I'm definitely logged in on Facebook. Any ideas? Thanks!

Here's the gist of my code:

In one of my controllers:

def check_login
    if current_facebook_user.nil?
        "This always gets returned, even though I'm logged into Facebook."
    else
        "This never gets run"
    end
end

Facebook JS. The line in FB.Event.subscribe('auth.login', function(response) { ... } redirects to the check_login function above.

<script>
    window.fbAsyncInit = function() {
        FB.init({
            appId : '123456789012345',
            status : true,  // check login status
            cookie : true,  // enable cookies to allow the server to access the session
            channelUrl : 'true',  // add channelURL to avoid IE redirect problems
            xfbml : true  // parse XFBML
        });
        FB.Event.subscribe('auth.login', function(response) {
            window.location = "http://www.mysite.com/check_login";
        });
    }; ( function() {
        var s = document.createElement('div');
        s.setAttribute('id', 'fb-root');
        document.documentElement.getElementsByTagName("body")[0].appendChild(s);
        var e = document.createElement('script');
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        s.appendChild(e);
    }());
    function logout() {
        FB.logout();
        window.location = 'http://www.mysite.com/logout';
    };
</script>

Solution

  • If you login through your browser using the Facebook JavaScript SDK the users session data is held within the browser. As result your Rails code is unaware of the change in the users state. So you have to explicitly pass valid current user session data back to your server from which you can maintain a valid session server side as well.

    For example:

        FB.Event.subscribe('auth.login', function(response) {
            window.location = "http://www.mysite.com/check_login?session=" + JSON.stringify(response.session);
        });