ng-token-auth.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. }
  121. }(this)).error(function(t) {
  122. return function(e) {
  123. return t.rejectDfd({
  124. reason: "unauthorized",
  125. errors: ["Invalid credentials"]
  126. }), c.$broadcast("auth:login-error", e)
  127. }
  128. }(this)), this.dfd.promise
  129. },
  130. userIsAuthenticated: function() {
  131. return this.retrieveData("auth_headers") && this.user.signedIn && !this.tokenHasExpired()
  132. },
  133. requestPasswordReset: function(t, e) {
  134. var n;
  135. 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) {
  136. return c.$broadcast("auth:password-reset-request-success", t)
  137. }).error(function(t) {
  138. return c.$broadcast("auth:password-reset-request-error", t)
  139. })
  140. },
  141. updatePassword: function(t) {
  142. return r.put(this.apiUrl() + this.getConfig().passwordUpdatePath, t).success(function(t) {
  143. return function(e) {
  144. return c.$broadcast("auth:password-change-success", e), t.mustResetPassword = !1
  145. }
  146. }(this)).error(function(t) {
  147. return c.$broadcast("auth:password-change-error", t)
  148. })
  149. },
  150. updateAccount: function(t) {
  151. return r.put(this.apiUrl() + this.getConfig().accountUpdatePath, t).success(function(t) {
  152. return function(e) {
  153. var n, r, i, s, a, o;
  154. if (s = t.getConfig().handleAccountUpdateResponse(e), n = t.retrieveData("auth_headers"), angular.extend(t.user, s), n) {
  155. i = {}, o = t.getConfig().tokenFormat;
  156. for (r in o) a = o[r], n[r] && s[r] && (i[r] = s[r]);
  157. t.setAuthHeaders(i)
  158. }
  159. return c.$broadcast("auth:account-update-success", e)
  160. }
  161. }(this)).error(function(t) {
  162. return c.$broadcast("auth:account-update-error", t)
  163. })
  164. },
  165. destroyAccount: function(t) {
  166. return r["delete"](this.apiUrl() + this.getConfig().accountUpdatePath, t).success(function(t) {
  167. return function(e) {
  168. return t.invalidateTokens(), c.$broadcast("auth:account-destroy-success", e)
  169. }
  170. }(this)).error(function(t) {
  171. return c.$broadcast("auth:account-destroy-error", t)
  172. })
  173. },
  174. authenticate: function(t, e) {
  175. return null == e && (e = {}), null == this.dfd && (this.setConfigName(e.config), this.initDfd(), this.openAuthWindow(t, e)), this.dfd.promise
  176. },
  177. setConfigName: function(t) {
  178. return null == t && (t = e), this.persistData("currentConfigName", t, t)
  179. },
  180. openAuthWindow: function(t, e) {
  181. var n, r;
  182. if (r = this.getConfig(e.config).omniauthWindowType, n = this.buildAuthUrl(r, t, e), "newWindow" === r) return this.requestCredentialsViaPostMessage(this.createPopup(n));
  183. if ("inAppBrowser" === r) return this.requestCredentialsViaExecuteScript(this.createPopup(n));
  184. if ("sameWindow" === r) return this.visitUrl(n);
  185. throw 'Unsupported omniauthWindowType "#{omniauthWindowType}"'
  186. },
  187. visitUrl: function(t) {
  188. return o.location.replace(t)
  189. },
  190. buildAuthUrl: function(t, e, n) {
  191. var r, i, s, a;
  192. 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 || {}, {
  193. omniauth_window_type: t
  194. });
  195. for (i in s) a = s[i], r += "&", r += encodeURIComponent(i), r += "=", r += encodeURIComponent(a);
  196. return r
  197. },
  198. requestCredentialsViaPostMessage: function(t) {
  199. return t.closed ? this.handleAuthWindowClose(t) : (t.postMessage("requestCredentials", "*"), this.requestCredentialsPollingTimer = u(function(e) {
  200. return function() {
  201. return e.requestCredentialsViaPostMessage(t)
  202. }
  203. }(this), 500))
  204. },
  205. requestCredentialsViaExecuteScript: function(t) {
  206. var e, n;
  207. 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() {
  208. return t.removeEventListener("loadstop", n), t.removeEventListener("exit", e)
  209. }
  210. },
  211. handleLoadStop: function(t) {
  212. return n = this, t.executeScript({
  213. code: "requestCredentials()"
  214. }, function(e) {
  215. var r, i;
  216. return r = e[0], r ? (i = new Event("message"), i.data = r, n.cancelOmniauthInAppBrowserListeners(), o.dispatchEvent(i), n.initDfd(), t.close()) : void 0
  217. })
  218. },
  219. handleAuthWindowClose: function(t) {
  220. return this.cancel({
  221. reason: "unauthorized",
  222. errors: ["User canceled login"]
  223. }), this.cancelOmniauthInAppBrowserListeners, c.$broadcast("auth:window-closed")
  224. },
  225. createPopup: function(t) {
  226. return o.open(t, "_blank")
  227. },
  228. resolveDfd: function() {
  229. return this.dfd.resolve(this.user), u(function(t) {
  230. return function() {
  231. return t.dfd = null, c.$$phase ? void 0 : c.$digest()
  232. }
  233. }(this), 0)
  234. },
  235. buildQueryString: function(t, e) {
  236. var n, r, i, s;
  237. i = [];
  238. 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);
  239. return i.join("&")
  240. },
  241. parseLocation: function(t) {
  242. var e, n, r, i;
  243. i = t.substring(1).split("&"), n = {}, r = void 0, e = void 0;
  244. for (e in i) e = e, "" !== i[e] && (r = i[e].split("="), n[decodeURIComponent(r[0])] = decodeURIComponent(r[1]));
  245. return n
  246. },
  247. validateUser: function(t) {
  248. var e, n, r, i, a, o, u, d, h;
  249. 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,
  250. this.setAuthHeaders(this.buildAuthHeaders({
  251. token: u,
  252. clientId: e,
  253. uid: d,
  254. expiry: r
  255. })),
  256. h = s.path() || "/", ["token", "client_id", "uid", "expiry", "config", "reset_password", "account_confirmation_success", "oauth_registration"].forEach(function(t) {
  257. return delete a[t]
  258. }),
  259. Object.keys(a).length > 0 && (h += "?" + this.buildQueryString(a)), s.url(h)) : this.retrieveData("currentConfigName") && (n = this.retrieveData("currentConfigName")),
  260. isEmpty(this.retrieveData("auth_headers")) ? (this.rejectDfd({
  261. reason: "unauthorized",
  262. errors: ["No credentials"]
  263. }), c.$broadcast("auth:invalid")) : this.tokenHasExpired() ? (c.$broadcast("auth:session-expired"),
  264. this.rejectDfd({
  265. reason: "unauthorized",
  266. errors: ["Session expired."]
  267. })) : this.validateToken({
  268. config: n
  269. }))), this.dfd.promise
  270. },
  271. validateToken: function(t) {
  272. return null == t && (t = {}), this.tokenHasExpired() ? this.rejectDfd({
  273. reason: "unauthorized",
  274. errors: ["Expired credentials"]
  275. }) : r.get(this.apiUrl(t.config) + this.getConfig(t.config).tokenValidationPath).success(function(e) {
  276. return function(n) {
  277. var r;
  278. 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)
  279. }
  280. }(this)).error(function(t) {
  281. return function(e) {
  282. 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({
  283. reason: "unauthorized",
  284. errors: e.errors
  285. })
  286. }
  287. }(this))
  288. },
  289. tokenHasExpired: function() {
  290. var t, e;
  291. return t = this.getExpiry(), e = (new Date).getTime(), t && e > t
  292. },
  293. getExpiry: function() {
  294. return this.getConfig().parseExpiry(this.retrieveData("auth_headers") || {})
  295. },
  296. invalidateTokens: function() {
  297. var t, e, n;
  298. n = this.user;
  299. for (t in n) e = n[t], delete this.user[t];
  300. return this.deleteData("currentConfigName"), null != this.timer && u.cancel(this.timer), this.deleteData("auth_headers")
  301. },
  302. signOut: function() {
  303. return r["delete"](this.apiUrl() + this.getConfig().signOutUrl).success(function(t) {
  304. return function(e) {
  305. return t.invalidateTokens(), c.$broadcast("auth:logout-success")
  306. }
  307. }(this)).error(function(t) {
  308. return function(e) {
  309. return t.invalidateTokens(), c.$broadcast("auth:logout-error", e)
  310. }
  311. }(this))
  312. },
  313. handleValidAuth: function(t, e) {
  314. 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({
  315. token: this.user.auth_token,
  316. clientId: this.user.client_id,
  317. uid: this.user.uid,
  318. expiry: this.user.expiry
  319. })), this.resolveDfd()
  320. },
  321. buildAuthHeaders: function(t) {
  322. var e, n, r, i;
  323. e = {}, i = this.getConfig().tokenFormat;
  324. for (n in i) r = i[n], e[n] = d(r)(t);
  325. return e
  326. },
  327. persistData: function(t, e, n) {
  328. if (this.getConfig(n).storage instanceof Object) return this.getConfig(n).storage.persistData(t, e, this.getConfig(n));
  329. switch (this.getConfig(n).storage) {
  330. case "localStorage":
  331. return o.localStorage.setItem(t, JSON.stringify(e));
  332. default:
  333. return a(t, e, {
  334. path: "/",
  335. expires: 9999,
  336. expirationUnit: "days"
  337. })
  338. }
  339. },
  340. retrieveData: function(t) {
  341. if (this.getConfig().storage instanceof Object) return this.getConfig().storage.retrieveData(t);
  342. switch (this.getConfig().storage) {
  343. case "localStorage":
  344. return JSON.parse(o.localStorage.getItem(t));
  345. default:
  346. return a(t)
  347. }
  348. },
  349. deleteData: function(t) {
  350. switch (this.getConfig().storage instanceof Object && this.getConfig().storage.deleteData(t), this.getConfig().storage) {
  351. case "localStorage":
  352. return o.localStorage.removeItem(t);
  353. default:
  354. return a.remove(t, {
  355. path: "/"
  356. })
  357. }
  358. },
  359. setAuthHeaders: function(t) {
  360. var e, n, r, i;
  361. 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) {
  362. return function() {
  363. return t.validateUser({
  364. config: t.getSavedConfig()
  365. })
  366. }
  367. }(this), parseInt(e - r))), i
  368. },
  369. initDfd: function() {
  370. return this.dfd = i.defer()
  371. },
  372. rejectDfd: function(t) {
  373. return this.invalidateTokens(), null != this.dfd ? (this.dfd.reject(t), u(function(t) {
  374. return function() {
  375. return t.dfd = null
  376. }
  377. }(this), 0)) : void 0
  378. },
  379. apiUrl: function(t) {
  380. return this.getConfig(t).proxyIf() ? this.getConfig(t).proxyUrl : this.getConfig(t).apiUrl
  381. },
  382. getConfig: function(e) {
  383. return t[this.getCurrentConfigName(e)]
  384. },
  385. getResultOrValue: function(t) {
  386. return "function" == typeof t ? t() : t
  387. },
  388. getCurrentConfigName: function(t) {
  389. return t || this.getSavedConfig()
  390. },
  391. getSavedConfig: function() {
  392. var t, n, r, i;
  393. t = void 0, i = "currentConfigName", r = !1;
  394. try {
  395. r = !! o.localStorage
  396. } catch (s) {
  397. n = s
  398. }
  399. return r && null == t && (t = JSON.parse(o.localStorage.getItem(i))), null == t && (t = a(i)), t || e
  400. }
  401. }
  402. }
  403. }(this)]
  404. }
  405. }).config(["$httpProvider", function(t) {
  406. var e, n, r;
  407. return n = function(t, e) {
  408. var n, r;
  409. return r = Number(t.getExpiry()), n = Number(t.getConfig().parseExpiry(e || {})), n >= r
  410. }, r = function(t, e) {
  411. var r, i, s, a;
  412. i = {}, a = t.getConfig().tokenFormat;
  413. for (r in a) {s = a[r];
  414. // i[r]=e.headers(r)}
  415. // i[r]=a[r]
  416. // }
  417. if(e.headers(r)){i[r]=e.headers(r)}}
  418. // e.headers(r) && (i[r] = e.headers(r));
  419. return n(t, i) ? t.setAuthHeaders(i) : void 0
  420. }, t.interceptors.push(["$injector", function(t) {
  421. return {
  422. request: function(e) {
  423. return t.invoke(["$http", "$auth", function(t, n) {
  424. var r, i, s, a;
  425. if (e.url.match(n.apiUrl())) {
  426. s = n.retrieveData("auth_headers"), a = [];
  427. for (r in s) i = s[r], a.push(e.headers[r] = i);
  428. return a
  429. }
  430. }]), e
  431. },
  432. response: function(e) {
  433. return t.invoke(["$http", "$auth", function(t, n) {
  434. return e.config.url.match(n.apiUrl()) ? r(n, e) : void 0
  435. }]), e
  436. },
  437. responseError: 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. }]), t.get("$q").reject(e)
  441. }
  442. }
  443. }]), e = ["get", "post", "put", "patch", "delete"], angular.forEach(e, function(e) {
  444. var n;
  445. return null == (n = t.defaults.headers)[e] && (n[e] = {}), t.defaults.headers[e]["If-Modified-Since"] = "Mon, 26 Jul 1997 05:00:00 GMT"
  446. })
  447. }]).run(["$auth", "$window", "$rootScope", function(t, e, n) {
  448. return t.initialize()
  449. }]), window.isOldIE = function() {
  450. var t, e, n;
  451. return e = !1, t = navigator.userAgent.toLowerCase(), t && -1 !== t.indexOf("msie") && (n = parseInt(t.split("msie")[1]), 10 > n && (e = !0)), e
  452. }, window.isIE = function() {
  453. var t;
  454. return t = navigator.userAgent.toLowerCase(), t && -1 !== t.indexOf("msie") || !! navigator.userAgent.match(/Trident.*rv\:11\./)
  455. }, window.isEmpty = function(t) {
  456. var e, n;
  457. if (!t) return !0;
  458. if (t.length > 0) return !1;
  459. if (0 === t.length) return !0;
  460. for (e in t) if (n = t[e], Object.prototype.hasOwnProperty.call(t, e)) return !1;
  461. return !0
  462. };