words

Facebook Application login w/ Backbone.js

Currently I’m in a facebook project where I use Backbone to create SPI application. Just an example how to combine Facebook Javascript SDKs FB.login with a Backbone Model.

SessionModel

This module handles actions that needs FB authentication.

      SessionModel = Backbone.Model.extend({
        defaults: {
          id: null,
          third_party_id: null,
          name: null,
          email: null,
          status: 0
        },

        isAuthorized: function () {
          /* true if third_party_id exists */
          return Boolean(this.get("third_party_id"));
        },

        logout: function () {
          /* destroy session */
          window.activeSession.id = "";
          window.activeSession.clear();
          console.log('logout done!');
        },

        login: function (opts) {
          console.log('#########\n login called.\n###########');

          /* run optional passed user func */
          opts.before && opts.before();

          _session = this;
          this._onALWAYS = function () {
            opts.after && opts.after();
          };
          this._onERROR = function () {
            console.log('this._onERROR with result:', result);
          };
          this._onSUCCESS = function (result) {
            console.log('this._onSUCCESS with result:', result);
            console.log(_session.get('third_party_id'));
          };

          this._getuserdata = function (callback) {
            console.log('_getuserdata called;');
            /* Here you can assemble a query */
            FB.api('/me?fields=third_party_id,email,name', function (response) {
              if (!response || response.error) {
                callback(true, response.error);
              } else {
                console.log('"/me" query success where username is ' + response['name'] + '.', response);
                callback(null, response);
              }
            });

          };

          this._savesession = function (user, callback) {
            console.log('_savesession called, user data:', user);
            /* if third_party_id exist its totally okay */
            if (user['third_party_id']) {
              _session.set({
                id: user['id'],
                third_party_id: user['third_party_id'],
                name: user['name'],
                email: user['email'],
                status: "1"
              }, {
                silent: true
              });
              callback(null, "Everything is wonderful.");
            } else {
              callback(true, "third_party_id check failed!");
              return false;
            }
          }

          FB.login(function (response) {
            if (response.authResponse) {
              console.log('Fetching authResponse information.... ');

              /* Use async.js to run async functions in a row */
              async.waterfall([
              _session._getuserdata,
              _session._savesession,
              /* optionally here you can include _session.save() -> this will push cookies (including auth_token) to the server */
               ], function (err, result) {
                console.log('Queue finished. Error occured:', err, ' result:', result); !! err && _session._onERROR(result); !! !err && _session._onSUCCESS(result);
                _session._onALWAYS(result);
              });

            } else {
              _session._onERROR('User cancelled login or did not fully authorize.');
            }
          }, {
            scope: 'email,user_likes'
          });
        }

      });

      /* Instantiate session */
      window.activeSession = new SessionModel();
      console.log('authorized after create (should be false):', window.activeSession.isAuthorized());

First thing you need to do is init Facebook SDK. After it is finished you can bind events to elements that requires login before fire them:

      // Load the SDK Asynchronously
      (function (d) {
        var js, id = 'facebook-jssdk',
          ref = d.getElementsByTagName('script')[0];
        if (d.getElementById(id)) {
          return;
        }
        js = d.createElement('script');
        js.id = id;
        js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        ref.parentNode.insertBefore(js, ref);
      }(document));

      window.fbAsyncInit = function () {
        FB.init({
          appId: '1001001001',
          channelUrl: '//your/path/to/channel.php',
          status: true, // check login status
          cookie: true, // enable cookies to allow the server to access the session
          xfbml: true // parse XFBML
        });

        FB.getLoginStatus(function (response) {
          console.log('FB resp:', response, response.status);
          /* Bind event handler only after Facebook SDK had a nice cup of coffee */
          $('#btnLogin').on('click', function () {
            window.activeSession.login({
              before: function () {
                console.log('before login()')
              },
              after: function () {
                console.log('after login()')
              }
            });
          });
        });

      };

Github repo

https://github.com/zsitro/backbone-facebook-login

Dependencies

Demo on Facebook: http://apps.facebook.com/482440281767077/ (hopefully still online)

Wanna improve?

Feel free to modify and do a pull request. It would be sparkling.

Last updated: