ng-token-authyuan.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. if (typeof module !== 'undefined' && typeof exports !== 'undefined' && module.exports === exports) {
  2. module.exports = 'ng-token-auth';
  3. }
  4. angular.module('ng-token-auth', ['ipCookie']).provider('$auth', function() {
  5. var configs, defaultConfigName;
  6. configs = {
  7. "default": {
  8. apiUrl: '/api',
  9. signOutUrl: '/auth/sign_out',
  10. emailSignInPath: '/auth/sign_in',
  11. emailRegistrationPath: '/auth',
  12. accountUpdatePath: '/auth',
  13. accountDeletePath: '/auth',
  14. confirmationSuccessUrl: function() {
  15. return window.location.href;
  16. },
  17. passwordResetPath: '/auth/password',
  18. passwordUpdatePath: '/auth/password',
  19. passwordResetSuccessUrl: function() {
  20. return window.location.href;
  21. },
  22. tokenValidationPath: '/auth/validate_token',
  23. proxyIf: function() {
  24. return false;
  25. },
  26. proxyUrl: '/proxy',
  27. validateOnPageLoad: true,
  28. omniauthWindowType: 'sameWindow',
  29. storage: 'cookies',
  30. forceValidateToken: false,
  31. tokenFormat: {
  32. "access-token": "{{ token }}",
  33. "token-type": "Bearer",
  34. client: "{{ clientId }}",
  35. expiry: "{{ expiry }}",
  36. uid: "{{ uid }}"
  37. },
  38. parseExpiry: function(headers) {
  39. return (parseInt(headers['expiry'], 10) * 1000) || null;
  40. },
  41. handleLoginResponse: function(resp) {
  42. return resp.data;
  43. },
  44. handleAccountUpdateResponse: function(resp) {
  45. return resp.data;
  46. },
  47. handleTokenValidationResponse: function(resp) {
  48. return resp.data;
  49. },
  50. authProviderPaths: {
  51. github: '/auth/github',
  52. facebook: '/auth/facebook',
  53. google: '/auth/google_oauth2'
  54. }
  55. }
  56. };
  57. defaultConfigName = "default";
  58. return {
  59. configure: function(params) {
  60. var conf, defaults, fullConfig, i, k, label, v, _i, _len;
  61. if (params instanceof Array && params.length) {
  62. for (i = _i = 0, _len = params.length; _i < _len; i = ++_i) {
  63. conf = params[i];
  64. label = null;
  65. for (k in conf) {
  66. v = conf[k];
  67. label = k;
  68. if (i === 0) {
  69. defaultConfigName = label;
  70. }
  71. }
  72. defaults = angular.copy(configs["default"]);
  73. fullConfig = {};
  74. fullConfig[label] = angular.extend(defaults, conf[label]);
  75. angular.extend(configs, fullConfig);
  76. }
  77. if (defaultConfigName !== "default") {
  78. delete configs["default"];
  79. }
  80. } else if (params instanceof Object) {
  81. angular.extend(configs["default"], params);
  82. } else {
  83. throw "Invalid argument: ng-token-auth config should be an Array or Object.";
  84. }
  85. return configs;
  86. },
  87. $get: [
  88. '$http', '$q', '$location', 'ipCookie', '$window', '$timeout', '$rootScope', '$interpolate', (function(_this) {
  89. return function($http, $q, $location, ipCookie, $window, $timeout, $rootScope, $interpolate) {
  90. return {
  91. header: null,
  92. dfd: null,
  93. user: {},
  94. mustResetPassword: false,
  95. listener: null,
  96. initialize: function() {
  97. this.initializeListeners();
  98. this.cancelOmniauthInAppBrowserListeners = (function() {});
  99. return this.addScopeMethods();
  100. },
  101. initializeListeners: function() {
  102. this.listener = angular.bind(this, this.handlePostMessage);
  103. if ($window.addEventListener) {
  104. return $window.addEventListener("message", this.listener, false);
  105. }
  106. },
  107. cancel: function(reason) {
  108. if (this.requestCredentialsPollingTimer != null) {
  109. $timeout.cancel(this.requestCredentialsPollingTimer);
  110. }
  111. this.cancelOmniauthInAppBrowserListeners();
  112. if (this.dfd != null) {
  113. this.rejectDfd(reason);
  114. }
  115. return $timeout(((function(_this) {
  116. return function() {
  117. return _this.requestCredentialsPollingTimer = null;
  118. };
  119. })(this)), 0);
  120. },
  121. destroy: function() {
  122. this.cancel();
  123. if ($window.removeEventListener) {
  124. return $window.removeEventListener("message", this.listener, false);
  125. }
  126. },
  127. handlePostMessage: function(ev) {
  128. var error, oauthRegistration;
  129. if (ev.data.message === 'deliverCredentials') {
  130. delete ev.data.message;
  131. oauthRegistration = ev.data.oauth_registration;
  132. delete ev.data.oauth_registration;
  133. this.handleValidAuth(ev.data, true);
  134. $rootScope.$broadcast('auth:login-success', ev.data);
  135. if (oauthRegistration) {
  136. $rootScope.$broadcast('auth:oauth-registration', ev.data);
  137. }
  138. }
  139. if (ev.data.message === 'authFailure') {
  140. error = {
  141. reason: 'unauthorized',
  142. errors: [ev.data.error]
  143. };
  144. this.cancel(error);
  145. return $rootScope.$broadcast('auth:login-error', error);
  146. }
  147. },
  148. addScopeMethods: function() {
  149. $rootScope.user = this.user;
  150. $rootScope.authenticate = angular.bind(this, this.authenticate);
  151. $rootScope.signOut = angular.bind(this, this.signOut);
  152. $rootScope.destroyAccount = angular.bind(this, this.destroyAccount);
  153. $rootScope.submitRegistration = angular.bind(this, this.submitRegistration);
  154. $rootScope.submitLogin = angular.bind(this, this.submitLogin);
  155. $rootScope.requestPasswordReset = angular.bind(this, this.requestPasswordReset);
  156. $rootScope.updatePassword = angular.bind(this, this.updatePassword);
  157. $rootScope.updateAccount = angular.bind(this, this.updateAccount);
  158. if (this.getConfig().validateOnPageLoad) {
  159. return this.validateUser({
  160. config: this.getSavedConfig()
  161. });
  162. }
  163. },
  164. submitRegistration: function(params, opts) {
  165. var successUrl;
  166. if (opts == null) {
  167. opts = {};
  168. }
  169. successUrl = this.getResultOrValue(this.getConfig(opts.config).confirmationSuccessUrl);
  170. angular.extend(params, {
  171. confirm_success_url: successUrl,
  172. config_name: this.getCurrentConfigName(opts.config)
  173. });
  174. return $http.post(this.apiUrl(opts.config) + this.getConfig(opts.config).emailRegistrationPath, params).success(function(resp) {
  175. return $rootScope.$broadcast('auth:registration-email-success', params);
  176. }).error(function(resp) {
  177. return $rootScope.$broadcast('auth:registration-email-error', resp);
  178. });
  179. },
  180. submitLogin: function(params, opts) {
  181. if (opts == null) {
  182. opts = {};
  183. }
  184. this.initDfd();
  185. $http.post(this.apiUrl(opts.config) + this.getConfig(opts.config).emailSignInPath, params).success((function(_this) {
  186. // $http.post(this.apiUrl(opts.config) + this.getConfig(opts.config).checkLoginUrl, params).success((function(_this) {
  187. return function(resp) {
  188. var authData;
  189. _this.setConfigName(opts.config);
  190. authData = _this.getConfig(opts.config).handleLoginResponse(resp, _this);
  191. _this.handleValidAuth(authData, true);
  192. return $rootScope.$broadcast('auth:login-success', _this.user);
  193. };
  194. })(this)).error((function(_this) {
  195. return function(resp) {
  196. _this.rejectDfd({
  197. reason: 'unauthorized',
  198. errors: ['Invalid credentials']
  199. });
  200. return $rootScope.$broadcast('auth:login-error', resp);
  201. };
  202. })(this));
  203. return this.dfd.promise;
  204. },
  205. userIsAuthenticated: function() {
  206. return this.retrieveData('auth_headers') && this.user.signedIn && !this.tokenHasExpired();
  207. },
  208. requestPasswordReset: function(params, opts) {
  209. var successUrl;
  210. if (opts == null) {
  211. opts = {};
  212. }
  213. successUrl = this.getResultOrValue(this.getConfig(opts.config).passwordResetSuccessUrl);
  214. params.redirect_url = successUrl;
  215. if (opts.config != null) {
  216. params.config_name = opts.config;
  217. }
  218. return $http.post(this.apiUrl(opts.config) + this.getConfig(opts.config).passwordResetPath, params).success(function(resp) {
  219. return $rootScope.$broadcast('auth:password-reset-request-success', params);
  220. }).error(function(resp) {
  221. return $rootScope.$broadcast('auth:password-reset-request-error', resp);
  222. });
  223. },
  224. updatePassword: function(params) {
  225. return $http.put(this.apiUrl() + this.getConfig().passwordUpdatePath, params).success((function(_this) {
  226. return function(resp) {
  227. $rootScope.$broadcast('auth:password-change-success', resp);
  228. return _this.mustResetPassword = false;
  229. };
  230. })(this)).error(function(resp) {
  231. return $rootScope.$broadcast('auth:password-change-error', resp);
  232. });
  233. },
  234. updateAccount: function(params) {
  235. return $http.put(this.apiUrl() + this.getConfig().accountUpdatePath, params).success((function(_this) {
  236. return function(resp) {
  237. var curHeaders, key, newHeaders, updateResponse, val, _ref;
  238. updateResponse = _this.getConfig().handleAccountUpdateResponse(resp);
  239. curHeaders = _this.retrieveData('auth_headers');
  240. angular.extend(_this.user, updateResponse);
  241. if (curHeaders) {
  242. newHeaders = {};
  243. _ref = _this.getConfig().tokenFormat;
  244. for (key in _ref) {
  245. val = _ref[key];
  246. if (curHeaders[key] && updateResponse[key]) {
  247. newHeaders[key] = updateResponse[key];
  248. }
  249. }
  250. _this.setAuthHeaders(newHeaders);
  251. }
  252. return $rootScope.$broadcast('auth:account-update-success', resp);
  253. };
  254. })(this)).error(function(resp) {
  255. return $rootScope.$broadcast('auth:account-update-error', resp);
  256. });
  257. },
  258. destroyAccount: function(params) {
  259. return $http["delete"](this.apiUrl() + this.getConfig().accountUpdatePath, params).success((function(_this) {
  260. return function(resp) {
  261. _this.invalidateTokens();
  262. return $rootScope.$broadcast('auth:account-destroy-success', resp);
  263. };
  264. })(this)).error(function(resp) {
  265. return $rootScope.$broadcast('auth:account-destroy-error', resp);
  266. });
  267. },
  268. authenticate: function(provider, opts) {
  269. if (opts == null) {
  270. opts = {};
  271. }
  272. if (this.dfd == null) {
  273. this.setConfigName(opts.config);
  274. this.initDfd();
  275. this.openAuthWindow(provider, opts);
  276. }
  277. return this.dfd.promise;
  278. },
  279. setConfigName: function(configName) {
  280. if (configName == null) {
  281. configName = defaultConfigName;
  282. }
  283. return this.persistData('currentConfigName', configName, configName);
  284. },
  285. openAuthWindow: function(provider, opts) {
  286. var authUrl, omniauthWindowType;
  287. omniauthWindowType = this.getConfig(opts.config).omniauthWindowType;
  288. authUrl = this.buildAuthUrl(omniauthWindowType, provider, opts);
  289. if (omniauthWindowType === 'newWindow') {
  290. return this.requestCredentialsViaPostMessage(this.createPopup(authUrl));
  291. } else if (omniauthWindowType === 'inAppBrowser') {
  292. return this.requestCredentialsViaExecuteScript(this.createPopup(authUrl));
  293. } else if (omniauthWindowType === 'sameWindow') {
  294. return this.visitUrl(authUrl);
  295. } else {
  296. throw 'Unsupported omniauthWindowType "#{omniauthWindowType}"';
  297. }
  298. },
  299. visitUrl: function(url) {
  300. return $window.location.replace(url);
  301. },
  302. buildAuthUrl: function(omniauthWindowType, provider, opts) {
  303. var authUrl, key, params, val;
  304. if (opts == null) {
  305. opts = {};
  306. }
  307. authUrl = this.getConfig(opts.config).apiUrl;
  308. authUrl += this.getConfig(opts.config).authProviderPaths[provider];
  309. authUrl += '?auth_origin_url=' + encodeURIComponent($window.location.href);
  310. params = angular.extend({}, opts.params || {}, {
  311. omniauth_window_type: omniauthWindowType
  312. });
  313. for (key in params) {
  314. val = params[key];
  315. authUrl += '&';
  316. authUrl += encodeURIComponent(key);
  317. authUrl += '=';
  318. authUrl += encodeURIComponent(val);
  319. }
  320. return authUrl;
  321. },
  322. requestCredentialsViaPostMessage: function(authWindow) {
  323. if (authWindow.closed) {
  324. return this.handleAuthWindowClose(authWindow);
  325. } else {
  326. authWindow.postMessage("requestCredentials", "*");
  327. return this.requestCredentialsPollingTimer = $timeout(((function(_this) {
  328. return function() {
  329. return _this.requestCredentialsViaPostMessage(authWindow);
  330. };
  331. })(this)), 500);
  332. }
  333. },
  334. requestCredentialsViaExecuteScript: function(authWindow) {
  335. var handleAuthWindowClose, handleLoadStop;
  336. this.cancelOmniauthInAppBrowserListeners();
  337. handleAuthWindowClose = this.handleAuthWindowClose.bind(this, authWindow);
  338. handleLoadStop = this.handleLoadStop.bind(this, authWindow);
  339. authWindow.addEventListener('loadstop', handleLoadStop);
  340. authWindow.addEventListener('exit', handleAuthWindowClose);
  341. return this.cancelOmniauthInAppBrowserListeners = function() {
  342. authWindow.removeEventListener('loadstop', handleLoadStop);
  343. return authWindow.removeEventListener('exit', handleAuthWindowClose);
  344. };
  345. },
  346. handleLoadStop: function(authWindow) {
  347. _this = this;
  348. return authWindow.executeScript({
  349. code: 'requestCredentials()'
  350. }, function(response) {
  351. var data, ev;
  352. data = response[0];
  353. if (data) {
  354. ev = new Event('message');
  355. ev.data = data;
  356. _this.cancelOmniauthInAppBrowserListeners();
  357. $window.dispatchEvent(ev);
  358. _this.initDfd();
  359. return authWindow.close();
  360. }
  361. });
  362. },
  363. handleAuthWindowClose: function(authWindow) {
  364. this.cancel({
  365. reason: 'unauthorized',
  366. errors: ['User canceled login']
  367. });
  368. this.cancelOmniauthInAppBrowserListeners;
  369. return $rootScope.$broadcast('auth:window-closed');
  370. },
  371. createPopup: function(url) {
  372. return $window.open(url, '_blank');
  373. },
  374. resolveDfd: function() {
  375. this.dfd.resolve(this.user);
  376. return $timeout(((function(_this) {
  377. return function() {
  378. _this.dfd = null;
  379. if (!$rootScope.$$phase) {
  380. return $rootScope.$digest();
  381. }
  382. };
  383. })(this)), 0);
  384. },
  385. buildQueryString: function(param, prefix) {
  386. var encoded, k, str, v;
  387. str = [];
  388. for (k in param) {
  389. v = param[k];
  390. k = prefix ? prefix + "[" + k + "]" : k;
  391. encoded = angular.isObject(v) ? this.buildQueryString(v, k) : k + "=" + encodeURIComponent(v);
  392. str.push(encoded);
  393. }
  394. return str.join("&");
  395. },
  396. parseLocation: function(location) {
  397. var i, obj, pair, pairs;
  398. pairs = location.substring(1).split('&');
  399. obj = {};
  400. pair = void 0;
  401. i = void 0;
  402. for (i in pairs) {
  403. i = i;
  404. if (pairs[i] === '') {
  405. continue;
  406. }
  407. pair = pairs[i].split('=');
  408. obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  409. }
  410. return obj;
  411. },
  412. validateUser: function(opts) {
  413. var clientId, configName, expiry, location_parse, params, search, token, uid, url;
  414. if (opts == null) {
  415. opts = {};
  416. }
  417. configName = opts.config;
  418. if (this.dfd == null) {
  419. //FIX timer refresh expiry
  420. if (this.userIsAuthenticated()) {
  421. this.initDfd();
  422. if (this.getConfig().forceValidateToken) {
  423. this.validateToken({
  424. config: configName
  425. });
  426. }
  427. }
  428. }
  429. if (this.dfd == null) {
  430. this.initDfd();
  431. if (this.userIsAuthenticated()) {
  432. this.resolveDfd();
  433. } else {
  434. search = $location.search();
  435. location_parse = this.parseLocation(window.location.search);
  436. params = Object.keys(search).length === 0 ? location_parse : search;
  437. token = params.auth_token || params.token;
  438. if (token !== void 0) {
  439. clientId = params.client_id;
  440. uid = params.uid;
  441. expiry = params.expiry;
  442. configName = params.config;
  443. this.setConfigName(configName);
  444. this.mustResetPassword = params.reset_password;
  445. this.firstTimeLogin = params.account_confirmation_success;
  446. this.oauthRegistration = params.oauth_registration;
  447. this.setAuthHeaders(this.buildAuthHeaders({
  448. token: token,
  449. clientId: clientId,
  450. uid: uid,
  451. expiry: expiry
  452. }));
  453. url = $location.path() || '/';
  454. ['token', 'client_id', 'uid', 'expiry', 'config', 'reset_password', 'account_confirmation_success', 'oauth_registration'].forEach(function(prop) {
  455. return delete params[prop];
  456. });
  457. if (Object.keys(params).length > 0) {
  458. url += '?' + this.buildQueryString(params);
  459. }
  460. $location.url(url);
  461. } else if (this.retrieveData('currentConfigName')) {
  462. configName = this.retrieveData('currentConfigName');
  463. }
  464. if (!isEmpty(this.retrieveData('auth_headers'))) {
  465. if (this.tokenHasExpired()) {
  466. $rootScope.$broadcast('auth:session-expired');
  467. this.rejectDfd({
  468. reason: 'unauthorized',
  469. errors: ['Session expired.']
  470. });
  471. } else {
  472. this.validateToken({
  473. config: configName
  474. });
  475. }
  476. } else {
  477. this.rejectDfd({
  478. reason: 'unauthorized',
  479. errors: ['No credentials']
  480. });
  481. $rootScope.$broadcast('auth:invalid');
  482. }
  483. }
  484. }
  485. return this.dfd.promise;
  486. },
  487. validateToken: function(opts) {
  488. if (opts == null) {
  489. opts = {};
  490. }
  491. if (!this.tokenHasExpired()) {
  492. return $http.get(this.apiUrl(opts.config) + this.getConfig(opts.config).tokenValidationPath).success((function(_this) {
  493. return function(resp) {
  494. var authData;
  495. authData = _this.getConfig(opts.config).handleTokenValidationResponse(resp);
  496. _this.handleValidAuth(authData);
  497. if (_this.firstTimeLogin) {
  498. $rootScope.$broadcast('auth:email-confirmation-success', _this.user);
  499. }
  500. if (_this.oauthRegistration) {
  501. $rootScope.$broadcast('auth:oauth-registration', _this.user);
  502. }
  503. if (_this.mustResetPassword) {
  504. $rootScope.$broadcast('auth:password-reset-confirm-success', _this.user);
  505. }
  506. //fix auth expiry
  507. _this.setAuthHeaders(_this.buildAuthHeaders({
  508. token: authData.auth_token,
  509. clientId: authData.client_id,
  510. uid: authData.uid,
  511. expiry: authData.expiry
  512. }));
  513. return $rootScope.$broadcast('auth:validation-success', _this.user);
  514. };
  515. })(this)).error((function(_this) {
  516. return function(data) {
  517. if (_this.firstTimeLogin) {
  518. $rootScope.$broadcast('auth:email-confirmation-error', data);
  519. }
  520. if (_this.mustResetPassword) {
  521. $rootScope.$broadcast('auth:password-reset-confirm-error', data);
  522. }
  523. $rootScope.$broadcast('auth:validation-error', data);
  524. return _this.rejectDfd({
  525. reason: 'unauthorized',
  526. errors: data.errors
  527. });
  528. };
  529. })(this));
  530. } else {
  531. return this.rejectDfd({
  532. reason: 'unauthorized',
  533. errors: ['Expired credentials']
  534. });
  535. }
  536. },
  537. tokenHasExpired: function() {
  538. var expiry, now;
  539. expiry = this.getExpiry();
  540. now = new Date().getTime();
  541. return expiry && expiry < now;
  542. },
  543. getExpiry: function() {
  544. return this.getConfig().parseExpiry(this.retrieveData('auth_headers') || {});
  545. },
  546. invalidateTokens: function() {
  547. var key, val, _ref;
  548. _ref = this.user;
  549. for (key in _ref) {
  550. val = _ref[key];
  551. delete this.user[key];
  552. }
  553. this.deleteData('currentConfigName');
  554. if (this.timer != null) {
  555. $timeout.cancel(this.timer);
  556. }
  557. return this.deleteData('auth_headers');
  558. },
  559. signOut: function() {
  560. return $http["delete"](this.apiUrl() + this.getConfig().signOutUrl).success((function(_this) {
  561. return function(resp) {
  562. _this.invalidateTokens();
  563. return $rootScope.$broadcast('auth:logout-success');
  564. };
  565. })(this)).error((function(_this) {
  566. return function(resp) {
  567. _this.invalidateTokens();
  568. return $rootScope.$broadcast('auth:logout-error', resp);
  569. };
  570. })(this));
  571. },
  572. handleValidAuth: function(user, setHeader) {
  573. if (setHeader == null) {
  574. setHeader = false;
  575. }
  576. if (this.requestCredentialsPollingTimer != null) {
  577. $timeout.cancel(this.requestCredentialsPollingTimer);
  578. }
  579. this.cancelOmniauthInAppBrowserListeners();
  580. if (this.user.menu) {
  581. this.user.menu = undefined;
  582. }
  583. angular.extend(this.user, user);
  584. //fix login
  585. if (user.error) {
  586. this.user.signedIn = false;
  587. } else {
  588. this.user.signedIn = true;
  589. }
  590. //fix
  591. //this.user.signedIn = true;
  592. this.user.configName = this.getCurrentConfigName();
  593. if (setHeader) {
  594. this.setAuthHeaders(this.buildAuthHeaders({
  595. token: this.user.auth_token,
  596. clientId: this.user.client_id,
  597. uid: this.user.uid,
  598. expiry: this.user.expiry
  599. }));
  600. }
  601. return this.resolveDfd();
  602. },
  603. buildAuthHeaders: function(ctx) {
  604. var headers, key, val, _ref;
  605. headers = {};
  606. _ref = this.getConfig().tokenFormat;
  607. for (key in _ref) {
  608. val = _ref[key];
  609. headers[key] = $interpolate(val)(ctx);
  610. }
  611. return headers;
  612. },
  613. persistData: function(key, val, configName) {
  614. if (this.getConfig(configName).storage instanceof Object) {
  615. return this.getConfig(configName).storage.persistData(key, val, this.getConfig(configName));
  616. } else {
  617. switch (this.getConfig(configName).storage) {
  618. case 'localStorage':
  619. return $window.localStorage.setItem(key, JSON.stringify(val));
  620. default:
  621. return ipCookie(key, val, {
  622. path: '/',
  623. expires: 9999,
  624. expirationUnit: 'days'
  625. });
  626. }
  627. }
  628. },
  629. retrieveData: function(key) {
  630. if (this.getConfig().storage instanceof Object) {
  631. return this.getConfig().storage.retrieveData(key);
  632. } else {
  633. switch (this.getConfig().storage) {
  634. case 'localStorage':
  635. return JSON.parse($window.localStorage.getItem(key));
  636. default:
  637. return ipCookie(key);
  638. }
  639. }
  640. },
  641. deleteData: function(key) {
  642. if (this.getConfig().storage instanceof Object) {
  643. this.getConfig().storage.deleteData(key);
  644. }
  645. switch (this.getConfig().storage) {
  646. case 'localStorage':
  647. return $window.localStorage.removeItem(key);
  648. default:
  649. return ipCookie.remove(key, {
  650. path: '/'
  651. });
  652. }
  653. },
  654. setAuthHeaders: function(h) {
  655. var expiry, newHeaders, now, result;
  656. newHeaders = angular.extend(this.retrieveData('auth_headers') || {}, h);
  657. result = this.persistData('auth_headers', newHeaders);
  658. expiry = this.getExpiry();
  659. now = new Date().getTime();
  660. if (expiry > now) {
  661. if (this.timer != null) {
  662. $timeout.cancel(this.timer);
  663. }
  664. this.timer = $timeout(((function(_this) {
  665. return function() {
  666. return _this.validateUser({
  667. config: _this.getSavedConfig()
  668. });
  669. };
  670. })(this)), parseInt(expiry - now));
  671. }
  672. return result;
  673. },
  674. initDfd: function() {
  675. return this.dfd = $q.defer();
  676. },
  677. rejectDfd: function(reason) {
  678. this.invalidateTokens();
  679. if (this.dfd != null) {
  680. this.dfd.reject(reason);
  681. return $timeout(((function(_this) {
  682. return function() {
  683. return _this.dfd = null;
  684. };
  685. })(this)), 0);
  686. }
  687. },
  688. apiUrl: function(configName) {
  689. if (this.getConfig(configName).proxyIf()) {
  690. return this.getConfig(configName).proxyUrl;
  691. } else {
  692. return this.getConfig(configName).apiUrl;
  693. }
  694. },
  695. getConfig: function(name) {
  696. return configs[this.getCurrentConfigName(name)];
  697. },
  698. getResultOrValue: function(arg) {
  699. if (typeof arg === 'function') {
  700. return arg();
  701. } else {
  702. return arg;
  703. }
  704. },
  705. getCurrentConfigName: function(name) {
  706. return name || this.getSavedConfig();
  707. },
  708. getSavedConfig: function() {
  709. var c, error, hasLocalStorage, key;
  710. c = void 0;
  711. key = 'currentConfigName';
  712. hasLocalStorage = false;
  713. try {
  714. hasLocalStorage = !!$window.localStorage;
  715. } catch (_error) {
  716. error = _error;
  717. }
  718. if (hasLocalStorage) {
  719. if (c == null) {
  720. c = JSON.parse($window.localStorage.getItem(key));
  721. }
  722. }
  723. if (c == null) {
  724. c = ipCookie(key);
  725. }
  726. return c || defaultConfigName;
  727. }
  728. };
  729. };
  730. })(this)
  731. ]
  732. };
  733. }).config([
  734. '$httpProvider',
  735. function($httpProvider) {
  736. var httpMethods, tokenIsCurrent, updateHeadersFromResponse;
  737. tokenIsCurrent = function($auth, headers) {
  738. var newTokenExpiry, oldTokenExpiry;
  739. oldTokenExpiry = Number($auth.getExpiry());
  740. newTokenExpiry = Number($auth.getConfig().parseExpiry(headers || {}));
  741. return newTokenExpiry >= oldTokenExpiry;
  742. };
  743. updateHeadersFromResponse = function($auth, resp) {
  744. var key, newHeaders, val, _ref;
  745. newHeaders = {};
  746. _ref = $auth.getConfig().tokenFormat;
  747. for (key in _ref) {
  748. val = _ref[key];
  749. if (resp.headers(key)) {
  750. newHeaders[key] = resp.headers(key);
  751. }
  752. }
  753. if (tokenIsCurrent($auth, newHeaders)) {
  754. return $auth.setAuthHeaders(newHeaders);
  755. }
  756. };
  757. $httpProvider.interceptors.push([
  758. '$injector',
  759. function($injector) {
  760. return {
  761. request: function(req) {
  762. $injector.invoke([
  763. '$http', '$auth',
  764. function($http, $auth) {
  765. var key, val, _ref, _results;
  766. if (req.url.match($auth.apiUrl())) {
  767. _ref = $auth.retrieveData('auth_headers');
  768. _results = [];
  769. for (key in _ref) {
  770. val = _ref[key];
  771. _results.push(req.headers[key] = val);
  772. }
  773. return _results;
  774. }
  775. }
  776. ]);
  777. return req;
  778. },
  779. response: function(resp) {
  780. $injector.invoke([
  781. '$http', '$auth',
  782. function($http, $auth) {
  783. if (resp.config.url.match($auth.apiUrl())) {
  784. return updateHeadersFromResponse($auth, resp);
  785. }
  786. }
  787. ]);
  788. return resp;
  789. },
  790. responseError: function(resp) {
  791. $injector.invoke([
  792. '$http', '$auth',
  793. function($http, $auth) {
  794. if (resp.config.url.match($auth.apiUrl())) {
  795. return updateHeadersFromResponse($auth, resp);
  796. }
  797. }
  798. ]);
  799. return $injector.get('$q').reject(resp);
  800. }
  801. };
  802. }
  803. ]);
  804. httpMethods = ['get', 'post', 'put', 'patch', 'delete'];
  805. return angular.forEach(httpMethods, function(method) {
  806. var _base;
  807. if ((_base = $httpProvider.defaults.headers)[method] == null) {
  808. _base[method] = {};
  809. }
  810. return $httpProvider.defaults.headers[method]['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
  811. });
  812. }
  813. ]).run([
  814. '$auth', '$window', '$rootScope',
  815. function($auth, $window, $rootScope) {
  816. return $auth.initialize();
  817. }
  818. ]);
  819. window.isOldIE = function() {
  820. var nav, out, version;
  821. out = false;
  822. nav = navigator.userAgent.toLowerCase();
  823. if (nav && nav.indexOf('msie') !== -1) {
  824. version = parseInt(nav.split('msie')[1]);
  825. if (version < 10) {
  826. out = true;
  827. }
  828. }
  829. return out;
  830. };
  831. window.isIE = function() {
  832. var nav;
  833. nav = navigator.userAgent.toLowerCase();
  834. return (nav && nav.indexOf('msie') !== -1) || !!navigator.userAgent.match(/Trident.*rv\:11\./);
  835. };
  836. window.isEmpty = function(obj) {
  837. var key, val;
  838. if (!obj) {
  839. return true;
  840. }
  841. if (obj.length > 0) {
  842. return false;
  843. }
  844. if (obj.length === 0) {
  845. return true;
  846. }
  847. for (key in obj) {
  848. val = obj[key];
  849. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  850. return false;
  851. }
  852. }
  853. return true;
  854. };