@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
711 lines (692 loc) • 29.2 kB
JavaScript
import { __extends, __decorate, __param, __read, __assign } from 'tslib';
import { defineTypeEnum } from '@terminus/ngx-tools/utilities';
import { InjectionToken, Optional, Inject, Injectable, NgModule } from '@angular/core';
import { ofType, Actions, Effect, EffectsModule } from '@ngrx/effects';
import { createFeatureSelector, createSelector, Store, select, StoreModule } from '@ngrx/store';
import { TsCookieService } from '@terminus/ngx-tools/browser';
import { throwError, merge, timer, Scheduler, of } from 'rxjs';
import { async } from 'rxjs/internal/scheduler/async';
import { retryWhen, mergeMap, take, delay, filter, switchMap, withLatestFrom, map, flatMap, tap, catchError } from 'rxjs/operators';
import { HttpHeaders, HttpClient, HttpClientModule } from '@angular/common/http';
import { isTokenResponse, isHttpResponse } from '@terminus/ngx-tools/type-guards';
/* eslint-disable @typescript-eslint/no-magic-numbers, no-bitwise, no-mixed-operators */
/**
* The code was extracted from:
* https://github.com/davidchambers/Base64.js
*/
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var InvalidCharacterError = /** @class */ (function (_super) {
__extends(InvalidCharacterError, _super);
function InvalidCharacterError(message) {
var _this = _super.call(this, message) || this;
_this.message = message;
return _this;
}
return InvalidCharacterError;
}(Error));
/**
* Encode value
*
* @param input
* @returns The encoded value
*/
function atobPolyfill(input) {
var str = String(input).replace(/=+$/, '');
if (str.length % 4 === 1) {
throw new InvalidCharacterError("NGXTools: 'atob' failed: The string to be decoded is not correctly encoded.");
}
var output = '';
for (
// initialize result and counters
var bc = 0, bs = void 0, buffer = void 0, idx = 0;
// get next character
buffer = str.charAt(idx++);
// character found in table? initialize bit storage and add its ascii value;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
~buffer && (bs = bc % 4 ? (bs * 64) + buffer : buffer,
// and if not first of each 4 characters,
// convert the first 8 bits to one ascii character
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0) {
// try to find character in table (0-63, not found => -1)
buffer = chars.indexOf(buffer);
}
return output;
}
/* eslint-disable @typescript-eslint/no-magic-numbers */
var localAtob = window.atob || atobPolyfill;
/**
* Decode unicode value
*
* @param str
* @returns The decoded value
*/
var b64DecodeUnicode = function (str) { return decodeURIComponent(localAtob(str).replace(/(.)/g, function (m, p) {
var code = p.charCodeAt(0).toString(16).toUpperCase();
if (code.length < 2) {
code = "0" + code;
}
return "%" + code;
})); };
var ɵ0 = b64DecodeUnicode;
// eslint-disable-next-line camelcase
/**
* Decode url encoded value
*
* @param str
* @returns The decoded value
*/
// eslint-disable-next-line camelcase
function base64_url_decode(str) {
var output = str.replace(/-/g, '+').replace(/_/g, '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw new Error('Illegal base64url string!');
}
try {
return b64DecodeUnicode(output);
}
catch (err) {
return localAtob(output);
}
}
// Rewritten from https://github.com/auth0/jwt-decode/tree/master/lib to be typescript compliant
var InvalidTokenError = /** @class */ (function () {
function InvalidTokenError(message) {
this.message = message;
}
return InvalidTokenError;
}());
// eslint-disable-next-line @typescript-eslint/no-explicit-any
InvalidTokenError.prototype.name = 'InvalidTokenError';
/**
* Decode JWT token
*
* @param token
* @param options
* @returns Token
*/
function jwtDecode(token, options) {
if (typeof token !== 'string') {
throw new InvalidTokenError('Invalid token specified');
}
options = options || {};
var pos = options.header === true ? 0 : 1;
try {
return JSON.parse(base64_url_decode(token.split('.')[pos]));
}
catch (e) {
if (e instanceof Error) {
throw new InvalidTokenError("Invalid token specified: " + e.message);
}
else {
throw e;
}
}
}
var ActionTypes;
(function (ActionTypes) {
ActionTypes["StoreToken"] = "[ngx-tools-jwt-token-provider] Store Token";
ActionTypes["TokenNearingExpiration"] = "[ngx-tools-jwt-token-provider] Token Nearing Expiration";
ActionTypes["TokenExpired"] = "[ngx-tools-jwt-token-provider] Token Expired";
ActionTypes["EscalateToken"] = "[ngx-tools-jwt-token-provider] Escalate Token";
ActionTypes["EscalationSuccess"] = "[ngx-tools-jwt-token-provider] Escalation Success";
ActionTypes["EscalationFailed"] = "[ngx-tools-jwt-token-provider] Escalation Failed";
ActionTypes["AllTokensExpired"] = "[ngx-tools-jwt-token-provider] All Tokens have Expired";
ActionTypes["InitialTokenExtracted"] = "[ngx-tools-jwt-token-provider] Initial Token Extracted";
ActionTypes["FailedToActivateRoute"] = "[ngx-tools-jwt-token-provider] Failed To Activate Route";
})(ActionTypes || (ActionTypes = {}));
defineTypeEnum(ActionTypes);
/**
* InitialTokenExtracted
*/
var InitialTokenExtracted = /** @class */ (function () {
function InitialTokenExtracted(token) {
this.token = token;
this.type = ActionTypes.InitialTokenExtracted;
}
return InitialTokenExtracted;
}());
/**
* FailedToActivateRoute
*/
var FailedToActivateRoute = /** @class */ (function () {
function FailedToActivateRoute() {
this.type = ActionTypes.FailedToActivateRoute;
}
return FailedToActivateRoute;
}());
/**
* StoreToken
*/
var StoreToken = /** @class */ (function () {
function StoreToken(_a) {
var tokenName = _a.tokenName, token = _a.token, isDefaultToken = _a.isDefaultToken;
this.type = ActionTypes.StoreToken;
this.tokenName = tokenName;
this.token = token;
this.isDefaultToken = !!isDefaultToken;
}
return StoreToken;
}());
/**
* TokenExpired
*/
var TokenExpired = /** @class */ (function () {
function TokenExpired(_a) {
var tokenName = _a.tokenName, token = _a.token;
this.type = ActionTypes.TokenExpired;
this.tokenName = tokenName;
this.token = token;
}
return TokenExpired;
}());
/**
* AllTokensExpired
*/
var AllTokensExpired = /** @class */ (function () {
function AllTokensExpired() {
this.type = ActionTypes.AllTokensExpired;
}
return AllTokensExpired;
}());
/**
* TokenNearingExpiration
*/
var TokenNearingExpiration = /** @class */ (function () {
function TokenNearingExpiration(_a) {
var tokenName = _a.tokenName, token = _a.token;
this.type = ActionTypes.TokenNearingExpiration;
this.tokenName = tokenName;
this.token = token;
}
return TokenNearingExpiration;
}());
/**
* EscalateToken
*/
var EscalateToken = /** @class */ (function () {
function EscalateToken(tokenName) {
this.tokenName = tokenName;
this.type = ActionTypes.EscalateToken;
}
return EscalateToken;
}());
/**
* EscalationSuccess
*/
var EscalationSuccess = /** @class */ (function () {
function EscalationSuccess(tokenName) {
this.tokenName = tokenName;
this.type = ActionTypes.EscalationSuccess;
}
return EscalationSuccess;
}());
/**
* EscalationFailed
*/
var EscalationFailed = /** @class */ (function () {
function EscalationFailed(tokenName) {
this.tokenName = tokenName;
this.type = ActionTypes.EscalationFailed;
}
return EscalationFailed;
}());
var JWT_TOKEN_MANAGEMENT_STATE_TOKEN = 'ngx-tools-jwtTokenManagement';
var jwtModuleEmptyState = {
jwtTokens: {
initialTokenStatus: 'empty',
tokens: {},
},
};
var getJwtTokenRoot = function () { return createFeatureSelector(JWT_TOKEN_MANAGEMENT_STATE_TOKEN); };
/**
* Return all current tokens
*/
var getTokens = function () { return createSelector(getJwtTokenRoot(), function (jwtTokenState) { return (jwtTokenState ? jwtTokenState.jwtTokens.tokens : {}); }); };
var getDefaultToken = function () { return createSelector(getJwtTokenRoot(), function (jwtTokenState) { return (jwtTokenState ? jwtTokenState.jwtTokens.defaultToken : undefined); }); };
var tokenForWithoutDefault = function (serviceName) { return createSelector(getTokens(), function (userState) { return userState[serviceName]; }); };
var tokenFor = function (serviceName) { return createSelector(getDefaultToken(), tokenForWithoutDefault(serviceName), function (defaultToken, serviceToken) { return serviceToken || defaultToken; }); };
var claimsFor = function (serviceName) { return createSelector(tokenFor(serviceName), function (token) {
if (token) {
try {
return jwtDecode(token);
}
catch (e) {
if (e.name === 'InvalidTokenError') {
return null;
}
throw e;
}
}
else {
return null;
}
}); };
var claimValue = function (serviceName, claimName) { return createSelector(claimsFor(serviceName), function (claims) { return (claims ? claims[claimName] : null); }); };
var INITIAL_TOKEN_NAME = new InjectionToken('jwt-token-managment INITIAL_JWT_TOKEN_NAME');
// TODO: Scheduler is marked as deprecated to stop others from using although it is not technically deprecated from what I can tell. The
// 'correct' path would be to create our own class extending `SchedulerLike`. https://github.com/GetTerminus/ngx-tools/issues/287
// eslint-disable-next-line deprecation/deprecation
var SCHEDULER = new InjectionToken('scheduler');
var ESCALATION_WAIT_TIME = new InjectionToken('wait time');
var FORBIDDEN_ERROR = 403;
var DEFAULT_ESCALATION_WAIT_TIME = 30000;
var RetryWithEscalation = /** @class */ (function () {
function RetryWithEscalation(actions$,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
store,
// TODO: Scheduler is marked as deprecated to stop others from using although it is not technically deprecated
// from what I can tell. The 'correct' path would be to create our own class extending `SchedulerLike`.
// https://github.com/GetTerminus/ngx-tools/issues/287
// eslint-disable-next-line deprecation/deprecation
scheduler, waitTime) {
this.actions$ = actions$;
this.store = store;
this.scheduler = scheduler;
this.waitTime = waitTime;
}
RetryWithEscalation.prototype.retryWithEscalation = function (tokenName) {
var _this = this;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return function (source) { return source.pipe(retryWhen(function (errors) {
var DELAY_MS = 10;
var tries = 0;
return errors.pipe(mergeMap(function (err) {
if (tries > 0 || err instanceof Error || err.status !== FORBIDDEN_ERROR) {
return throwError(err);
}
tries += 1;
_this.store.dispatch(new EscalateToken(tokenName));
return merge(_this.waitForResult(tokenName), _this.expirationTimer()).pipe(take(1), delay(DELAY_MS, _this.scheduler || async));
}));
})); };
};
RetryWithEscalation.prototype.waitForResult = function (tokenName) {
var _this = this;
return this.actions$
.pipe(ofType(ActionTypes.EscalationFailed, ActionTypes.EscalationSuccess), filter(function (a) { return a.tokenName === tokenName; }), switchMap(function (escResult) {
if (escResult.type === ActionTypes.EscalationSuccess) {
return 'complete';
}
return _this.failureError();
}));
};
RetryWithEscalation.prototype.expirationTimer = function () {
var _this = this;
return timer(this.waitTime || DEFAULT_ESCALATION_WAIT_TIME, this.scheduler || async).pipe(switchMap(function () { return _this.failureError(); }));
};
RetryWithEscalation.prototype.failureError = function () {
return throwError(new Error('Failed to escalate token'));
};
RetryWithEscalation.ctorParameters = function () { return [
{ type: Actions },
{ type: Store },
{ type: Scheduler, decorators: [{ type: Optional }, { type: Inject, args: [SCHEDULER,] }] },
{ type: Number, decorators: [{ type: Optional }, { type: Inject, args: [ESCALATION_WAIT_TIME,] }] }
]; };
RetryWithEscalation = __decorate([
Injectable(),
__param(2, Optional()), __param(2, Inject(SCHEDULER)),
__param(3, Optional()), __param(3, Inject(ESCALATION_WAIT_TIME))
], RetryWithEscalation);
return RetryWithEscalation;
}());
var SECONDS_BEFORE_EXPIRATION_TO_NOTIFY = new InjectionToken('wait time');
var SECONDS_IN_MINUTE = 60;
var DEFAULT_MINUTES_BEFORE_EXPIRATION_TO_NOTIFY = 5;
var DEFAULT_SECONDS_BEFORE_EXPIRATION_TO_NOTIFY = DEFAULT_MINUTES_BEFORE_EXPIRATION_TO_NOTIFY * SECONDS_IN_MINUTE;
var CLEANUP_DELAY = 100;
var TOKENS_EXPIRED_DELAY = 10;
var MS_IN_SECONDS = 1000;
var JwtTokenProviderEffects = /** @class */ (function () {
function JwtTokenProviderEffects(actions$,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
store, cookieService, initialTokenName, scheduler, timeToWaitBeforeExpiration) {
var _this = this;
this.actions$ = actions$;
this.store = store;
this.cookieService = cookieService;
this.initialTokenName = initialTokenName;
this.scheduler = scheduler;
this.timeToWaitBeforeExpiration = timeToWaitBeforeExpiration;
this.initializationCleanup$ = of(true)
.pipe(delay(CLEANUP_DELAY, this.scheduler || async), withLatestFrom(this.store.select(getTokens())), map(function (_a) {
var _b = __read(_a, 2), _ = _b[0], tokens = _b[1];
return tokens;
}), take(1), flatMap(function (tokens) {
var actions = [];
for (var tokenName in tokens) {
if (tokens.hasOwnProperty(tokenName)) {
var token = tokens[tokenName];
if (token) {
actions.push(new StoreToken({
tokenName: tokenName,
token: token,
}));
}
}
}
return actions;
}));
this.allTokensExpired$ = this.actions$
.pipe(ofType(ActionTypes.TokenExpired), delay(TOKENS_EXPIRED_DELAY, this.scheduler || async), withLatestFrom(this.store.select(getTokens())), map(function (_a) {
var _b = __read(_a, 2), _ = _b[0], tokens = _b[1];
return tokens;
}), filter(function (tokens) { return Object.keys(tokens).length === 0; }), map(function (tokens) { return new AllTokensExpired(); }));
this.notifyOfTokenExpiration$ = this.actions$
.pipe(ofType(ActionTypes.StoreToken),
// eslint-disable-next-line max-len
map(function (action) { return [action, jwtDecode(action.token)]; }), filter(function (a) { return a[1].exp !== undefined; }), mergeMap(function (_a) {
var _b = __read(_a, 2), action = _b[0], claims = _b[1];
var currentEpoch = Math.ceil((new Date()).getTime() / MS_IN_SECONDS);
if (claims.exp > currentEpoch) {
var expiresIn = claims.exp - currentEpoch;
var expirationBuffer = _this.timeToWaitBeforeExpiration || DEFAULT_SECONDS_BEFORE_EXPIRATION_TO_NOTIFY;
var expirationNearIn = 0;
if (expiresIn < expirationBuffer) {
expirationNearIn = 1;
}
else {
expirationNearIn = expiresIn - expirationBuffer;
}
return merge(_this.buildDelayedExpirationObservable(expirationNearIn * MS_IN_SECONDS, action, false), _this.buildDelayedExpirationObservable(expiresIn * MS_IN_SECONDS, action, true));
}
return of(new TokenExpired({
tokenName: action.tokenName,
token: action.token,
}));
}));
this.initialCookieLoader$ = function (_a) {
var _b = (_a === void 0 ? {} : _a).currentState, currentState = _b === void 0 ? _this.store.select(getJwtTokenRoot()) : _b;
return of(true).pipe(take(1), withLatestFrom(currentState), filter(function (_a) {
var _b = __read(_a, 2), _ = _b[0], state = _b[1];
return !!(state && state.jwtTokens.initialTokenStatus === 'uninitialized');
}), mergeMap(function (_a) {
var _b = __read(_a, 2), a = _b[0], _ = _b[1];
var cookie = _this.cookieService.get('jwt_cookie');
if (cookie.length > 0) {
return [
new InitialTokenExtracted(cookie),
new StoreToken({
tokenName: _this.initialTokenName,
token: cookie,
isDefaultToken: true,
}),
];
}
return [
new InitialTokenExtracted(cookie),
];
}));
};
}
/*
* This next function is being excluded from coverage due the complexities of testing the `delay` function.
* In order to test as much as possible, each piece has been separated into smaller testable functions.
*/
JwtTokenProviderEffects.prototype.buildDelayedExpirationObservable = function (emitTime, action, expired) {
var outputActionArgs = {
tokenName: action.tokenName,
token: action.token,
};
return timer(emitTime, this.scheduler || async).pipe(take(1), map(function () { return (expired
? new TokenExpired(outputActionArgs)
: new TokenNearingExpiration(outputActionArgs)); }));
};
JwtTokenProviderEffects.ctorParameters = function () { return [
{ type: Actions },
{ type: Store },
{ type: TsCookieService },
{ type: String, decorators: [{ type: Inject, args: [INITIAL_TOKEN_NAME,] }] },
{ type: Scheduler, decorators: [{ type: Optional }, { type: Inject, args: [SCHEDULER,] }] },
{ type: Number, decorators: [{ type: Optional }, { type: Inject, args: [SECONDS_BEFORE_EXPIRATION_TO_NOTIFY,] }] }
]; };
__decorate([
Effect()
], JwtTokenProviderEffects.prototype, "initializationCleanup$", void 0);
__decorate([
Effect()
], JwtTokenProviderEffects.prototype, "allTokensExpired$", void 0);
__decorate([
Effect()
], JwtTokenProviderEffects.prototype, "notifyOfTokenExpiration$", void 0);
__decorate([
Effect()
], JwtTokenProviderEffects.prototype, "initialCookieLoader$", void 0);
JwtTokenProviderEffects = __decorate([
Injectable(),
__param(3, Inject(INITIAL_TOKEN_NAME)),
__param(4, Optional()),
__param(4, Inject(SCHEDULER))
// TODO: Scheduler is marked as deprecated to stop others from using although it is not technically deprecated from
// what I can tell. The 'correct' path would be to create our own class extending `SchedulerLike`.
// https://github.com/GetTerminus/ngx-tools/issues/287
// eslint-disable-next-line deprecation/deprecation
,
__param(5, Optional()),
__param(5, Inject(SECONDS_BEFORE_EXPIRATION_TO_NOTIFY))
], JwtTokenProviderEffects);
return JwtTokenProviderEffects;
}());
var _a;
var jwtEmptyStateReset = (_a = {}, _a[JWT_TOKEN_MANAGEMENT_STATE_TOKEN] = jwtModuleEmptyState, _a);
var DefaultTokenRequired = /** @class */ (function () {
function DefaultTokenRequired(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
store) {
this.store = store;
this.currentLoadState = this.store.pipe(select(getJwtTokenRoot()), map(function (s) { return (s && s.jwtTokens.initialTokenStatus) || 'uninitialized'; }));
this.currentToken = this.store.pipe(select(getDefaultToken()), map(function (s) { return s || ''; }));
}
DefaultTokenRequired.prototype.canActivate = function () {
var _this = this;
return this.currentLoadState.pipe(filter(function (s) { return s !== 'uninitialized'; }), withLatestFrom(this.currentToken), map(function (_a) {
var _b = __read(_a, 2), _ = _b[0], token = _b[1];
return token.length > 0;
}), tap(function (result) {
if (!result) {
_this.store.dispatch(new FailedToActivateRoute());
}
}));
};
DefaultTokenRequired.ctorParameters = function () { return [
{ type: Store }
]; };
DefaultTokenRequired = __decorate([
Injectable()
], DefaultTokenRequired);
return DefaultTokenRequired;
}());
var initialState = {
initialTokenStatus: 'uninitialized',
tokens: {},
};
/**
* @param state
* @param action
*/
function jwtTokenProviderReducer(state, action) {
if (state === void 0) { state = initialState; }
switch (action.type) {
case ActionTypes.InitialTokenExtracted: {
if (state.initialTokenStatus !== 'uninitialized') {
return state;
}
if (action.token.length === 0) {
return {
initialTokenStatus: 'empty',
tokens: {},
};
}
return {
initialTokenStatus: 'loaded',
defaultToken: action.token,
tokens: {},
};
}
case ActionTypes.StoreToken: {
var newState = __assign(__assign({}, state), { tokens: __assign({}, state.tokens) });
if (action.isDefaultToken) {
newState.defaultToken = action.token;
newState.tokens = {};
}
newState.tokens[action.tokenName] = action.token;
return newState;
}
case ActionTypes.TokenExpired: {
var newState = __assign(__assign({}, state), { tokens: __assign({}, state.tokens) });
if (state.defaultToken && state.defaultToken === action.token) {
delete newState.defaultToken;
}
for (var k in state.tokens) {
if (state.tokens[k] && state.tokens[k] === action.token) {
delete newState.tokens[k];
}
}
return newState;
}
default: {
return state;
}
}
}
var TOKEN_NOT_FOUND_ERROR = new Error('Token Not found in response');
var TokenExtractor = /** @class */ (function () {
function TokenExtractor(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
store) {
this.store = store;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TokenExtractor.prototype.extractJwtToken = function (_a) {
var _this = this;
var tokenName = _a.tokenName, isDefaultToken = _a.isDefaultToken;
return function (source) { return source.pipe(tap(function (request) {
var token = _this.extractTokenFromResponse(request);
if (token === '') {
throw TOKEN_NOT_FOUND_ERROR;
}
else {
_this.store.dispatch(new StoreToken({
tokenName: tokenName,
token: token,
isDefaultToken: isDefaultToken,
}));
}
})); };
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TokenExtractor.prototype.extractTokenFromResponse = function (input) {
var token = '';
if (isTokenResponse(input)) {
token = input.token;
}
else if (isHttpResponse(input)) {
var authHeader = input.headers.get('Authorization');
var tokenStartsAtChar = 7;
if (authHeader && authHeader.startsWith('Bearer ')) {
token = authHeader.substr(tokenStartsAtChar);
}
}
return token;
};
TokenExtractor.ctorParameters = function () { return [
{ type: Store }
]; };
TokenExtractor = __decorate([
Injectable()
], TokenExtractor);
return TokenExtractor;
}());
var TokenEscalator = /** @class */ (function () {
function TokenEscalator(actions$,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
store, http, tokenExtractor) {
this.actions$ = actions$;
this.store = store;
this.http = http;
this.tokenExtractor = tokenExtractor;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TokenEscalator.prototype.escalateToken = function (_a) {
var _this = this;
var tokenName = _a.tokenName, authorizeUrl = _a.authorizeUrl, isDefaultToken = _a.isDefaultToken;
return this.actions$
.pipe(ofType(ActionTypes.EscalateToken), filter(function (a) { return a.tokenName === tokenName; }), withLatestFrom(authorizeUrl, this.store.select(tokenFor(tokenName))), switchMap(function (_a) {
var _b = __read(_a, 3), action = _b[0], url = _b[1], currentToken = _b[2];
var headers = new HttpHeaders({ Authorization: "Bearer " + currentToken });
return _this.http.get(url, { headers: headers }).pipe(_this.tokenExtractor.extractJwtToken({
tokenName: tokenName,
isDefaultToken: isDefaultToken,
}), map(function () { return new EscalationSuccess(tokenName); }), catchError(function () { return of(new EscalationFailed(tokenName)); }));
}));
};
TokenEscalator.ctorParameters = function () { return [
{ type: Actions },
{ type: Store },
{ type: HttpClient },
{ type: TokenExtractor }
]; };
TokenEscalator = __decorate([
Injectable()
], TokenEscalator);
return TokenEscalator;
}());
// NOTE: Not sure why this second param is required in strict mode
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var reducers = { jwtTokens: jwtTokenProviderReducer };
var JwtTokenManagementModule = /** @class */ (function () {
function JwtTokenManagementModule() {
}
JwtTokenManagementModule_1 = JwtTokenManagementModule;
JwtTokenManagementModule.forRoot = function (options) {
return {
ngModule: JwtTokenManagementModule_1,
providers: [
{
provide: INITIAL_TOKEN_NAME,
useValue: options.initialTokenName,
},
],
};
};
var JwtTokenManagementModule_1;
JwtTokenManagementModule = JwtTokenManagementModule_1 = __decorate([
NgModule({
imports: [
HttpClientModule,
StoreModule.forFeature(JWT_TOKEN_MANAGEMENT_STATE_TOKEN, reducers),
EffectsModule.forFeature([
JwtTokenProviderEffects,
]),
],
providers: [
RetryWithEscalation,
TokenEscalator,
TokenExtractor,
DefaultTokenRequired,
],
})
], JwtTokenManagementModule);
return JwtTokenManagementModule;
}());
/**
* Regenerate on retry
*
* @param obs
* @returns Observable
*/
var regenerateOnRetry = function (obs) { return of(true).pipe(switchMap(function () { return obs(); })); };
/**
* Generated bundle index. Do not edit.
*/
export { ActionTypes, AllTokensExpired as AllJwtTokensExpired, AllTokensExpired, DefaultTokenRequired, ESCALATION_WAIT_TIME, EscalateToken as EscalateJwtToken, EscalateToken, EscalationFailed, EscalationSuccess, FailedToActivateRoute, INITIAL_TOKEN_NAME, InitialTokenExtracted, InvalidCharacterError, InvalidTokenError, JWT_TOKEN_MANAGEMENT_STATE_TOKEN, TokenExpired as JwtTokenExpired, ActionTypes as JwtTokenManagementActionTypes, JwtTokenManagementModule, TokenNearingExpiration as JwtTokenNearingExpiration, JwtTokenProviderEffects, RetryWithEscalation, SCHEDULER, SECONDS_BEFORE_EXPIRATION_TO_NOTIFY, StoreToken as StoreJwtToken, StoreToken, TOKEN_NOT_FOUND_ERROR, TokenEscalator, TokenExpired, TokenExtractor, TokenNearingExpiration, atobPolyfill, base64_url_decode, claimValue, claimsFor, getDefaultToken, getJwtTokenRoot, getTokens, initialState, jwtDecode, jwtEmptyStateReset, jwtModuleEmptyState, jwtTokenProviderReducer, reducers, regenerateOnRetry, tokenFor, tokenForWithoutDefault, ɵ0 };
//# sourceMappingURL=terminus-ngx-tools-jwt.js.map