ng-token-auth.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. "undefined" != typeof module && "undefined" != typeof exports && module.exports === exports && (module.exports = "ng-token-auth"), angular.module("ng-token-auth", ["ipCookie"]).provider("$auth", function() {
  2. var t, e;
  3. return t = {
  4. "default": {
  5. apiUrl: "/api",
  6. signOutUrl: "/auth/sign_out",
  7. emailSignInPath: "/auth/sign_in",
  8. emailRegistrationPath: "/auth",
  9. accountUpdatePath: "/auth",
  10. accountDeletePath: "/auth",
  11. confirmationSuccessUrl: function() {
  12. return window.location.href
  13. },
  14. passwordResetPath: "/auth/password",
  15. passwordUpdatePath: "/auth/password",
  16. passwordResetSuccessUrl: function() {
  17. return window.location.href
  18. },
  19. tokenValidationPath: "/auth/validate_token",
  20. proxyIf: function() {
  21. return !1
  22. },
  23. proxyUrl: "/proxy",
  24. validateOnPageLoad: !0,
  25. omniauthWindowType: "sameWindow",
  26. storage: "cookies",
  27. tokenFormat: {
  28. "access-token": "{{ token }}",
  29. "token-type": "Bearer",
  30. client: "{{ clientId }}",
  31. expiry: "{{ expiry }}",
  32. uid: "{{ uid }}"
  33. },
  34. parseExpiry: function(t) {
  35. return 1e3 * parseInt(t.expiry, 10) || null
  36. },
  37. handleLoginResponse: function(t) {
  38. return t.data
  39. },
  40. handleAccountUpdateResponse: function(t) {
  41. return t.data
  42. },
  43. handleTokenValidationResponse: function(t) {
  44. return t.data
  45. },
  46. authProviderPaths: {
  47. github: "/auth/github",
  48. facebook: "/auth/facebook",
  49. google: "/auth/google_oauth2"
  50. }
  51. }
  52. }, e = "default", {
  53. configure: function(n) {
  54. var r, i, s, a, o, u, c, d, h;
  55. if (n instanceof Array && n.length) {
  56. for (a = d = 0, h = n.length; h > d; a = ++d) {
  57. r = n[a], u = null;
  58. for (o in r) c = r[o], u = o, 0 === a && (e = u);
  59. i = angular.copy(t["default"]), s = {}, s[u] = angular.extend(i, r[u]), angular.extend(t, s)
  60. }
  61. "default" !== e && delete t["default"]
  62. } else {
  63. if (!(n instanceof Object)) throw "Invalid argument: ng-token-auth config should be an Array or Object.";
  64. angular.extend(t["default"], n)
  65. }
  66. return t
  67. },
  68. $get: ["$http", "$q", "$location", "ipCookie", "$window", "$timeout", "$rootScope", "$interpolate", function(n) {
  69. return function(r, i, s, a, o, u, c, d) {
  70. return {
  71. header: null,
  72. dfd: null,
  73. user: {},
  74. mustResetPassword: !1,
  75. listener: null,
  76. initialize: function() {
  77. return this.initializeListeners(), this.cancelOmniauthInAppBrowserListeners = function() {}, this.addScopeMethods()
  78. },
  79. initializeListeners: function() {
  80. return this.listener = angular.bind(this, this.handlePostMessage), o.addEventListener ? o.addEventListener("message", this.listener, !1) : void 0
  81. },
  82. cancel: function(t) {
  83. return null != this.requestCredentialsPollingTimer && u.cancel(this.requestCredentialsPollingTimer), this.cancelOmniauthInAppBrowserListeners(), null != this.dfd && this.rejectDfd(t), u(function(t) {
  84. return function() {
  85. return t.requestCredentialsPollingTimer = null
  86. }
  87. }(this), 0)
  88. },
  89. destroy: function() {
  90. return this.cancel(), o.removeEventListener ? o.removeEventListener("message", this.listener, !1) : void 0
  91. },
  92. handlePostMessage: function(t) {
  93. var e, n;
  94. return "deliverCredentials" === t.data.message && (delete t.data.message, n = t.data.oauth_registration, delete t.data.oauth_registration, this.handleValidAuth(t.data, !0), c.$broadcast("auth:login-success", t.data), n && c.$broadcast("auth:oauth-registration", t.data)), "authFailure" === t.data.message ? (e = {
  95. reason: "unauthorized",
  96. errors: [t.data.error]
  97. }, this.cancel(e), c.$broadcast("auth:login-error", e)) : void 0
  98. },
  99. addScopeMethods: function() {
  100. return c.user = this.user, c.authenticate = angular.bind(this, this.authenticate), c.signOut = angular.bind(this, this.signOut), c.destroyAccount = angular.bind(this, this.destroyAccount), c.submitRegistration = angular.bind(this, this.submitRegistration), c.submitLogin = angular.bind(this, this.submitLogin), c.requestPasswordReset = angular.bind(this, this.requestPasswordReset), c.updatePassword = angular.bind(this, this.updatePassword), c.updateAccount = angular.bind(this, this.updateAccount), this.getConfig().validateOnPageLoad ? this.validateUser({
  101. config: this.getSavedConfig()
  102. }) : void 0
  103. },
  104. submitRegistration: function(t, e) {
  105. var n;
  106. return null == e && (e = {}), n = this.getResultOrValue(this.getConfig(e.config).confirmationSuccessUrl), angular.extend(t, {
  107. confirm_success_url: n,
  108. config_name: this.getCurrentConfigName(e.config)
  109. }), r.post(this.apiUrl(e.config) + this.getConfig(e.config).emailRegistrationPath, t).success(function(e) {
  110. return c.$broadcast("auth:registration-email-success", t)
  111. }).error(function(t) {
  112. return c.$broadcast("auth:registration-email-error", t)
  113. })
  114. },
  115. submitLogin: function(t, e) {
  116. return null == e && (e = {}), this.initDfd(), r.post(this.apiUrl(e.config) + this.getConfig(e.config).emailSignInPath, t).success(function(t) {
  117. return function(n) {
  118. var r;
  119. return t.setConfigName(e.config), r = t.getConfig(e.config).handleLoginResponse(n, t), t.handleValidAuth(r), c.$broadcast("auth:login-success", t.user),
  120. sessionStorage.setItem('header', JSON.stringify(t.getConfig(e.config).handleLoginResponse(n, t)));
  121. }
  122. }(this)).error(function(t) {
  123. return function(e) {
  124. return t.rejectDfd({
  125. reason: "unauthorized",
  126. errors: ["Invalid credentials"]
  127. }), c.$broadcast("auth:login-error", e)
  128. }
  129. }(this)), this.dfd.promise
  130. },
  131. userIsAuthenticated: function() {
  132. return this.retrieveData("auth_headers") && this.user.signedIn && !this.tokenHasExpired()
  133. },
  134. requestPasswordReset: function(t, e) {
  135. var n;
  136. return null == e && (e = {}), n = this.getResultOrValue(this.getConfig(e.config).passwordResetSuccessUrl), t.redirect_url = n, null != e.config && (t.config_name = e.config), r.post(this.apiUrl(e.config) + this.getConfig(e.config).passwordResetPath, t).success(function(e) {
  137. return c.$broadcast("auth:password-reset-request-success", t)
  138. }).error(function(t) {
  139. return c.$broadcast("auth:password-reset-request-error", t)
  140. })
  141. },
  142. updatePassword: function(t) {
  143. return r.put(this.apiUrl() + this.getConfig().passwordUpdatePath, t).success(function(t) {
  144. return function(e) {
  145. return c.$broadcast("auth:password-change-success", e), t.mustResetPassword = !1
  146. }
  147. }(this)).error(function(t) {
  148. return c.$broadcast("auth:password-change-error", t)
  149. })
  150. },
  151. updateAccount: function(t) {
  152. return r.put(this.apiUrl() + this.getConfig().accountUpdatePath, t).success(function(t) {
  153. return function(e) {
  154. var n, r, i, s, a, o;
  155. if (s = t.getConfig().handleAccountUpdateResponse(e), n = t.retrieveData("auth_headers"), angular.extend(t.user, s), n) {
  156. i = {}, o = t.getConfig().tokenFormat;
  157. for (r in o) a = o[r], n[r] && s[r] && (i[r] = s[r]);
  158. t.setAuthHeaders(i)
  159. }
  160. return c.$broadcast("auth:account-update-success", e)
  161. }
  162. }(this)).error(function(t) {
  163. return c.$broadcast("auth:account-update-error", t)
  164. })
  165. },
  166. destroyAccount: function(t) {
  167. return r["delete"](this.apiUrl() + this.getConfig().accountUpdatePath, t).success(function(t) {
  168. return function(e) {
  169. return t.invalidateTokens(), c.$broadcast("auth:account-destroy-success", e)
  170. }
  171. }(this)).error(function(t) {
  172. return c.$broadcast("auth:account-destroy-error", t)
  173. })
  174. },
  175. authenticate: function(t, e) {
  176. return null == e && (e = {}), null == this.dfd && (this.setConfigName(e.config), this.initDfd(), this.openAuthWindow(t, e)), this.dfd.promise
  177. },
  178. setConfigName: function(t) {
  179. return null == t && (t = e), this.persistData("currentConfigName", t, t)
  180. },
  181. openAuthWindow: function(t, e) {
  182. var n, r;
  183. if (r = this.getConfig(e.config).omniauthWindowType, n = this.buildAuthUrl(r, t, e), "newWindow" === r) return this.requestCredentialsViaPostMessage(this.createPopup(n));
  184. if ("inAppBrowser" === r) return this.requestCredentialsViaExecuteScript(this.createPopup(n));
  185. if ("sameWindow" === r) return this.visitUrl(n);
  186. throw 'Unsupported omniauthWindowType "#{omniauthWindowType}"'
  187. },
  188. visitUrl: function(t) {
  189. return o.location.replace(t)
  190. },
  191. buildAuthUrl: function(t, e, n) {
  192. var r, i, s, a;
  193. null == n && (n = {}), r = this.getConfig(n.config).apiUrl, r += this.getConfig(n.config).authProviderPaths[e], r += "?auth_origin_url=" + encodeURIComponent(o.location.href), s = angular.extend({}, n.params || {}, {
  194. omniauth_window_type: t
  195. });
  196. for (i in s) a = s[i], r += "&", r += encodeURIComponent(i), r += "=", r += encodeURIComponent(a);
  197. return r
  198. },
  199. requestCredentialsViaPostMessage: function(t) {
  200. return t.closed ? this.handleAuthWindowClose(t) : (t.postMessage("requestCredentials", "*"), this.requestCredentialsPollingTimer = u(function(e) {
  201. return function() {
  202. return e.requestCredentialsViaPostMessage(t)
  203. }
  204. }(this), 500))
  205. },
  206. requestCredentialsViaExecuteScript: function(t) {
  207. var e, n;
  208. return this.cancelOmniauthInAppBrowserListeners(), e = this.handleAuthWindowClose.bind(this, t), n = this.handleLoadStop.bind(this, t), t.addEventListener("loadstop", n), t.addEventListener("exit", e), this.cancelOmniauthInAppBrowserListeners = function() {
  209. return t.removeEventListener("loadstop", n), t.removeEventListener("exit", e)
  210. }
  211. },
  212. handleLoadStop: function(t) {
  213. return n = this, t.executeScript({
  214. code: "requestCredentials()"
  215. }, function(e) {
  216. var r, i;
  217. return r = e[0], r ? (i = new Event("message"), i.data = r, n.cancelOmniauthInAppBrowserListeners(), o.dispatchEvent(i), n.initDfd(), t.close()) : void 0
  218. })
  219. },
  220. handleAuthWindowClose: function(t) {
  221. return this.cancel({
  222. reason: "unauthorized",
  223. errors: ["User canceled login"]
  224. }), this.cancelOmniauthInAppBrowserListeners, c.$broadcast("auth:window-closed")
  225. },
  226. createPopup: function(t) {
  227. return o.open(t, "_blank")
  228. },
  229. resolveDfd: function() {
  230. return this.dfd.resolve(this.user), u(function(t) {
  231. return function() {
  232. return t.dfd = null, c.$$phase ? void 0 : c.$digest()
  233. }
  234. }(this), 0)
  235. },
  236. buildQueryString: function(t, e) {
  237. var n, r, i, s;
  238. i = [];
  239. for (r in t) s = t[r], r = e ? e + "[" + r + "]" : r, n = angular.isObject(s) ? this.buildQueryString(s, r) : r + "=" + encodeURIComponent(s), i.push(n);
  240. return i.join("&")
  241. },
  242. parseLocation: function(t) {
  243. var e, n, r, i;
  244. i = t.substring(1).split("&"), n = {}, r = void 0, e = void 0;
  245. for (e in i) e = e, "" !== i[e] && (r = i[e].split("="), n[decodeURIComponent(r[0])] = decodeURIComponent(r[1]));
  246. return n
  247. },
  248. validateUser: function(t) {
  249. var e, n, r, i, a, o, u, d, h;
  250. return null == t && (t = {}), n = t.config, null == this.dfd && (this.initDfd(), this.userIsAuthenticated() ? this.resolveDfd() : (o = s.search(), i = this.parseLocation(window.location.search), a = 0 === Object.keys(o).length ? i : o, u = a.auth_token || a.token, void 0 !== u ? (e = a.client_id, d = a.uid, r = a.expiry, n = a.config, this.setConfigName(n), this.mustResetPassword = a.reset_password, this.firstTimeLogin = a.account_confirmation_success, this.oauthRegistration = a.oauth_registration,
  251. this.setAuthHeaders(this.buildAuthHeaders({
  252. token: u,
  253. clientId: e,
  254. uid: d,
  255. expiry: r
  256. })),
  257. h = s.path() || "/", ["token", "client_id", "uid", "expiry", "config", "reset_password", "account_confirmation_success", "oauth_registration"].forEach(function(t) {
  258. return delete a[t]
  259. }),
  260. Object.keys(a).length > 0 && (h += "?" + this.buildQueryString(a)), s.url(h)) : this.retrieveData("currentConfigName") && (n = this.retrieveData("currentConfigName")),
  261. isEmpty(JSON.parse(sessionStorage.getItem('header'))) ? (this.rejectDfd({
  262. reason: "unauthorized",
  263. errors: ["No credentials"]
  264. }), c.$broadcast("auth:invalid")) : this.tokenHasExpired() ? (c.$broadcast("auth:session-expired"),
  265. this.rejectDfd({
  266. reason: "unauthorized",
  267. errors: ["Session expired."]
  268. })) : this.validateToken({
  269. config: n
  270. }))), this.dfd.promise
  271. },
  272. validateToken: function(t) {
  273. return null == t && (t = {}), this.tokenHasExpired() ? this.rejectDfd({
  274. reason: "unauthorized",
  275. errors: ["Expired credentials"]
  276. }) : r.get(this.apiUrl(t.config) + this.getConfig(t.config).tokenValidationPath).success(function(e) {
  277. return function(n) {
  278. var r;
  279. // sessionStorage.setItem('header', JSON.stringify(e.getConfig(t.config).handleTokenValidationResponse(n)));
  280. return r = e.getConfig(t.config).handleTokenValidationResponse(n), e.handleValidAuth(r), e.firstTimeLogin && c.$broadcast("auth:email-confirmation-success", e.user), e.oauthRegistration && c.$broadcast("auth:oauth-registration", e.user), e.mustResetPassword && c.$broadcast("auth:password-reset-confirm-success", e.user), c.$broadcast("auth:validation-success", e.user)
  281. }
  282. }(this)).error(function(t) {
  283. return function(e) {
  284. return t.firstTimeLogin && c.$broadcast("auth:email-confirmation-error", e), t.mustResetPassword && c.$broadcast("auth:password-reset-confirm-error", e), c.$broadcast("auth:validation-error", e), t.rejectDfd({
  285. reason: "unauthorized",
  286. errors: e.errors
  287. })
  288. }
  289. }(this))
  290. },
  291. tokenHasExpired: function() {
  292. var t, e;
  293. return t = this.getExpiry(), e = (new Date).getTime(), t && e > t
  294. },
  295. getExpiry: function() {
  296. return this.getConfig().parseExpiry(this.retrieveData("auth_headers") || {})
  297. },
  298. invalidateTokens: function() {
  299. var t, e, n;
  300. n = this.user;
  301. for (t in n) e = n[t], delete this.user[t];
  302. return this.deleteData("currentConfigName"), null != this.timer && u.cancel(this.timer), this.deleteData("auth_headers")
  303. },
  304. signOut: function() {
  305. return r["post"](this.apiUrl() + this.getConfig().signOutUrl, {}).success(function(t) {
  306. return function(e) {
  307. return t.invalidateTokens(), c.$broadcast("auth:logout-success")
  308. }
  309. }(this)).error(function(t) {
  310. return function(e) {
  311. return t.invalidateTokens(), c.$broadcast("auth:logout-error", e)
  312. }
  313. }(this))
  314. },
  315. handleValidAuth: function(t, e) {
  316. return null == e && (e = !1), null != this.requestCredentialsPollingTimer && u.cancel(this.requestCredentialsPollingTimer), this.cancelOmniauthInAppBrowserListeners(), angular.extend(this.user, t), this.user.signedIn = !0, this.user.configName = this.getCurrentConfigName(), e && this.setAuthHeaders(this.buildAuthHeaders({
  317. token: this.user.auth_token,
  318. clientId: this.user.client_id,
  319. uid: this.user.uid,
  320. expiry: this.user.expiry
  321. })), this.resolveDfd()
  322. },
  323. buildAuthHeaders: function(t) {
  324. var e, n, r, i;
  325. e = {}, i = this.getConfig().tokenFormat;
  326. for (n in i) r = i[n], e[n] = d(r)(t);
  327. return e
  328. },
  329. persistData: function(t, e, n) {
  330. if (this.getConfig(n).storage instanceof Object) return this.getConfig(n).storage.persistData(t, e, this.getConfig(n));
  331. switch (this.getConfig(n).storage) {
  332. case "localStorage":
  333. return o.localStorage.setItem(t, JSON.stringify(e));
  334. default:
  335. return a(t, e, {
  336. path: "/",
  337. expires: 9999,
  338. expirationUnit: "days"
  339. })
  340. }
  341. },
  342. retrieveData: function(t) {
  343. if (this.getConfig().storage instanceof Object) return this.getConfig().storage.retrieveData(t);
  344. switch (this.getConfig().storage) {
  345. case "localStorage":
  346. return JSON.parse(o.localStorage.getItem(t));
  347. default:
  348. return a(t)
  349. }
  350. },
  351. deleteData: function(t) {
  352. switch (this.getConfig().storage instanceof Object && this.getConfig().storage.deleteData(t), this.getConfig().storage) {
  353. case "localStorage":
  354. return o.localStorage.removeItem(t);
  355. default:
  356. return a.remove(t, {
  357. path: "/"
  358. })
  359. }
  360. },
  361. setAuthHeaders: function(t) {
  362. var e, n, r, i;
  363. return n = angular.extend(this.retrieveData("auth_headers") || {}, t), i = this.persistData("auth_headers", n), e = this.getExpiry(), r = (new Date).getTime(), e > r && (null != this.timer && u.cancel(this.timer), this.timer = u(function(t) {
  364. return function() {
  365. return t.validateUser({
  366. config: t.getSavedConfig()
  367. })
  368. }
  369. }(this), parseInt(e - r))), i
  370. },
  371. initDfd: function() {
  372. return this.dfd = i.defer()
  373. },
  374. rejectDfd: function(t) {
  375. // return this.invalidateTokens(), null != this.dfd ? (this.dfd.reject(t), u(function(t) {
  376. // return function() {
  377. // return t.dfd = null
  378. // }
  379. // }(this), 0)) : void 0
  380. return this.invalidateTokens()
  381. },
  382. apiUrl: function(t) {
  383. return this.getConfig(t).proxyIf() ? this.getConfig(t).proxyUrl : this.getConfig(t).apiUrl
  384. },
  385. getConfig: function(e) {
  386. return t[this.getCurrentConfigName(e)]
  387. },
  388. getResultOrValue: function(t) {
  389. return "function" == typeof t ? t() : t
  390. },
  391. getCurrentConfigName: function(t) {
  392. return t || this.getSavedConfig()
  393. },
  394. getSavedConfig: function() {
  395. var t, n, r, i;
  396. t = void 0, i = "currentConfigName", r = !1;
  397. try {
  398. r = !!o.localStorage
  399. } catch (s) {
  400. n = s
  401. }
  402. return r && null == t && (t = JSON.parse(o.localStorage.getItem(i))), null == t && (t = a(i)), t || e
  403. }
  404. }
  405. }
  406. }(this)]
  407. }
  408. }).config(["$httpProvider", function(t) {
  409. var e, n, r;
  410. return n = function(t, e) {
  411. var n, r;
  412. return r = Number(t.getExpiry()), n = Number(t.getConfig().parseExpiry(e || {})), n >= r
  413. }, r = function(t, e) {
  414. var r, i, s, a;
  415. i = {}, a = t.getConfig().tokenFormat;
  416. for (r in a) {
  417. s = a[r];
  418. // i[r]=e.headers(r)}
  419. // i[r]=a[r]
  420. // }
  421. if (e.headers(r)) { i[r] = e.headers(r) }
  422. }
  423. // e.headers(r) && (i[r] = e.headers(r));
  424. return n(t, i) ? t.setAuthHeaders(i) : void 0
  425. }, t.interceptors.push(["$injector", function(t) {
  426. return {
  427. request: function(e) {
  428. return t.invoke(["$http", "$auth", function(t, n) {
  429. var r, i, s, a;
  430. if (e.url.match(n.apiUrl())) {
  431. s = n.retrieveData("auth_headers"), a = [];
  432. for (r in s) i = s[r], a.push(e.headers[r] = i);
  433. return a
  434. }
  435. }]), e
  436. },
  437. response: function(e) {
  438. return t.invoke(["$http", "$auth", function(t, n) {
  439. return e.config.url.match(n.apiUrl()) ? r(n, e) : void 0
  440. }]), e
  441. },
  442. responseError: function(e) {
  443. return t.invoke(["$http", "$auth", function(t, n) {
  444. return e.config.url.match(n.apiUrl()) ? r(n, e) : void 0
  445. }]), t.get("$q").reject(e)
  446. }
  447. }
  448. }]), e = ["get", "post", "put", "patch", "delete"], angular.forEach(e, function(e) {
  449. var n;
  450. return null == (n = t.defaults.headers)[e] && (n[e] = {}), t.defaults.headers[e]["If-Modified-Since"] = "Mon, 26 Jul 1997 05:00:00 GMT"
  451. })
  452. }]).run(["$auth", "$window", "$rootScope", function(t, e, n) {
  453. return t.initialize()
  454. }]), window.isOldIE = function() {
  455. var t, e, n;
  456. return e = !1, t = navigator.userAgent.toLowerCase(), t && -1 !== t.indexOf("msie") && (n = parseInt(t.split("msie")[1]), 10 > n && (e = !0)), e
  457. }, window.isIE = function() {
  458. var t;
  459. return t = navigator.userAgent.toLowerCase(), t && -1 !== t.indexOf("msie") || !!navigator.userAgent.match(/Trident.*rv\:11\./)
  460. }, window.isEmpty = function(t) {
  461. var e, n;
  462. if (!t) return !0;
  463. if (t.length > 0) return !1;
  464. if (0 === t.length) return !0;
  465. for (e in t)
  466. if (n = t[e], Object.prototype.hasOwnProperty.call(t, e)) return !1;
  467. return !0
  468. };