Advertisement
Guest User

openfb-angular.js

a guest
Aug 7th, 2014
351
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.78 KB | None | 0 0
  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.2
  9. */
  10. angular.module('openfb', [])
  11.  
  12. .factory('OpenFB', function ($rootScope, $q, $window, $http) {
  13.  
  14. var FB_LOGIN_URL = 'https://www.facebook.com/dialog/oauth',
  15.  
  16. FB_LOGOUT_URL = 'https://www.facebook.com/logout.php',
  17.  
  18. // By default we store fbtoken in sessionStorage. This can be overriden in init()
  19. tokenStore = window.sessionStorage,
  20.  
  21. fbAppId,
  22. oauthRedirectURL,
  23.  
  24. // Because the OAuth login spans multiple processes, we need to keep the success/error handlers as variables
  25. // inside the module instead of keeping them local within the login function.
  26. deferredLogin,
  27.  
  28. // Indicates if the app is running inside Cordova
  29. runningInCordova,
  30.  
  31. // Used in the exit event handler to identify if the login has already been processed elsewhere (in the oauthCallback function)
  32. loginProcessed;
  33.  
  34. document.addEventListener("deviceready", function () {
  35. runningInCordova = true;
  36. }, false);
  37.  
  38. /**
  39. * Initialize the OpenFB module. You must use this function and initialize the module with an appId before you can
  40. * use any other function.
  41. * @param appId - The id of the Facebook app
  42. * @param redirectURL - The OAuth redirect URL. Optional. If not provided, we use sensible defaults.
  43. * @param store - The store used to save the Facebook token. Optional. If not provided, we use sessionStorage.
  44. */
  45. function init(appId, redirectURL, store) {
  46. fbAppId = appId;
  47. if (redirectURL) oauthRedirectURL = redirectURL;
  48. if (store) tokenStore = store;
  49. }
  50.  
  51. /**
  52. * Login to Facebook using OAuth. If running in a Browser, the OAuth workflow happens in a a popup window.
  53. * If running in Cordova container, it happens using the In-App Browser. Don't forget to install the In-App Browser
  54. * plugin in your Cordova project: cordova plugins add org.apache.cordova.inappbrowser.
  55. * @param fbScope - The set of Facebook permissions requested
  56. */
  57. function login(fbScope) {
  58.  
  59. if (!fbAppId) {
  60. return error({error: 'Facebook App Id not set.'});
  61. }
  62.  
  63. var loginWindow;
  64.  
  65. fbScope = fbScope || '';
  66.  
  67. deferredLogin = $q.defer();
  68.  
  69. loginProcessed = false;
  70.  
  71. tokenStore['fbtoken'] = undefined;
  72.  
  73. // Check if an explicit oauthRedirectURL has been provided in init(). If not, infer the appropriate value
  74. if (!oauthRedirectURL) {
  75. if (runningInCordova) {
  76. oauthRedirectURL = 'https://www.facebook.com/connect/login_success.html';
  77. } else {
  78. // Trying to calculate oauthRedirectURL based on the current URL.
  79. var index = document.location.href.indexOf('index.html');
  80. if (index > 0) {
  81. oauthRedirectURL = document.location.href.substring(0, index) + 'oauthcallback.html';
  82. } else {
  83. return alert("Can't reliably infer the OAuth redirect URI. Please specify it explicitly in openFB.init()");
  84. }
  85. }
  86. }
  87.  
  88. loginWindow = window.open(FB_LOGIN_URL + '?client_id=' + fbAppId + '&redirect_uri=' + oauthRedirectURL +
  89. '&response_type=token&display=popup&scope=' + fbScope, '_blank', 'location=no');
  90.  
  91. // If the app is running in Cordova, listen to URL changes in the InAppBrowser until we get a URL with an access_token or an error
  92. if (runningInCordova) {
  93. loginWindow.addEventListener('loadstart', function (event) {
  94. var url = event.url;
  95. if (url.indexOf("access_token=") > 0 || url.indexOf("error=") > 0) {
  96. loginWindow.close();
  97. oauthCallback(url);
  98. }
  99. });
  100.  
  101. loginWindow.addEventListener('exit', function () {
  102. // Handle the situation where the user closes the login window manually before completing the login process
  103. deferredLogin.reject({error: 'user_cancelled', error_description: 'User cancelled login process', error_reason: "user_cancelled"});
  104. });
  105. }
  106. // Note: if the app is running in the browser the loginWindow dialog will call back by invoking the
  107. // oauthCallback() function. See oauthcallback.html for details.
  108.  
  109. return deferredLogin.promise;
  110.  
  111. }
  112.  
  113. /**
  114. * Called either by oauthcallback.html (when the app is running the browser) or by the loginWindow loadstart event
  115. * handler defined in the login() function (when the app is running in the Cordova/PhoneGap container).
  116. * @param url - The oautchRedictURL called by Facebook with the access_token in the querystring at the ned of the
  117. * OAuth workflow.
  118. */
  119. function oauthCallback(url) {
  120. // Parse the OAuth data received from Facebook
  121. var queryString,
  122. obj;
  123.  
  124. loginProcessed = true;
  125. if (url.indexOf("access_token=") > 0) {
  126. queryString = url.substr(url.indexOf('#') + 1);
  127. obj = parseQueryString(queryString);
  128. tokenStore['fbtoken'] = obj['access_token'];
  129. deferredLogin.resolve();
  130. } else if (url.indexOf("error=") > 0) {
  131. queryString = url.substring(url.indexOf('?') + 1, url.indexOf('#'));
  132. obj = parseQueryString(queryString);
  133. deferredLogin.reject(obj);
  134. } else {
  135. deferredLogin.reject();
  136. }
  137. }
  138.  
  139. /**
  140. * Application-level logout: we simply discard the token.
  141. */
  142. function logout(fbScope) {
  143.  
  144. if (!fbAppId) {
  145. return error({error: 'Facebook App Id not set.'});
  146. }
  147.  
  148. if ( !tokenStore['fbtoken'] ) {
  149. return error({error: 'AccessToken not set.'});
  150. }
  151.  
  152. var logoutWindow;
  153.  
  154. fbScope = fbScope || '';
  155.  
  156. deferredLogout = $q.defer();
  157.  
  158. logoutRedirectUrl = 'https://www.facebook.com/connect/login_success.html';
  159.  
  160. logoutWindow = window.open(FB_LOGOUT_URL + '?access_token=' + tokenStore['fbtoken'] + '&next=' + logoutRedirectUrl +
  161. '&response_type=token&display=popup&scope=' + fbScope, '_blank', 'location=no');
  162.  
  163. // If the app is running in Cordova, listen to URL changes in the InAppBrowser until we get a URL with an access_token or an error
  164. logoutWindow.addEventListener('loadstart', function (event) {
  165. var url = event.url;
  166. if (url.indexOf("access_token=") > 0 || url.indexOf("error=") > 0) {
  167. logoutWindow.close();
  168. tokenStore['fbtoken'] = undefined;
  169. deferredLogout.resolve();
  170. }
  171. else {
  172. deferredLogout.reject('Error on FB PHP logout');
  173. }
  174. });
  175.  
  176. // Note: if the app is running in the browser the loginWindow dialog will call back by invoking the
  177. // oauthCallback() function. See oauthcallback.html for details.
  178.  
  179. return deferredLogout.promise;
  180.  
  181.  
  182. }
  183.  
  184. /**
  185. * Helper function to de-authorize the app
  186. * @param success
  187. * @param error
  188. * @returns {*}
  189. */
  190. function revokePermissions() {
  191. return api({method: 'DELETE', path: '/me/permissions'})
  192. .success(function () {
  193. console.log('Permissions revoked');
  194. });
  195. }
  196.  
  197. /**
  198. * Lets you make any Facebook Graph API request.
  199. * @param obj - Request configuration object. Can include:
  200. * method: HTTP method: GET, POST, etc. Optional - Default is 'GET'
  201. * path: path in the Facebook graph: /me, /me.friends, etc. - Required
  202. * params: queryString parameters as a map - Optional
  203. */
  204. function api(obj) {
  205.  
  206. var method = obj.method || 'GET',
  207. params = obj.params || {};
  208.  
  209. params['access_token'] = tokenStore['fbtoken'];
  210.  
  211. return $http({method: method, url: 'https://graph.facebook.com' + obj.path, params: params})
  212. .error(function(data, status, headers, config) {
  213. if (data.error && data.error.type === 'OAuthException') {
  214. $rootScope.$emit('OAuthException');
  215. }
  216. });
  217. }
  218.  
  219. /**
  220. * Helper function for a POST call into the Graph API
  221. * @param path
  222. * @param params
  223. * @returns {*}
  224. */
  225. function post(path, params) {
  226. return api({method: 'POST', path: path, params: params});
  227. }
  228.  
  229. /**
  230. * Helper function for a GET call into the Graph API
  231. * @param path
  232. * @param params
  233. * @returns {*}
  234. */
  235. function get(path, params) {
  236. return api({method: 'GET', path: path, params: params});
  237. }
  238.  
  239. function parseQueryString(queryString) {
  240. var qs = decodeURIComponent(queryString),
  241. obj = {},
  242. params = qs.split('&');
  243. params.forEach(function (param) {
  244. var splitter = param.split('=');
  245. obj[splitter[0]] = splitter[1];
  246. });
  247. return obj;
  248. }
  249.  
  250. return {
  251. init: init,
  252. login: login,
  253. logout: logout,
  254. revokePermissions: revokePermissions,
  255. api: api,
  256. post: post,
  257. get: get,
  258. oauthCallback: oauthCallback
  259. }
  260.  
  261. });
  262.  
  263. // Global function called back by the OAuth login dialog
  264. function oauthCallback(url) {
  265. var injector = angular.element(document.getElementById('main')).injector();
  266. injector.invoke(function (OpenFB) {
  267. OpenFB.oauthCallback(url);
  268. });
  269. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement