Advertisement
Guest User

OpenFB.js

a guest
Mar 14th, 2017
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * OpenFB is a micro-library that lets you integrate your JavaScript application with Facebook.
  3.  * OpenFB works for both BROWSER-BASED apps and CORDOVA/PHONEGAP apps.
  4.  * This library has no dependency: You don't need (and shouldn't use) the Facebook SDK with this library. Whe running in
  5.  * Cordova, you also don't need the Facebook Cordova plugin. There is also no dependency on jQuery.
  6.  * OpenFB allows you to login to Facebook and execute any Facebook Graph API request.
  7.  * @author Christophe Coenraets @ccoenraets
  8.  * @version 0.1
  9.  */
  10. var openFB = (function() {
  11.  
  12.     var FB_LOGIN_URL = 'https://www.facebook.com/dialog/oauth',
  13.  
  14.         // By default we store fbtoken in sessionStorage. This can be overriden in init()
  15.         tokenStore = window.sessionStorage,
  16.  
  17.         fbAppId,
  18.         oauthRedirectURL,
  19.  
  20.         // Because the OAuth login spawns multiple processes, we need to keep the success/error handlers as variables
  21.         // inside the module as opposed to keeping them local within the function.
  22.         loginSuccessHandler,
  23.         loginErrorHandler;
  24.  
  25.     /**
  26.      * Initialize the OpenFB module. You must use this function and initialize the module with an appId before you can
  27.      * use any other function.
  28.      * @param appId - The id of the Facebook app
  29.      * @param redirectURL - The OAuth redirect URL. Optional. If not provided, we use sensible defaults.
  30.      * @param store - The store used to save the Facebook token. Optional. If not provided, we use sessionStorage.
  31.      */
  32.     function init(appId, redirectURL, store) {
  33.         fbAppId = appId;
  34.         runningInCordova = true;
  35.         if (redirectURL) oauthRedirectURL = redirectURL;
  36.         if (store) tokenStore = store;
  37.     }
  38.  
  39.     /**
  40.      * Login to Facebook using OAuth. If running in a Browser, the OAuth workflow happens in a a popup window.
  41.      * If running in Cordova container, it happens using the In-App Browser. Don't forget to install the In-App Browser
  42.      * plugin in your Cordova project: cordova plugins add org.apache.cordova.inappbrowser.
  43.      * @param scope - The set of Facebook permissions requested
  44.      * @param success - Callback function to invoke when the login process succeeds
  45.      * @param error - Callback function to invoke when the login process fails
  46.      * @returns {*}
  47.      */
  48.     function login(scope, success, error) {
  49.  
  50.         if (!fbAppId) {
  51.             return error({error: 'Facebook App Id not set.'});
  52.         }
  53.  
  54.         var loginWindow;
  55.  
  56.         scope = scope || '';
  57.  
  58.         loginSuccessHandler = success;
  59.         loginErrorHandler = error;
  60.  
  61.         if (!oauthRedirectURL) {
  62.             if (runningInCordova === 'true') {
  63.                 oauthRedirectURL = 'https://www.facebook.com/connect/login_success.html';
  64.             } else {
  65.                 // Trying to calculate oauthRedirectURL based on the current URL.
  66.                 var index = document.location.href.indexOf('login2.html');
  67.                 if (index > 0) {
  68.                     oauthRedirectURL = window.document.location.href.substring(0, index) + 'oauthcallback.html';
  69.                 } else {
  70.                     return alert("Can't reliably guess the OAuth redirect URI. Please specify it explicitly in openFB.init()");
  71.                 }
  72.             }
  73.         }
  74.  
  75.         loginWindow = window.open(FB_LOGIN_URL + '?client_id=' + fbAppId + '&redirect_uri=' + oauthRedirectURL +
  76.             '&response_type=token&display=popup&scope=' + scope, '_blank', 'location=no');
  77.  
  78.         // If the app is running in Cordova, listen to URL changes in the InAppBrowser until we get a URL with an access_token
  79.         if (runningInCordova === 'true') {
  80.             loginWindow.addEventListener('loadstart', function (event) {
  81.                 var url = event.url;
  82.                 if (url.indexOf("access_token=") > 0) {
  83.                     loginWindow.close();
  84.                     oauthCallback(url);
  85.                 }
  86.             });
  87.  
  88.             loginWindow.addEventListener('exit', function (event) {
  89.                 // Handle the situation where the user closes the login window manually before completing the login process
  90.                 var url = event.url;
  91.                 if (url.indexOf("access_token=") > 0) {
  92.                     deferredLogin.reject();
  93.                 }
  94.             });
  95.         }
  96.         // Note: if the app is running in the browser the loginWindow dialog will call back by invoking the
  97.         // oauthCallback() function. See oauthcallback.html for details.
  98.  
  99.     }
  100.  
  101.     /**
  102.      * Called either by oauthcallback.html (when the app is running the browser) or by the loginWindow loadstart event
  103.      * handler defined in the login() function (when the app is running in the Cordova/PhoneGap container).
  104.      * @param url - The oautchRedictURL called by Facebook with the access_token in the querystring at the ned of the
  105.      * OAuth workflow.
  106.      */
  107.     function oauthCallback(url) {
  108.         // Parse the OAuth data received from Facebook
  109.         var hash = decodeURIComponent(url.substr(url.indexOf('#') + 1)),
  110.             params = hash.split('&'),
  111.             oauthData = {};
  112.         params.forEach(function (param) {
  113.             var splitter = param.split('=');
  114.             oauthData[splitter[0]] = splitter[1];
  115.         });
  116.         var fbtoken = oauthData['access_token'];
  117.         if (fbtoken) {
  118.             tokenStore['fbtoken'] = fbtoken;
  119.             if (loginSuccessHandler) loginSuccessHandler();
  120.         } else {
  121.             if (loginErrorHandler) loginErrorHandler();
  122.         }
  123.     }
  124.  
  125.     /**
  126.      * Application-level logout: we simply discard the token.
  127.      */
  128.     function logout() {
  129.         tokenStore['fbtoken'] = undefined;
  130.     }
  131.  
  132.     /**
  133.      * Lets you make any Facebook Graph API request.
  134.      * @param obj - Request configuration object. Can include:
  135.      *  method:  HTTP method: GET, POST, etc. Optional - Default is 'GET'
  136.      *  path:    path in the Facebook graph: /me, /me.friends, etc. - Required
  137.      *  params:  queryString parameters as a map - Optional
  138.      *  success: callback function when operation succeeds - Optional
  139.      *  error:   callback function when operation fails - Optional
  140.      */
  141.     function api(obj) {
  142.  
  143.         var method = obj.method || 'GET',
  144.             params = obj.params || {},
  145.             xhr = new XMLHttpRequest(),
  146.             url;
  147.  
  148.         params['access_token'] = tokenStore['fbtoken'];
  149.  
  150.         url = 'https://graph.facebook.com/v2.8' + obj.path + '?fields=id,name,email&' + toQueryString(params);
  151.  
  152.         xhr.onreadystatechange = function() {
  153.             console.log(xhr.readyState + ' ' + xhr.status);
  154.             if (xhr.readyState === 4) {
  155.                 if (xhr.status === 200) {
  156.                     if (obj.success) obj.success(JSON.parse(xhr.responseText));
  157.                 } else {
  158.                     var error = xhr.responseText ? JSON.parse(xhr.responseText).error : {message: 'An error has occurred'};
  159.                     if (obj.error) obj.error(error);
  160.                 }
  161.             }
  162.         }
  163.  
  164.         xhr.open(method, url, true);
  165.         xhr.send();
  166.     }
  167.  
  168.     /**
  169.      * Helper function to de-authorize the app
  170.      * @param success
  171.      * @param error
  172.      * @returns {*}
  173.      */
  174.     function revokePermissions(success, error) {
  175.         return api({method: 'DELETE',
  176.             path:'/me/permissions',
  177.             success: function() {
  178.                 tokenStore['fbtoken'] = undefined;
  179.                 success();
  180.             },
  181.             error: error});
  182.     }
  183.  
  184.     function toQueryString(obj) {
  185.         var parts = [];
  186.         for (var i in obj) {
  187.             if (obj.hasOwnProperty(i)) {
  188.                 parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]));
  189.             }
  190.         }
  191.         return parts.join("&");
  192.     }
  193.  
  194.  
  195.  
  196.     // The public API
  197.     return {
  198.         init: init,
  199.         login: login,
  200.         logout: logout,
  201.         revokePermissions: revokePermissions,
  202.         api: api,
  203.         oauthCallback: oauthCallback
  204.     }
  205.  
  206. }());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement