UNPKG

@terminus/ngx-tools

Version:

[![CircleCI][circle-badge]][circle-link] [![codecov][codecov-badge]][codecov-project] [![semantic-release][semantic-release-badge]][semantic-release] [![MIT License][license-image]][license-url] <br> [![NPM version][npm-version-image]][npm-url] [![Github

16 lines (14 loc) 15.4 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@terminus/ngx-tools/utilities"),require("@angular/core"),require("@ngrx/effects"),require("@ngrx/store"),require("@terminus/ngx-tools/browser"),require("rxjs"),require("rxjs/internal/scheduler/async"),require("rxjs/operators"),require("@angular/common/http"),require("@terminus/ngx-tools/type-guards")):"function"==typeof define&&define.amd?define("@terminus/ngx-tools/jwt",["exports","@terminus/ngx-tools/utilities","@angular/core","@ngrx/effects","@ngrx/store","@terminus/ngx-tools/browser","rxjs","rxjs/internal/scheduler/async","rxjs/operators","@angular/common/http","@terminus/ngx-tools/type-guards"],t):t(((e=e||self).terminus=e.terminus||{},e.terminus["ngx-tools"]=e.terminus["ngx-tools"]||{},e.terminus["ngx-tools"].jwt={}),e.terminus["ngx-tools"].utilities,e.ng.core,e.ngrx.effects,e.ngrx.store,e.terminus["ngx-tools"].browser,e.rxjs,e.rxjs["internal/scheduler/async"],e.rxjs.operators,e.ng.common.http,e.terminus["ngx-tools"]["type-guards"])}(this,(function(e,t,n,o,r,i,a,s,c,u,l){"use strict"; /*! ***************************************************************************** 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 p=function(e,t){return(p=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};var f=function(){return(f=Object.assign||function(e){for(var t,n=1,o=arguments.length;n<o;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e}).apply(this,arguments)};function k(e,t,n,o){var r,i=arguments.length,a=i<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,o);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(i<3?r(a):i>3?r(t,n,a):r(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function T(e,t){return function(n,o){t(n,o,e)}}function d(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var o,r,i=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(o=i.next()).done;)a.push(o.value)}catch(e){r={error:e}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}return a}var h=function(e){function t(t){var n=e.call(this,t)||this;return n.message=t,n}return function(e,t){function n(){this.constructor=e}p(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}(t,e),t}(Error);function y(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new h("NGXTools: 'atob' failed: The string to be decoded is not correctly encoded.");for(var n="",o=0,r=void 0,i=void 0,a=0;i=t.charAt(a++);~i&&(r=o%4?64*r+i:i,o++%4)?n+=String.fromCharCode(255&r>>(-2*o&6)):0)i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(i);return n}var m=window.atob||y,g=function(e){return decodeURIComponent(m(e).replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n})))},w=g;function E(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("Illegal base64url string!")}try{return g(t)}catch(e){return m(t)}}var v,x=function(e){this.message=e};function j(e,t){if("string"!=typeof e)throw new x("Invalid token specified");var n=!0===(t=t||{}).header?0:1;try{return JSON.parse(E(e.split(".")[n]))}catch(e){throw e instanceof Error?new x("Invalid token specified: "+e.message):e}}x.prototype.name="InvalidTokenError",(v=e.JwtTokenManagementActionTypes||(e.JwtTokenManagementActionTypes={})).StoreToken="[ngx-tools-jwt-token-provider] Store Token",v.TokenNearingExpiration="[ngx-tools-jwt-token-provider] Token Nearing Expiration",v.TokenExpired="[ngx-tools-jwt-token-provider] Token Expired",v.EscalateToken="[ngx-tools-jwt-token-provider] Escalate Token",v.EscalationSuccess="[ngx-tools-jwt-token-provider] Escalation Success",v.EscalationFailed="[ngx-tools-jwt-token-provider] Escalation Failed",v.AllTokensExpired="[ngx-tools-jwt-token-provider] All Tokens have Expired",v.InitialTokenExtracted="[ngx-tools-jwt-token-provider] Initial Token Extracted",v.FailedToActivateRoute="[ngx-tools-jwt-token-provider] Failed To Activate Route",t.defineTypeEnum(e.JwtTokenManagementActionTypes);var S,N=function(t){this.token=t,this.type=e.JwtTokenManagementActionTypes.InitialTokenExtracted},A=function(){this.type=e.JwtTokenManagementActionTypes.FailedToActivateRoute},M=function(t){var n=t.tokenName,o=t.token,r=t.isDefaultToken;this.type=e.JwtTokenManagementActionTypes.StoreToken,this.tokenName=n,this.token=o,this.isDefaultToken=!!r},I=function(t){var n=t.tokenName,o=t.token;this.type=e.JwtTokenManagementActionTypes.TokenExpired,this.tokenName=n,this.token=o},O=function(){this.type=e.JwtTokenManagementActionTypes.AllTokensExpired},b=function(t){var n=t.tokenName,o=t.token;this.type=e.JwtTokenManagementActionTypes.TokenNearingExpiration,this.tokenName=n,this.token=o},J=function(t){this.tokenName=t,this.type=e.JwtTokenManagementActionTypes.EscalateToken},_=function(t){this.tokenName=t,this.type=e.JwtTokenManagementActionTypes.EscalationSuccess},F=function(t){this.tokenName=t,this.type=e.JwtTokenManagementActionTypes.EscalationFailed},R={jwtTokens:{initialTokenStatus:"empty",tokens:{}}},D=function(){return r.createFeatureSelector("ngx-tools-jwtTokenManagement")},C=function(){return r.createSelector(D(),(function(e){return e?e.jwtTokens.tokens:{}}))},P=function(){return r.createSelector(D(),(function(e){return e?e.jwtTokens.defaultToken:void 0}))},$=function(e){return r.createSelector(C(),(function(t){return t[e]}))},L=function(e){return r.createSelector(P(),$(e),(function(e,t){return t||e}))},q=function(e){return r.createSelector(L(e),(function(e){if(!e)return null;try{return j(e)}catch(e){if("InvalidTokenError"===e.name)return null;throw e}}))},z=new n.InjectionToken("jwt-token-managment INITIAL_JWT_TOKEN_NAME"),W=new n.InjectionToken("scheduler"),H=new n.InjectionToken("wait time"),B=function(){function t(e,t,n,o){this.actions$=e,this.store=t,this.scheduler=n,this.waitTime=o}return t.prototype.retryWithEscalation=function(e){var t=this;return function(n){return n.pipe(c.retryWhen((function(n){var o=0;return n.pipe(c.mergeMap((function(n){return o>0||n instanceof Error||403!==n.status?a.throwError(n):(o+=1,t.store.dispatch(new J(e)),a.merge(t.waitForResult(e),t.expirationTimer()).pipe(c.take(1),c.delay(10,t.scheduler||s.async)))})))})))}},t.prototype.waitForResult=function(t){var n=this;return this.actions$.pipe(o.ofType(e.JwtTokenManagementActionTypes.EscalationFailed,e.JwtTokenManagementActionTypes.EscalationSuccess),c.filter((function(e){return e.tokenName===t})),c.switchMap((function(t){return t.type===e.JwtTokenManagementActionTypes.EscalationSuccess?"complete":n.failureError()})))},t.prototype.expirationTimer=function(){var e=this;return a.timer(this.waitTime||3e4,this.scheduler||s.async).pipe(c.switchMap((function(){return e.failureError()})))},t.prototype.failureError=function(){return a.throwError(new Error("Failed to escalate token"))},t.ctorParameters=function(){return[{type:o.Actions},{type:r.Store},{type:a.Scheduler,decorators:[{type:n.Optional},{type:n.Inject,args:[W]}]},{type:Number,decorators:[{type:n.Optional},{type:n.Inject,args:[H]}]}]},t=k([n.Injectable(),T(2,n.Optional()),T(2,n.Inject(W)),T(3,n.Optional()),T(3,n.Inject(H))],t)}(),K=new n.InjectionToken("wait time"),U=function(){function t(t,n,r,i,u,l){var p=this;this.actions$=t,this.store=n,this.cookieService=r,this.initialTokenName=i,this.scheduler=u,this.timeToWaitBeforeExpiration=l,this.initializationCleanup$=a.of(!0).pipe(c.delay(100,this.scheduler||s.async),c.withLatestFrom(this.store.select(C())),c.map((function(e){var t=d(e,2);t[0];return t[1]})),c.take(1),c.flatMap((function(e){var t=[];for(var n in e)if(e.hasOwnProperty(n)){var o=e[n];o&&t.push(new M({tokenName:n,token:o}))}return t}))),this.allTokensExpired$=this.actions$.pipe(o.ofType(e.JwtTokenManagementActionTypes.TokenExpired),c.delay(10,this.scheduler||s.async),c.withLatestFrom(this.store.select(C())),c.map((function(e){var t=d(e,2);t[0];return t[1]})),c.filter((function(e){return 0===Object.keys(e).length})),c.map((function(e){return new O}))),this.notifyOfTokenExpiration$=this.actions$.pipe(o.ofType(e.JwtTokenManagementActionTypes.StoreToken),c.map((function(e){return[e,j(e.token)]})),c.filter((function(e){return void 0!==e[1].exp})),c.mergeMap((function(e){var t=d(e,2),n=t[0],o=t[1],r=Math.ceil((new Date).getTime()/1e3);if(o.exp>r){var i=o.exp-r,s=p.timeToWaitBeforeExpiration||300,c=0;return c=i<s?1:i-s,a.merge(p.buildDelayedExpirationObservable(1e3*c,n,!1),p.buildDelayedExpirationObservable(1e3*i,n,!0))}return a.of(new I({tokenName:n.tokenName,token:n.token}))}))),this.initialCookieLoader$=function(e){var t=(void 0===e?{}:e).currentState,n=void 0===t?p.store.select(D()):t;return a.of(!0).pipe(c.take(1),c.withLatestFrom(n),c.filter((function(e){var t=d(e,2),n=(t[0],t[1]);return!(!n||"uninitialized"!==n.jwtTokens.initialTokenStatus)})),c.mergeMap((function(e){var t=d(e,2),n=(t[0],t[1],p.cookieService.get("jwt_cookie"));return n.length>0?[new N(n),new M({tokenName:p.initialTokenName,token:n,isDefaultToken:!0})]:[new N(n)]})))}}return t.prototype.buildDelayedExpirationObservable=function(e,t,n){var o={tokenName:t.tokenName,token:t.token};return a.timer(e,this.scheduler||s.async).pipe(c.take(1),c.map((function(){return n?new I(o):new b(o)})))},t.ctorParameters=function(){return[{type:o.Actions},{type:r.Store},{type:i.TsCookieService},{type:String,decorators:[{type:n.Inject,args:[z]}]},{type:a.Scheduler,decorators:[{type:n.Optional},{type:n.Inject,args:[W]}]},{type:Number,decorators:[{type:n.Optional},{type:n.Inject,args:[K]}]}]},k([o.Effect()],t.prototype,"initializationCleanup$",void 0),k([o.Effect()],t.prototype,"allTokensExpired$",void 0),k([o.Effect()],t.prototype,"notifyOfTokenExpiration$",void 0),k([o.Effect()],t.prototype,"initialCookieLoader$",void 0),t=k([n.Injectable(),T(3,n.Inject(z)),T(4,n.Optional()),T(4,n.Inject(W)),T(5,n.Optional()),T(5,n.Inject(K))],t)}(),G=((S={})["ngx-tools-jwtTokenManagement"]=R,S),V=function(){function e(e){this.store=e,this.currentLoadState=this.store.pipe(r.select(D()),c.map((function(e){return e&&e.jwtTokens.initialTokenStatus||"uninitialized"}))),this.currentToken=this.store.pipe(r.select(P()),c.map((function(e){return e||""})))}return e.prototype.canActivate=function(){var e=this;return this.currentLoadState.pipe(c.filter((function(e){return"uninitialized"!==e})),c.withLatestFrom(this.currentToken),c.map((function(e){var t=d(e,2);t[0];return t[1].length>0})),c.tap((function(t){t||e.store.dispatch(new A)})))},e.ctorParameters=function(){return[{type:r.Store}]},e=k([n.Injectable()],e)}(),X={initialTokenStatus:"uninitialized",tokens:{}};function Y(t,n){switch(void 0===t&&(t=X),n.type){case e.JwtTokenManagementActionTypes.InitialTokenExtracted:return"uninitialized"!==t.initialTokenStatus?t:0===n.token.length?{initialTokenStatus:"empty",tokens:{}}:{initialTokenStatus:"loaded",defaultToken:n.token,tokens:{}};case e.JwtTokenManagementActionTypes.StoreToken:var o=f(f({},t),{tokens:f({},t.tokens)});return n.isDefaultToken&&(o.defaultToken=n.token,o.tokens={}),o.tokens[n.tokenName]=n.token,o;case e.JwtTokenManagementActionTypes.TokenExpired:o=f(f({},t),{tokens:f({},t.tokens)});for(var r in t.defaultToken&&t.defaultToken===n.token&&delete o.defaultToken,t.tokens)t.tokens[r]&&t.tokens[r]===n.token&&delete o.tokens[r];return o;default:return t}}var Q=new Error("Token Not found in response"),Z=function(){function e(e){this.store=e}return e.prototype.extractJwtToken=function(e){var t=this,n=e.tokenName,o=e.isDefaultToken;return function(e){return e.pipe(c.tap((function(e){var r=t.extractTokenFromResponse(e);if(""===r)throw Q;t.store.dispatch(new M({tokenName:n,token:r,isDefaultToken:o}))})))}},e.prototype.extractTokenFromResponse=function(e){var t="";if(l.isTokenResponse(e))t=e.token;else if(l.isHttpResponse(e)){var n=e.headers.get("Authorization");n&&n.startsWith("Bearer ")&&(t=n.substr(7))}return t},e.ctorParameters=function(){return[{type:r.Store}]},e=k([n.Injectable()],e)}(),ee=function(){function t(e,t,n,o){this.actions$=e,this.store=t,this.http=n,this.tokenExtractor=o}return t.prototype.escalateToken=function(t){var n=this,r=t.tokenName,i=t.authorizeUrl,s=t.isDefaultToken;return this.actions$.pipe(o.ofType(e.JwtTokenManagementActionTypes.EscalateToken),c.filter((function(e){return e.tokenName===r})),c.withLatestFrom(i,this.store.select(L(r))),c.switchMap((function(e){var t=d(e,3),o=(t[0],t[1]),i=t[2],l=new u.HttpHeaders({Authorization:"Bearer "+i});return n.http.get(o,{headers:l}).pipe(n.tokenExtractor.extractJwtToken({tokenName:r,isDefaultToken:s}),c.map((function(){return new _(r)})),c.catchError((function(){return a.of(new F(r))})))})))},t.ctorParameters=function(){return[{type:o.Actions},{type:r.Store},{type:u.HttpClient},{type:Z}]},t=k([n.Injectable()],t)}(),te={jwtTokens:Y},ne=function(){function e(){}var t;return t=e,e.forRoot=function(e){return{ngModule:t,providers:[{provide:z,useValue:e.initialTokenName}]}},e=t=k([n.NgModule({imports:[u.HttpClientModule,r.StoreModule.forFeature("ngx-tools-jwtTokenManagement",te),o.EffectsModule.forFeature([U])],providers:[B,ee,Z,V]})],e)}();e.ActionTypes=e.JwtTokenManagementActionTypes,e.AllJwtTokensExpired=O,e.AllTokensExpired=O,e.DefaultTokenRequired=V,e.ESCALATION_WAIT_TIME=H,e.EscalateJwtToken=J,e.EscalateToken=J,e.EscalationFailed=F,e.EscalationSuccess=_,e.FailedToActivateRoute=A,e.INITIAL_TOKEN_NAME=z,e.InitialTokenExtracted=N,e.InvalidCharacterError=h,e.InvalidTokenError=x,e.JWT_TOKEN_MANAGEMENT_STATE_TOKEN="ngx-tools-jwtTokenManagement",e.JwtTokenExpired=I,e.JwtTokenManagementModule=ne,e.JwtTokenNearingExpiration=b,e.JwtTokenProviderEffects=U,e.RetryWithEscalation=B,e.SCHEDULER=W,e.SECONDS_BEFORE_EXPIRATION_TO_NOTIFY=K,e.StoreJwtToken=M,e.StoreToken=M,e.TOKEN_NOT_FOUND_ERROR=Q,e.TokenEscalator=ee,e.TokenExpired=I,e.TokenExtractor=Z,e.TokenNearingExpiration=b,e.atobPolyfill=y,e.base64_url_decode=E,e.claimValue=function(e,t){return r.createSelector(q(e),(function(e){return e?e[t]:null}))},e.claimsFor=q,e.getDefaultToken=P,e.getJwtTokenRoot=D,e.getTokens=C,e.initialState=X,e.jwtDecode=j,e.jwtEmptyStateReset=G,e.jwtModuleEmptyState=R,e.jwtTokenProviderReducer=Y,e.reducers=te,e.regenerateOnRetry=function(e){return a.of(!0).pipe(c.switchMap((function(){return e()})))},e.tokenFor=L,e.tokenForWithoutDefault=$,e.ɵ0=w,Object.defineProperty(e,"__esModule",{value:!0})})); //# sourceMappingURL=terminus-ngx-tools-jwt.umd.min.js.map