@bixi/auth
Version:
16 lines (14 loc) • 14.8 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@angular/common"),require("@angular/core"),require("@angular/router"),require("rxjs"),require("rxjs/operators"),require("extend"),require("@angular/common/http")):"function"==typeof define&&define.amd?define("@bixi/auth",["exports","@angular/common","@angular/core","@angular/router","rxjs","rxjs/operators","extend","@angular/common/http"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).bixi=e.bixi||{},e.bixi.auth={}),e.ng.common,e.ng.core,e.ng.router,e.rxjs,e.rxjs.operators,e.Extend,e.ng.common.http)}(this,(function(e,t,r,n,o,i,c,a){"use strict";function u(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function s(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var l=s(r),p=u(c),f={store_key:"_token",token_invalid_redirect:!0,token_exp_offset:10,token_send_key:"token",token_send_template:"${token}",token_send_place:"header",login_url:"/login",ignores:[/\/login/,/assets\//,/passport\//],allow_anonymous_key:"_allow_anonymous",executeOtherInterceptors:!0};function h(e){return e.merge(f)}
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */var y=function(e,t){return y=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},y(e,t)};function d(e,t){function r(){this.constructor=e}y(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}Object.create;function g(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function v(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,o,i=r.call(e),c=[];try{for(;(void 0===t||t-- >0)&&!(n=i.next()).done;)c.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return c}function _(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(v(arguments[t]));return e}Object.create;var b=new r.InjectionToken("bixi-auth-config");function m(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];if(Array.isArray(e)||"object"!=typeof e)return e;var o=function(e){return"object"==typeof e||"function"==typeof e},i=function(e,r){return Object.keys(r).filter((function(e){return"__proto__"!==e&&Object.prototype.hasOwnProperty.call(r,e)})).forEach((function(n){var c=r[n],a=e[n];Array.isArray(a)?e[n]=t?c:_(a,c):null!=c&&o(c)&&null!=a&&o(a)?e[n]=i(a,c):e[n]=j(c)})),e};return r.filter((function(e){return null!=e&&o(e)})).forEach((function(t){return i(e,t)})),e}function j(e){return p.default(!0,{},{_:e})._}var I=function(){function e(e){this.config=e||{}}return e.prototype.get=function(e){var t,r=this.config||{};return e?((t={})[e]=r[e],t):r},e.prototype.merge=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return m.apply(void 0,_([{},!0],e,[this.get()]))},e.prototype.attach=function(e,t){Object.assign(e,this.merge(t))},e.prototype.attachKey=function(e,t){Object.assign(e,this.get(t))},e.prototype.set=function(e){this.config=Object.assign(Object.assign({},this.config),e)},e}();I.decorators=[{type:r.Injectable,args:[{providedIn:"root"}]}],I.ctorParameters=function(){return[{type:void 0,decorators:[{type:r.Optional},{type:r.Inject,args:[b]}]}]},I.ɵprov=l.ɵɵdefineInjectable({factory:function(){return new I(l.ɵɵinject(b,8))},token:I,providedIn:"root"});var O=function(){function e(){}return e.prototype.get=function(e){return JSON.parse(localStorage.getItem(e)||"{}")||{}},e.prototype.set=function(e,t){return localStorage.setItem(e,JSON.stringify(t)),!0},e.prototype.remove=function(e){localStorage.removeItem(e)},e}();function k(){return new O}var w=new r.InjectionToken("AUTH_STORE_TOKEN",{providedIn:"root",factory:k});var S=function(){function e(e,t){this.store=t,this.change$=new o.BehaviorSubject(null),this._referrer={},this._options=h(e)}return Object.defineProperty(e.prototype,"login_url",{get:function(){return this._options.login_url},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"referrer",{get:function(){return this._referrer},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),e.prototype.set=function(e){return this.change$.next(e),this.store.set(this._options.store_key,e)},e.prototype.get=function(e){var t=this.store.get(this._options.store_key);return e?Object.assign(new e,t):t},e.prototype.clear=function(e){void 0===e&&(e={onlyToken:!1});var t=null;!0===e.onlyToken?((t=this.get()).token="",this.set(t)):this.store.remove(this._options.store_key),this.change$.next(t)},e.prototype.change=function(){return this.change$.pipe(i.share())},e}();function x(){return new S(r.inject(I),r.inject(w))}S.ctorParameters=function(){return[{type:I},{type:void 0,decorators:[{type:r.Inject,args:[w]}]}]};var T=new r.InjectionToken("BIXI_SERVICE_TOKEN",{providedIn:"root",factory:x});var E="_bixiAuthSocialType",A="_bixiAuthSocialCallbackByHref",C=function(){function e(e,t,r){this.tokenService=e,this.doc=t,this.router=r}return e.prototype.login=function(e,t,r){var n=this;if(void 0===t&&(t="/"),void 0===r&&(r={}),r=Object.assign({type:"window",windowFeatures:"location=yes,height=570,width=520,scrollbars=yes,status=yes"},r),localStorage.setItem(E,r.type),localStorage.setItem(A,t),"href"!==r.type)return this._win=window.open(e,"_blank",r.windowFeatures),this._winTime=setInterval((function(){if(n._win&&n._win.closed){n.ngOnDestroy();var e=n.tokenService.get();e&&!e.token&&(e=null),e&&n.tokenService.set(e),n.observer.next(e),n.observer.complete()}}),100),new o.Observable((function(e){n.observer=e}));this.doc.location.href=e},e.prototype.callback=function(e){if(!e&&-1===this.router.url.indexOf("?"))throw new Error("url muse contain a ?");var t={token:""};if("string"==typeof e){var r=e.split("?")[1].split("#")[0];t=this.router.parseUrl("./?"+r).queryParams}else t=e;if(!t||!t.token)throw new Error("invalide token data");this.tokenService.set(t);var n=localStorage.getItem(A)||"/";localStorage.removeItem(A);var o=localStorage.getItem(E);return localStorage.removeItem(E),"window"===o?window.close():this.router.navigateByUrl(n),t},e.prototype.ngOnDestroy=function(){clearInterval(this._winTime),this._winTime=null},e}();C.decorators=[{type:r.Injectable}],C.ctorParameters=function(){return[{type:void 0,decorators:[{type:r.Inject,args:[T]}]},{type:void 0,decorators:[{type:r.Inject,args:[t.DOCUMENT]}]},{type:n.Router}]};var P=function(){function e(){this.cache={}}return e.prototype.get=function(e){return this.cache[e]||{}},e.prototype.set=function(e,t){return this.cache[e]=t,!0},e.prototype.remove=function(e){this.cache[e]=null},e}();var R=function(){function e(){}return e.prototype.get=function(e){return JSON.parse(sessionStorage.getItem(e)||"{}")||{}},e.prototype.set=function(e,t){return sessionStorage.setItem(e,JSON.stringify(t)),!0},e.prototype.remove=function(e){sessionStorage.removeItem(e)},e}(),N=function(){function e(){}return e.prototype.get=function(e){return JSON.parse(Cookies.get(e)||"{}")||{}},e.prototype.set=function(e,t){return Cookies.set(e,JSON.stringify(t)),!0},e.prototype.remove=function(e){Cookies.remove(e)},e}();function B(e){return null!=e&&"string"==typeof e.token&&e.token.length>0}function J(e,t){return null!=e&&!!e.token&&!e.isExpired(t)}function q(e,r,o){var i=r.get(n.Router);r.get(T).referrer.url=o||i.url,!0===e.token_invalid_redirect&&setTimeout((function(){/^https?:\/\//g.test(e.login_url)?r.get(t.DOCUMENT).location.href=e.login_url:i.navigate([e.login_url])}))}var U=function(){function e(e,t){this.next=e,this.interceptor=t}return e.prototype.handle=function(e){return this.interceptor.intercept(e,this.next)},e}();var D=function(){function e(e){this.injector=e}return e.prototype.intercept=function(e,t){var r,n,i=h(this.injector.get(I));if(i.ignores)try{for(var c=g(i.ignores),u=c.next();!u.done;u=c.next()){if(u.value.test(e.url))return t.handle(e)}}catch(e){r={error:e}}finally{try{u&&!u.done&&(n=c.return)&&n.call(c)}finally{if(r)throw r.error}}if(i.allow_anonymous_key&&(e.params.has(i.allow_anonymous_key)||new RegExp("[?|&]"+i.allow_anonymous_key+"=[^&]+").test(e.urlWithParams)))return t.handle(e);if(!this.isAuth(i)){console.warn("[@bixi/auth](interceptor): Token 不存在或已过期,前往登录页"),q(i,this.injector);var s=new o.Observable((function(t){var r=new a.HttpErrorResponse({url:e.url,headers:e.headers,status:401,statusText:"来自 @bixi/auth 的拦截,所请求URL未授权,若是登录API可加入 [url?_allow_anonymous=true] 来表示忽略校验"});t.error(r)}));if(i.executeOtherInterceptors){var l=this.injector.get(a.HTTP_INTERCEPTORS,[]),p=l.slice(l.indexOf(this)+1);if(p.length>0)return p.reduceRight((function(e,t){return new U(e,t)}),{handle:function(e){return s}}).handle(e)}return s}return e=this.setReq(e,i),t.handle(e)},e}();function M(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("'atob' failed: The string to be decoded is not correctly encoded.")}return function(e){return decodeURIComponent(Array.prototype.map.call(function(e){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="";e=String(e).replace(/=+$/,"");for(var n=0,o=void 0,i=void 0,c=0;i=e.charAt(c++);~i&&(o=n%4?64*o+i:i,n++%4)?r+=String.fromCharCode(255&o>>(-2*n&6)):0)i=t.indexOf(i);return r}(e),(function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""))}(t)}D.decorators=[{type:r.Injectable}],D.ctorParameters=function(){return[{type:r.Injector,decorators:[{type:r.Optional}]}]};var H=function(){function e(){}return Object.defineProperty(e.prototype,"payload",{get:function(){var e=(this.token||"").split(".");if(3!==e.length)throw new Error("JWT must have 3 parts");var t=M(e[1]);return JSON.parse(t)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"exp",{get:function(){var e=this.payload;if(!e.hasOwnProperty("exp"))return null;var t=new Date(0);return t.setUTCSeconds(e.exp),t.valueOf()},enumerable:!1,configurable:!0}),e.prototype.isExpired=function(e){void 0===e&&(e=0);var t=this.exp;return null==t?null:!(t>(new Date).valueOf()+1e3*e)},e}();var F=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return d(t,e),t.prototype.isAuth=function(e){return this.model=this.injector.get(T).get(H),J(this.model,e.token_exp_offset)},t.prototype.setReq=function(e,t){return e.clone({setHeaders:{Authorization:"Bearer "+this.model.token}})},t}(D);F.decorators=[{type:r.Injectable}];var K=function(){function e(e,t){this.srv=e,this.injector=t}return Object.defineProperty(e.prototype,"cog",{get:function(){return this.srv.options},enumerable:!1,configurable:!0}),e.prototype.process=function(){var e=J(this.srv.get(H),this.cog.token_exp_offset);return e||(console.warn("[@bixi/auth](jwt guard): token 不存在或已过期,前往登录页"),q(this.cog,this.injector,this.url)),e},e.prototype.canLoad=function(e,t){return this.url=e.path,this.process()},e.prototype.canActivateChild=function(e,t){return this.url=t.url,this.process()},e.prototype.canActivate=function(e,t){return this.url=t.url,this.process()},e}();K.decorators=[{type:r.Injectable,args:[{providedIn:"root"}]}],K.ctorParameters=function(){return[{type:void 0,decorators:[{type:r.Inject,args:[T]}]},{type:r.Injector}]},K.ɵprov=l.ɵɵdefineInjectable({factory:function(){return new K(l.ɵɵinject(T),l.ɵɵinject(l.INJECTOR))},token:K,providedIn:"root"});var L=function(){};var X=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return d(t,e),t.prototype.isAuth=function(e){return this.model=this.injector.get(T).get(),B(this.model)},t.prototype.setReq=function(e,t){var r=this,n=t.token_send_template,o=t.token_send_key,i=n.replace(/\$\{([\w]+)\}/g,(function(e,t){return r.model[t]}));switch(t.token_send_place){case"header":var c={};c[o]=i,e=e.clone({setHeaders:c});break;case"body":var a=e.body||{};a[o]=i,e=e.clone({body:a});break;case"url":e=e.clone({params:e.params.append(o,i)})}return e},t}(D);X.decorators=[{type:r.Injectable}];var $=function(){function e(e,t){this.srv=e,this.injector=t}return Object.defineProperty(e.prototype,"cog",{get:function(){return this.srv.options},enumerable:!1,configurable:!0}),e.prototype.process=function(){var e=B(this.srv.get());return e||q(this.cog,this.injector,this.url),e},e.prototype.canLoad=function(e,t){return this.url=e.path,this.process()},e.prototype.canActivateChild=function(e,t){return this.url=t.url,this.process()},e.prototype.canActivate=function(e,t){return this.url=t.url,this.process()},e}();$.decorators=[{type:r.Injectable,args:[{providedIn:"root"}]}],$.ctorParameters=function(){return[{type:void 0,decorators:[{type:r.Inject,args:[T]}]},{type:r.Injector}]},$.ɵprov=l.ɵɵdefineInjectable({factory:function(){return new $(l.ɵɵinject(T),l.ɵɵinject(l.INJECTOR))},token:$,providedIn:"root"});var W=function(){};W.decorators=[{type:r.NgModule,args:[{}]}],e.AUTH_DEFAULT_CONFIG=f,e.BIXI_AUTH_CONFIG=b,e.BIXI_SERVICE_TOKEN=T,e.BIXI_SERVICE_TOKEN_FACTORY=x,e.BIXI_STORE_TOKEN=w,e.BIXI_STORE_TOKEN_LOCAL_FACTORY=k,e.BaseInterceptor=D,e.BixiAuthModule=W,e.CookieStorageStore=N,e.JWTGuard=K,e.JWTInterceptor=F,e.JWTTokenModel=H,e.LocalStorageStore=O,e.MemoryStore=P,e.SessionStorageStore=R,e.SimpleGuard=$,e.SimpleInterceptor=X,e.SimpleTokenModel=L,e.SocialService=C,e.TokenService=S,e.mergeConfig=h,e.urlBase64Decode=M,e["ɵa"]=I,Object.defineProperty(e,"__esModule",{value:!0})}));
//# sourceMappingURL=auth.umd.min.js.map