@nebular/auth
Version:
@nebular/auth
1 lines • 190 kB
Source Map (JSON)
{"version":3,"file":"nebular-auth.mjs","sources":["../../../src/framework/auth/auth.options.ts","../../../src/framework/auth/helpers.ts","../../../src/framework/auth/services/token/token.ts","../../../src/framework/auth/services/token/token-parceler.ts","../../../src/framework/auth/services/token/token-storage.ts","../../../src/framework/auth/services/token/token.service.ts","../../../src/framework/auth/services/auth.service.ts","../../../src/framework/auth/strategies/auth-strategy.ts","../../../src/framework/auth/services/auth-result.ts","../../../src/framework/auth/strategies/auth-strategy-options.ts","../../../src/framework/auth/strategies/dummy/dummy-strategy-options.ts","../../../src/framework/auth/strategies/dummy/dummy-strategy.ts","../../../src/framework/auth/strategies/oauth2/oauth2-strategy.options.ts","../../../src/framework/auth/strategies/oauth2/oauth2-strategy.ts","../../../src/framework/auth/strategies/password/password-strategy-options.ts","../../../src/framework/auth/strategies/password/password-strategy.ts","../../../src/framework/auth/components/auth-block/auth-block.component.ts","../../../src/framework/auth/components/auth.component.ts","../../../src/framework/auth/components/login/login.component.ts","../../../src/framework/auth/components/login/login.component.html","../../../src/framework/auth/components/register/register.component.ts","../../../src/framework/auth/components/register/register.component.html","../../../src/framework/auth/components/logout/logout.component.ts","../../../src/framework/auth/components/logout/logout.component.html","../../../src/framework/auth/components/request-password/request-password.component.ts","../../../src/framework/auth/components/request-password/request-password.component.html","../../../src/framework/auth/components/reset-password/reset-password.component.ts","../../../src/framework/auth/components/reset-password/reset-password.component.html","../../../src/framework/auth/auth.module.ts","../../../src/framework/auth/auth.routes.ts","../../../src/framework/auth/services/interceptors/jwt-interceptor.ts","../../../src/framework/auth/services/interceptors/simple-interceptor.ts","../../../src/framework/auth/models/user.ts","../../../src/framework/auth/public_api.ts","../../../src/framework/auth/nebular-auth.ts"],"sourcesContent":["import { InjectionToken } from '@angular/core';\nimport { HttpRequest } from '@angular/common/http';\nimport { NbAuthStrategy } from './strategies/auth-strategy';\nimport { NbAuthStrategyOptions } from './strategies/auth-strategy-options';\nimport { NbAuthToken, NbAuthTokenClass } from './services/token/token';\n\nexport type NbAuthStrategyClass = new (...params: any[]) => NbAuthStrategy;\n\nexport type NbAuthStrategies = [NbAuthStrategyClass, NbAuthStrategyOptions][];\n\nexport interface NbAuthOptions {\n forms?: any;\n strategies?: NbAuthStrategies;\n}\n\nexport interface NbAuthSocialLink {\n link?: string,\n url?: string,\n target?: string,\n title?: string,\n icon?: string,\n}\n\nconst socialLinks: NbAuthSocialLink[] = [];\n\nexport const defaultAuthOptions: any = {\n strategies: [],\n forms: {\n login: {\n redirectDelay: 500, // delay before redirect after a successful login, while success message is shown to the user\n strategy: 'email', // provider id key. If you have multiple strategies, or what to use your own\n rememberMe: true, // whether to show or not the `rememberMe` checkbox\n showMessages: { // show/not show success/error messages\n success: true,\n error: true,\n },\n socialLinks: socialLinks, // social links at the bottom of a page\n },\n register: {\n redirectDelay: 500,\n strategy: 'email',\n showMessages: {\n success: true,\n error: true,\n },\n terms: true,\n socialLinks: socialLinks,\n },\n requestPassword: {\n redirectDelay: 500,\n strategy: 'email',\n showMessages: {\n success: true,\n error: true,\n },\n socialLinks: socialLinks,\n },\n resetPassword: {\n redirectDelay: 500,\n strategy: 'email',\n showMessages: {\n success: true,\n error: true,\n },\n socialLinks: socialLinks,\n },\n logout: {\n redirectDelay: 500,\n strategy: 'email',\n },\n validation: {\n password: {\n required: true,\n minLength: 4,\n maxLength: 50,\n },\n email: {\n required: true,\n },\n fullName: {\n required: false,\n minLength: 4,\n maxLength: 50,\n },\n },\n },\n};\n\nexport const NB_AUTH_OPTIONS = new InjectionToken<NbAuthOptions>('Nebular Auth Options');\nexport const NB_AUTH_USER_OPTIONS = new InjectionToken<NbAuthOptions>('Nebular User Auth Options');\nexport const NB_AUTH_STRATEGIES = new InjectionToken<NbAuthStrategies>('Nebular Auth Strategies');\nexport const NB_AUTH_TOKENS = new InjectionToken<NbAuthTokenClass<NbAuthToken>[]>('Nebular Auth Tokens');\nexport const NB_AUTH_INTERCEPTOR_HEADER = new InjectionToken<string>('Nebular Simple Interceptor Header');\nexport const NB_AUTH_TOKEN_INTERCEPTOR_FILTER =\n new InjectionToken<(req: HttpRequest<any>) => boolean>('Nebular Interceptor Filter');\n\n","/**\n * Extending object that entered in first argument.\n *\n * Returns extended object or false if have no target object or incorrect type.\n *\n * If you wish to clone source object (without modify it), just use empty new\n * object as first argument, like this:\n * deepExtend({}, yourObj_1, [yourObj_N]);\n */\nexport const deepExtend = function (...objects: any[]): any {\n if (arguments.length < 1 || typeof arguments[0] !== 'object') {\n return false;\n }\n\n if (arguments.length < 2) {\n return arguments[0];\n }\n\n const target = arguments[0];\n\n // convert arguments to array and cut off target object\n const args = Array.prototype.slice.call(arguments, 1);\n\n let val, src;\n\n args.forEach(function (obj: any) {\n // skip argument if it is array or isn't object\n if (typeof obj !== 'object' || Array.isArray(obj)) {\n return;\n }\n\n Object.keys(obj).forEach(function (key) {\n src = target[key]; // source value\n val = obj[key]; // new value\n\n // recursion prevention\n if (val === target) {\n return;\n\n /**\n * if new value isn't object then just overwrite by new value\n * instead of extending.\n */\n } else if (typeof val !== 'object' || val === null) {\n target[key] = val;\n\n return;\n\n // just clone arrays (and recursive clone objects inside)\n } else if (Array.isArray(val)) {\n target[key] = deepCloneArray(val);\n\n return;\n\n // custom cloning and overwrite for specific objects\n } else if (isSpecificValue(val)) {\n target[key] = cloneSpecificValue(val);\n\n return;\n\n // overwrite by new value if source isn't object or array\n } else if (typeof src !== 'object' || src === null || Array.isArray(src)) {\n target[key] = deepExtend({}, val);\n\n return;\n\n // source value and new value is objects both, extending...\n } else {\n target[key] = deepExtend(src, val);\n\n return;\n }\n });\n });\n\n return target;\n};\n\nfunction isSpecificValue(val: any) {\n return (\n val instanceof Date\n || val instanceof RegExp\n ) ? true : false;\n}\n\nfunction cloneSpecificValue(val: any): any {\n if (val instanceof Date) {\n return new Date(val.getTime());\n } else if (val instanceof RegExp) {\n return new RegExp(val);\n } else {\n throw new Error('cloneSpecificValue: Unexpected situation');\n }\n}\n\n/**\n * Recursive cloning array.\n */\nfunction deepCloneArray(arr: any[]): any {\n const clone: any[] = [];\n arr.forEach(function (item: any, index: any) {\n if (typeof item === 'object' && item !== null) {\n if (Array.isArray(item)) {\n clone[index] = deepCloneArray(item);\n } else if (isSpecificValue(item)) {\n clone[index] = cloneSpecificValue(item);\n } else {\n clone[index] = deepExtend({}, item);\n }\n } else {\n clone[index] = item;\n }\n });\n\n return clone;\n}\n\n// getDeepFromObject({result: {data: 1}}, 'result.data', 2); // returns 1\nexport function getDeepFromObject(object = {}, name: string, defaultValue?: any) {\n const keys = name.split('.');\n // clone the object\n let level = deepExtend({}, object || {});\n keys.forEach((k) => {\n if (level && typeof level[k] !== 'undefined') {\n level = level[k];\n } else {\n level = undefined;\n }\n });\n\n return typeof level === 'undefined' ? defaultValue : level;\n}\n\nexport function urlBase64Decode(str: string): string {\n let output = str.replace(/-/g, '+').replace(/_/g, '/');\n switch (output.length % 4) {\n case 0: { break; }\n case 2: { output += '=='; break; }\n case 3: { output += '='; break; }\n default: {\n throw new Error('Illegal base64url string!');\n }\n }\n return b64DecodeUnicode(output);\n}\n\nexport function b64decode(str: string): string {\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n let output: string = '';\n\n str = String(str).replace(/=+$/, '');\n\n if (str.length % 4 === 1) {\n throw new Error(`'atob' failed: The string to be decoded is not correctly encoded.`);\n }\n\n for (\n // initialize result and counters\n let bc: number = 0, bs: any, buffer: any, idx: number = 0;\n // get next character\n buffer = str.charAt(idx++);\n // character found in table? initialize bit storage and add its ascii value;\n ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,\n // and if not first of each 4 characters,\n // convert the first 8 bits to one ascii character\n bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0\n ) {\n // try to find character in table (0-63, not found => -1)\n buffer = chars.indexOf(buffer);\n }\n return output;\n}\n\n// https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem\nexport function b64DecodeUnicode(str: any) {\n return decodeURIComponent(Array.prototype.map.call(b64decode(str), (c: any) => {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n }).join(''));\n}\n","import { urlBase64Decode } from '../../helpers';\n\nexport abstract class NbAuthToken {\n\n protected payload: any = null;\n\n abstract getValue(): string;\n abstract isValid(): boolean;\n // the strategy name used to acquire this token (needed for refreshing token)\n abstract getOwnerStrategyName(): string;\n abstract getCreatedAt(): Date;\n abstract toString(): string;\n\n getName(): string {\n return (this.constructor as NbAuthTokenClass).NAME;\n }\n\n getPayload(): any {\n return this.payload;\n }\n}\n\nexport class NbAuthTokenNotFoundError extends Error {\n constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class NbAuthIllegalTokenError extends Error {\n constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class NbAuthEmptyTokenError extends NbAuthIllegalTokenError {\n constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class NbAuthIllegalJWTTokenError extends NbAuthIllegalTokenError {\n constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport interface NbAuthRefreshableToken {\n getRefreshToken(): string;\n setRefreshToken(refreshToken: string);\n}\n\nexport interface NbAuthTokenClass<T = NbAuthToken> {\n NAME: string;\n new (raw: any, strategyName: string, expDate?: Date): T;\n}\n\nexport function nbAuthCreateToken<T extends NbAuthToken>(tokenClass: NbAuthTokenClass<T>,\n token: any,\n ownerStrategyName: string,\n createdAt?: Date) {\n return new tokenClass(token, ownerStrategyName, createdAt);\n}\n\nexport function decodeJwtPayload(payload: string): any {\n\n if (payload.length === 0) {\n throw new NbAuthEmptyTokenError('Cannot extract from an empty payload.');\n }\n\n const parts = payload.split('.');\n\n if (parts.length !== 3) {\n throw new NbAuthIllegalJWTTokenError(\n `The payload ${payload} is not valid JWT payload and must consist of three parts.`);\n }\n\n let decoded;\n try {\n decoded = urlBase64Decode(parts[1]);\n } catch (e) {\n throw new NbAuthIllegalJWTTokenError(\n `The payload ${payload} is not valid JWT payload and cannot be parsed.`);\n }\n\n if (!decoded) {\n throw new NbAuthIllegalJWTTokenError(\n `The payload ${payload} is not valid JWT payload and cannot be decoded.`);\n }\n return JSON.parse(decoded);\n}\n\n/**\n * Wrapper for simple (text) token\n */\nexport class NbAuthSimpleToken extends NbAuthToken {\n\n static NAME = 'nb:auth:simple:token';\n\n constructor(protected readonly token: any,\n protected readonly ownerStrategyName: string,\n protected createdAt?: Date) {\n super();\n try {\n this.parsePayload();\n } catch (err) {\n if (!(err instanceof NbAuthTokenNotFoundError)) {\n // token is present but has got a problem, including illegal\n throw err;\n }\n }\n this.createdAt = this.prepareCreatedAt(createdAt);\n }\n\n protected parsePayload(): any {\n this.payload = null;\n }\n\n protected prepareCreatedAt(date: Date) {\n return date ? date : new Date();\n }\n\n /**\n * Returns the token's creation date\n * @returns {Date}\n */\n getCreatedAt(): Date {\n return this.createdAt;\n }\n\n /**\n * Returns the token value\n * @returns string\n */\n getValue(): string {\n return this.token;\n }\n\n getOwnerStrategyName(): string {\n return this.ownerStrategyName;\n }\n\n /**\n * Is non empty and valid\n * @returns {boolean}\n */\n isValid(): boolean {\n return !!this.getValue();\n }\n\n /**\n * Validate value and convert to string, if value is not valid return empty string\n * @returns {string}\n */\n toString(): string {\n return !!this.token ? this.token : '';\n }\n}\n\n/**\n * Wrapper for JWT token with additional methods.\n */\nexport class NbAuthJWTToken extends NbAuthSimpleToken {\n\n static NAME = 'nb:auth:jwt:token';\n\n /**\n * for JWT token, the iat (issued at) field of the token payload contains the creation Date\n */\n protected prepareCreatedAt(date: Date) {\n const decoded = this.getPayload();\n return decoded && decoded.iat ? new Date(Number(decoded.iat) * 1000) : super.prepareCreatedAt(date);\n }\n\n /**\n * Returns payload object\n * @returns any\n */\n protected parsePayload(): void {\n if (!this.token) {\n throw new NbAuthTokenNotFoundError('Token not found. ')\n }\n this.payload = decodeJwtPayload(this.token);\n }\n\n /**\n * Returns expiration date\n * @returns Date\n */\n getTokenExpDate(): Date {\n const decoded = this.getPayload();\n if (decoded && !decoded.hasOwnProperty('exp')) {\n return null;\n }\n const date = new Date(0);\n date.setUTCSeconds(decoded.exp); // 'cause jwt token are set in seconds\n return date;\n }\n\n /**\n * Is data expired\n * @returns {boolean}\n */\n isValid(): boolean {\n return super.isValid() && (!this.getTokenExpDate() || new Date() < this.getTokenExpDate());\n }\n}\n\nconst prepareOAuth2Token = (data) => {\n if (typeof data === 'string') {\n try {\n return JSON.parse(data);\n } catch (e) {}\n }\n return data;\n};\n\n/**\n * Wrapper for OAuth2 token whose access_token is a JWT Token\n */\nexport class NbAuthOAuth2Token extends NbAuthSimpleToken {\n\n static NAME = 'nb:auth:oauth2:token';\n\n constructor( data: { [key: string]: string|number }|string = {},\n ownerStrategyName: string,\n createdAt?: Date) {\n\n // we may get it as string when retrieving from a storage\n super(prepareOAuth2Token(data), ownerStrategyName, createdAt);\n }\n\n /**\n * Returns the token value\n * @returns string\n */\n getValue(): string {\n return this.token.access_token;\n }\n\n /**\n * Returns the refresh token\n * @returns string\n */\n getRefreshToken(): string {\n return this.token.refresh_token;\n }\n\n /**\n * put refreshToken in the token payload\n * @param refreshToken\n */\n setRefreshToken(refreshToken: string) {\n this.token.refresh_token = refreshToken;\n }\n\n /**\n * Parses token payload\n * @returns any\n */\n protected parsePayload(): void {\n if (!this.token) {\n throw new NbAuthTokenNotFoundError('Token not found.')\n } else {\n if (!Object.keys(this.token).length) {\n throw new NbAuthEmptyTokenError('Cannot extract payload from an empty token.');\n }\n }\n this.payload = this.token;\n }\n\n /**\n * Returns the token type\n * @returns string\n */\n getType(): string {\n return this.token.token_type;\n }\n\n /**\n * Is data expired\n * @returns {boolean}\n */\n isValid(): boolean {\n return super.isValid() && (!this.getTokenExpDate() || new Date() < this.getTokenExpDate());\n }\n\n /**\n * Returns expiration date\n * @returns Date\n */\n getTokenExpDate(): Date {\n if (!this.token.hasOwnProperty('expires_in')) {\n return null;\n }\n return new Date(this.createdAt.getTime() + Number(this.token.expires_in) * 1000);\n}\n\n /**\n * Convert to string\n * @returns {string}\n */\n toString(): string {\n return JSON.stringify(this.token);\n }\n}\n\n/**\n * Wrapper for OAuth2 token embedding JWT tokens\n */\nexport class NbAuthOAuth2JWTToken extends NbAuthOAuth2Token {\n\n static NAME = 'nb:auth:oauth2:jwt:token';\n\n protected accessTokenPayload: any;\n\n protected parsePayload(): void {\n super.parsePayload();\n this.parseAccessTokenPayload();\n }\n\n protected parseAccessTokenPayload(): any {\n const accessToken = this.getValue();\n if (!accessToken) {\n throw new NbAuthTokenNotFoundError('access_token key not found.')\n }\n this.accessTokenPayload = decodeJwtPayload(accessToken);\n }\n\n /**\n * Returns access token payload\n * @returns any\n */\n getAccessTokenPayload(): any {\n return this.accessTokenPayload;\n }\n\n /**\n * for Oauth2 JWT token, the iat (issued at) field of the access_token payload\n */\n protected prepareCreatedAt(date: Date) {\n const payload = this.accessTokenPayload;\n return payload && payload.iat ? new Date(Number(payload.iat) * 1000) : super.prepareCreatedAt(date);\n }\n\n /**\n * Is token valid\n * @returns {boolean}\n */\n isValid(): boolean {\n return this.accessTokenPayload && super.isValid();\n }\n\n /**\n * Returns expiration date :\n * - exp if set,\n * - super.getExpDate() otherwise\n * @returns Date\n */\n getTokenExpDate(): Date {\n if (this.accessTokenPayload && this.accessTokenPayload.hasOwnProperty('exp')) {\n const date = new Date(0);\n date.setUTCSeconds(this.accessTokenPayload.exp);\n return date;\n } else {\n return super.getTokenExpDate();\n }\n }\n}\n","import { Inject, Injectable, InjectionToken } from '@angular/core';\n\nimport { nbAuthCreateToken, NbAuthToken, NbAuthTokenClass } from './token';\nimport { NB_AUTH_TOKENS } from '../../auth.options';\n\nexport interface NbTokenPack {\n name: string,\n ownerStrategyName: string,\n createdAt: Number,\n value: string,\n}\n\nexport const NB_AUTH_FALLBACK_TOKEN = new InjectionToken<NbAuthTokenClass>('Nebular Auth Options');\n\n/**\n * Creates a token parcel which could be stored/restored\n */\n@Injectable()\nexport class NbAuthTokenParceler {\n\n constructor(@Inject(NB_AUTH_FALLBACK_TOKEN) private fallbackClass: NbAuthTokenClass,\n @Inject(NB_AUTH_TOKENS) private tokenClasses: NbAuthTokenClass[]) {\n }\n\n wrap(token: NbAuthToken): string {\n return JSON.stringify({\n name: token.getName(),\n ownerStrategyName: token.getOwnerStrategyName(),\n createdAt: token.getCreatedAt().getTime(),\n value: token.toString(),\n });\n }\n\n unwrap(value: string): NbAuthToken {\n let tokenClass: NbAuthTokenClass = this.fallbackClass;\n let tokenValue = '';\n let tokenOwnerStrategyName = '';\n let tokenCreatedAt: Date = null;\n\n const tokenPack: NbTokenPack = this.parseTokenPack(value);\n if (tokenPack) {\n tokenClass = this.getClassByName(tokenPack.name) || this.fallbackClass;\n tokenValue = tokenPack.value;\n tokenOwnerStrategyName = tokenPack.ownerStrategyName;\n tokenCreatedAt = new Date(Number(tokenPack.createdAt));\n }\n\n return nbAuthCreateToken(tokenClass, tokenValue, tokenOwnerStrategyName, tokenCreatedAt);\n\n }\n\n // TODO: this could be moved to a separate token registry\n protected getClassByName(name): NbAuthTokenClass {\n return this.tokenClasses.find((tokenClass: NbAuthTokenClass) => tokenClass.NAME === name);\n }\n\n protected parseTokenPack(value): NbTokenPack {\n try {\n return JSON.parse(value);\n } catch (e) { }\n return null;\n }\n}\n","import { Injectable } from '@angular/core';\n\nimport { NbAuthToken } from './token';\nimport { NbAuthTokenParceler } from './token-parceler';\n\nexport abstract class NbTokenStorage {\n\n abstract get(): NbAuthToken;\n abstract set(token: NbAuthToken);\n abstract clear();\n}\n\n/**\n * Service that uses browser localStorage as a storage.\n *\n * The token storage is provided into auth module the following way:\n * ```ts\n * { provide: NbTokenStorage, useClass: NbTokenLocalStorage },\n * ```\n *\n * If you need to change the storage behaviour or provide your own - just extend your class from basic `NbTokenStorage`\n * or `NbTokenLocalStorage` and provide in your `app.module`:\n * ```ts\n * { provide: NbTokenStorage, useClass: NbTokenCustomStorage },\n * ```\n *\n */\n@Injectable()\nexport class NbTokenLocalStorage extends NbTokenStorage {\n\n protected key = 'auth_app_token';\n\n constructor(private parceler: NbAuthTokenParceler) {\n super();\n }\n\n /**\n * Returns token from localStorage\n * @returns {NbAuthToken}\n */\n get(): NbAuthToken {\n const raw = localStorage.getItem(this.key);\n return this.parceler.unwrap(raw);\n }\n\n /**\n * Sets token to localStorage\n * @param {NbAuthToken} token\n */\n set(token: NbAuthToken) {\n const raw = this.parceler.wrap(token);\n localStorage.setItem(this.key, raw);\n }\n\n /**\n * Clears token from localStorage\n */\n clear() {\n localStorage.removeItem(this.key);\n }\n}\n","import { Injectable } from '@angular/core';\nimport { Observable, BehaviorSubject, of as observableOf } from 'rxjs';\nimport { filter, share } from 'rxjs/operators';\n\nimport { NbTokenStorage } from './token-storage';\nimport { NbAuthToken } from './token';\n\n/**\n * Service that allows you to manage authentication token - get, set, clear and also listen to token changes over time.\n */\n@Injectable()\nexport class NbTokenService {\n\n protected token$: BehaviorSubject<NbAuthToken> = new BehaviorSubject(null);\n\n constructor(protected tokenStorage: NbTokenStorage) {\n this.publishStoredToken();\n }\n\n /**\n * Publishes token when it changes.\n * @returns {Observable<NbAuthToken>}\n */\n tokenChange(): Observable<NbAuthToken> {\n return this.token$\n .pipe(\n filter(value => !!value),\n share(),\n );\n }\n\n /**\n * Sets a token into the storage. This method is used by the NbAuthService automatically.\n *\n * @param {NbAuthToken} token\n * @returns {Observable<any>}\n */\n set(token: NbAuthToken): Observable<null> {\n this.tokenStorage.set(token);\n this.publishStoredToken();\n return observableOf(null);\n }\n\n /**\n * Returns observable of current token\n * @returns {Observable<NbAuthToken>}\n */\n get(): Observable<NbAuthToken> {\n const token = this.tokenStorage.get();\n return observableOf(token);\n }\n\n /**\n * Removes the token and published token value\n *\n * @returns {Observable<any>}\n */\n clear(): Observable<null> {\n this.tokenStorage.clear();\n this.publishStoredToken();\n return observableOf(null);\n }\n\n protected publishStoredToken() {\n this.token$.next(this.tokenStorage.get());\n }\n}\n","/**\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */\nimport { Inject, Injectable } from '@angular/core';\n\nimport { Observable, of as observableOf } from 'rxjs';\nimport { switchMap, map } from 'rxjs/operators';\n\nimport { NbAuthStrategy } from '../strategies/auth-strategy';\nimport { NB_AUTH_STRATEGIES } from '../auth.options';\nimport { NbAuthResult } from './auth-result';\nimport { NbTokenService } from './token/token.service';\nimport { NbAuthToken } from './token/token';\n\n/**\n * Common authentication service.\n * Should be used to as an interlayer between UI Components and Auth Strategy.\n */\n@Injectable()\nexport class NbAuthService {\n\n constructor(protected tokenService: NbTokenService,\n @Inject(NB_AUTH_STRATEGIES) protected strategies) {\n }\n\n /**\n * Retrieves current authenticated token stored\n * @returns {Observable<any>}\n */\n getToken(): Observable<NbAuthToken> {\n return this.tokenService.get();\n }\n\n /**\n * Returns true if auth token is present in the token storage\n * @returns {Observable<boolean>}\n */\n isAuthenticated(): Observable<boolean> {\n return this.getToken()\n .pipe(map((token: NbAuthToken) => token.isValid()));\n }\n\n /**\n * Returns true if valid auth token is present in the token storage.\n * If not, calls the strategy refreshToken, and returns isAuthenticated() if success, false otherwise\n * @returns {Observable<boolean>}\n */\n isAuthenticatedOrRefresh(): Observable<boolean> {\n return this.getToken()\n .pipe(\n switchMap(token => {\n if (token.getValue() && !token.isValid()) {\n return this.refreshToken(token.getOwnerStrategyName(), token)\n .pipe(\n switchMap(res => {\n if (res.isSuccess()) {\n return this.isAuthenticated();\n } else {\n return observableOf(false);\n }\n }),\n )\n } else {\n return observableOf(token.isValid());\n }\n }));\n }\n\n /**\n * Returns tokens stream\n * @returns {Observable<NbAuthSimpleToken>}\n */\n onTokenChange(): Observable<NbAuthToken> {\n return this.tokenService.tokenChange();\n }\n\n /**\n * Returns authentication status stream\n * @returns {Observable<boolean>}\n */\n onAuthenticationChange(): Observable<boolean> {\n return this.onTokenChange()\n .pipe(map((token: NbAuthToken) => token.isValid()));\n }\n\n /**\n * Authenticates with the selected strategy\n * Stores received token in the token storage\n *\n * Example:\n * authenticate('email', {email: 'email@example.com', password: 'test'})\n *\n * @param strategyName\n * @param data\n * @returns {Observable<NbAuthResult>}\n */\n authenticate(strategyName: string, data?: any): Observable<NbAuthResult> {\n return this.getStrategy(strategyName).authenticate(data)\n .pipe(\n switchMap((result: NbAuthResult) => {\n return this.processResultToken(result);\n }),\n );\n }\n\n /**\n * Registers with the selected strategy\n * Stores received token in the token storage\n *\n * Example:\n * register('email', {email: 'email@example.com', name: 'Some Name', password: 'test'})\n *\n * @param strategyName\n * @param data\n * @returns {Observable<NbAuthResult>}\n */\n register(strategyName: string, data?: any): Observable<NbAuthResult> {\n return this.getStrategy(strategyName).register(data)\n .pipe(\n switchMap((result: NbAuthResult) => {\n return this.processResultToken(result);\n }),\n );\n }\n\n /**\n * Sign outs with the selected strategy\n * Removes token from the token storage\n *\n * Example:\n * logout('email')\n *\n * @param strategyName\n * @returns {Observable<NbAuthResult>}\n */\n logout(strategyName: string): Observable<NbAuthResult> {\n return this.getStrategy(strategyName).logout()\n .pipe(\n switchMap((result: NbAuthResult) => {\n if (result.isSuccess()) {\n this.tokenService.clear()\n .pipe(map(() => result));\n }\n return observableOf(result);\n }),\n );\n }\n\n /**\n * Sends forgot password request to the selected strategy\n *\n * Example:\n * requestPassword('email', {email: 'email@example.com'})\n *\n * @param strategyName\n * @param data\n * @returns {Observable<NbAuthResult>}\n */\n requestPassword(strategyName: string, data?: any): Observable<NbAuthResult> {\n return this.getStrategy(strategyName).requestPassword(data);\n }\n\n /**\n * Tries to reset password with the selected strategy\n *\n * Example:\n * resetPassword('email', {newPassword: 'test'})\n *\n * @param strategyName\n * @param data\n * @returns {Observable<NbAuthResult>}\n */\n resetPassword(strategyName: string, data?: any): Observable<NbAuthResult> {\n return this.getStrategy(strategyName).resetPassword(data);\n }\n\n /**\n * Sends a refresh token request\n * Stores received token in the token storage\n *\n * Example:\n * refreshToken('email', {token: token})\n *\n * @param {string} strategyName\n * @param data\n * @returns {Observable<NbAuthResult>}\n */\n refreshToken(strategyName: string, data?: any): Observable<NbAuthResult> {\n return this.getStrategy(strategyName).refreshToken(data)\n .pipe(\n switchMap((result: NbAuthResult) => {\n return this.processResultToken(result);\n }),\n );\n }\n\n /**\n * Get registered strategy by name\n *\n * Example:\n * getStrategy('email')\n *\n * @param {string} provider\n * @returns {NbAbstractAuthProvider}\n */\n protected getStrategy(strategyName: string): NbAuthStrategy {\n const found = this.strategies.find((strategy: NbAuthStrategy) => strategy.getName() === strategyName);\n\n if (!found) {\n throw new TypeError(`There is no Auth Strategy registered under '${strategyName}' name`);\n }\n\n return found;\n }\n\n private processResultToken(result: NbAuthResult) {\n if (result.isSuccess() && result.getToken()) {\n return this.tokenService.set(result.getToken())\n .pipe(\n map((token: NbAuthToken) => {\n return result;\n }),\n );\n }\n\n return observableOf(result);\n }\n}\n","import { HttpHeaders, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs';\nimport { NbAuthResult } from '../services/auth-result';\nimport { NbAuthStrategyOptions } from './auth-strategy-options';\nimport { deepExtend, getDeepFromObject } from '../helpers';\nimport { NbAuthToken, nbAuthCreateToken, NbAuthIllegalTokenError } from '../services/token/token';\n\nexport abstract class NbAuthStrategy {\n protected defaultOptions: NbAuthStrategyOptions;\n protected options: NbAuthStrategyOptions;\n\n // we should keep this any and validation should be done in `register` method instead\n // otherwise it won't be possible to pass an empty object\n setOptions(options: any): void {\n this.options = deepExtend({}, this.defaultOptions, options);\n }\n\n getOption(key: string): any {\n return getDeepFromObject(this.options, key, null);\n }\n\n createToken<T extends NbAuthToken>(value: any, failWhenInvalidToken?: boolean): T {\n const token = nbAuthCreateToken<T>(this.getOption('token.class'), value, this.getName());\n // At this point, nbAuthCreateToken failed with NbAuthIllegalTokenError which MUST be intercepted by strategies\n // Or token is created. It MAY be created even if backend did not return any token, in this case it is !Valid\n if (failWhenInvalidToken && !token.isValid()) {\n // If we require a valid token (i.e. isValid), then we MUST throw NbAuthIllegalTokenError so that the strategies\n // intercept it\n throw new NbAuthIllegalTokenError('Token is empty or invalid.');\n }\n return token;\n }\n\n getName(): string {\n return this.getOption('name');\n }\n\n abstract authenticate(data?: any): Observable<NbAuthResult>;\n\n abstract register(data?: any): Observable<NbAuthResult>;\n\n abstract requestPassword(data?: any): Observable<NbAuthResult>;\n\n abstract resetPassword(data?: any): Observable<NbAuthResult>;\n\n abstract logout(): Observable<NbAuthResult>;\n\n abstract refreshToken(data?: any): Observable<NbAuthResult>;\n\n protected createFailResponse(data?: any): HttpResponse<Object> {\n return new HttpResponse<Object>({ body: {}, status: 401 });\n }\n\n protected createSuccessResponse(data?: any): HttpResponse<Object> {\n return new HttpResponse<Object>({ body: {}, status: 200 });\n }\n\n protected getActionEndpoint(action: string): string {\n const actionEndpoint: string = this.getOption(`${action}.endpoint`);\n const baseEndpoint: string = this.getOption('baseEndpoint');\n return actionEndpoint ? baseEndpoint + actionEndpoint : '';\n }\n\n protected getHeaders(): HttpHeaders {\n const customHeaders: NbAuthStrategyOptions['headers'] = this.getOption('headers') ?? {};\n if (customHeaders instanceof HttpHeaders) {\n return customHeaders;\n }\n\n let headers = new HttpHeaders();\n Object.entries(customHeaders).forEach(([key, value]) => {\n headers = headers.append(key, value);\n });\n return headers;\n }\n}\n","import { NbAuthToken } from './token/token';\n\nexport class NbAuthResult {\n\n protected token: NbAuthToken;\n protected errors: string[] = [];\n protected messages: string[] = [];\n\n // TODO: better pass object\n constructor(protected success: boolean,\n protected response?: any,\n protected redirect?: any,\n errors?: any,\n messages?: any,\n token: NbAuthToken = null) {\n\n this.errors = this.errors.concat([errors]);\n if (errors instanceof Array) {\n this.errors = errors;\n }\n\n this.messages = this.messages.concat([messages]);\n if (messages instanceof Array) {\n this.messages = messages;\n }\n\n this.token = token;\n }\n\n getResponse(): any {\n return this.response;\n }\n\n getToken(): NbAuthToken {\n return this.token;\n }\n\n getRedirect(): string {\n return this.redirect;\n }\n\n getErrors(): string[] {\n return this.errors.filter(val => !!val);\n }\n\n getMessages(): string[] {\n return this.messages.filter(val => !!val);\n }\n\n isSuccess(): boolean {\n return this.success;\n }\n\n isFailure(): boolean {\n return !this.success;\n }\n}\n","/**\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */\nimport { HttpHeaders } from '@angular/common/http';\nimport { NbAuthTokenClass } from '../services/token/token';\n\nexport interface NbStrategyToken {\n class?: NbAuthTokenClass;\n [key: string]: any;\n}\n\nexport class NbAuthStrategyOptions {\n name: string;\n token?: NbStrategyToken;\n headers?: HttpHeaders | { [header: string]: string | string[]; };\n}\n","/**\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */\nimport { NbAuthStrategyOptions, NbStrategyToken } from '../auth-strategy-options';\nimport { NbAuthSimpleToken } from '../../services/token/token';\n\nexport class NbDummyAuthStrategyOptions extends NbAuthStrategyOptions {\n token?: NbStrategyToken = {\n class: NbAuthSimpleToken,\n };\n delay?: number = 1000;\n alwaysFail?: boolean = false;\n}\n\nexport const dummyStrategyOptions: NbDummyAuthStrategyOptions = new NbDummyAuthStrategyOptions();\n","import { Injectable } from '@angular/core';\n\nimport { Observable, of as observableOf } from 'rxjs';\nimport { delay } from 'rxjs/operators';\n\nimport { NbAuthStrategy } from '../auth-strategy';\nimport { NbAuthResult } from '../../services/auth-result';\nimport { NbDummyAuthStrategyOptions, dummyStrategyOptions } from './dummy-strategy-options';\nimport { NbAuthStrategyClass } from '../../auth.options';\n\n/**\n * Dummy auth strategy. Could be useful for auth setup when backend is not available yet.\n *\n *\n * Strategy settings.\n *\n * ```ts\n * export class NbDummyAuthStrategyOptions extends NbAuthStrategyOptions {\n * name = 'dummy';\n * token = {\n * class: NbAuthSimpleToken,\n * };\n * delay? = 1000;\n * alwaysFail? = false;\n * }\n * ```\n */\n@Injectable()\nexport class NbDummyAuthStrategy extends NbAuthStrategy {\n protected defaultOptions: NbDummyAuthStrategyOptions = dummyStrategyOptions;\n\n static setup(options: NbDummyAuthStrategyOptions): [NbAuthStrategyClass, NbDummyAuthStrategyOptions] {\n return [NbDummyAuthStrategy, options];\n }\n\n authenticate(data?: any): Observable<NbAuthResult> {\n return observableOf(this.createDummyResult(data)).pipe(delay(this.getOption('delay')));\n }\n\n register(data?: any): Observable<NbAuthResult> {\n return observableOf(this.createDummyResult(data)).pipe(delay(this.getOption('delay')));\n }\n\n requestPassword(data?: any): Observable<NbAuthResult> {\n return observableOf(this.createDummyResult(data)).pipe(delay(this.getOption('delay')));\n }\n\n resetPassword(data?: any): Observable<NbAuthResult> {\n return observableOf(this.createDummyResult(data)).pipe(delay(this.getOption('delay')));\n }\n\n logout(data?: any): Observable<NbAuthResult> {\n return observableOf(this.createDummyResult(data)).pipe(delay(this.getOption('delay')));\n }\n\n refreshToken(data?: any): Observable<NbAuthResult> {\n return observableOf(this.createDummyResult(data)).pipe(delay(this.getOption('delay')));\n }\n\n protected createDummyResult(data?: any): NbAuthResult {\n if (this.getOption('alwaysFail')) {\n return new NbAuthResult(false, this.createFailResponse(data), null, ['Something went wrong.']);\n }\n\n try {\n const token = this.createToken('test token', true);\n return new NbAuthResult(true, this.createSuccessResponse(data), '/', [], ['Successfully logged in.'], token);\n } catch (err) {\n return new NbAuthResult(false, this.createFailResponse(data), null, [(err as Error).message]);\n }\n }\n}\n","/**\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */\n\nimport { NbAuthOAuth2Token, NbAuthTokenClass } from '../../services/token/token';\nimport { NbAuthStrategyOptions } from '../auth-strategy-options';\n\nexport enum NbOAuth2ResponseType {\n CODE = 'code',\n TOKEN = 'token',\n}\n\n// TODO: client_credentials\nexport enum NbOAuth2GrantType {\n AUTHORIZATION_CODE = 'authorization_code',\n PASSWORD = 'password',\n REFRESH_TOKEN = 'refresh_token',\n}\n\nexport enum NbOAuth2ClientAuthMethod {\n NONE = 'none',\n BASIC = 'basic',\n REQUEST_BODY = 'request-body',\n}\n\nexport class NbOAuth2AuthStrategyOptions extends NbAuthStrategyOptions {\n baseEndpoint?: string = '';\n clientId: string = '';\n clientSecret?: string = '';\n clientAuthMethod?: string = NbOAuth2ClientAuthMethod.NONE;\n redirect?: { success?: string; failure?: string } = {\n success: '/',\n failure: null,\n };\n defaultErrors?: any[] = ['Something went wrong, please try again.'];\n defaultMessages?: any[] = ['You have been successfully authenticated.'];\n authorize?: {\n endpoint?: string;\n redirectUri?: string;\n responseType?: string;\n requireValidToken?: boolean; // used only with NbOAuth2ResponseType.TOKEN\n scope?: string;\n state?: string;\n params?: { [key: string]: string };\n } = {\n endpoint: 'authorize',\n responseType: NbOAuth2ResponseType.CODE,\n requireValidToken: true,\n };\n token?: {\n endpoint?: string;\n grantType?: string;\n redirectUri?: string;\n scope?: string; // Used only with 'password' grantType\n requireValidToken?: boolean;\n class: NbAuthTokenClass,\n } = {\n endpoint: 'token',\n grantType: NbOAuth2GrantType.AUTHORIZATION_CODE,\n requireValidToken: true,\n class: NbAuthOAuth2Token,\n };\n refresh?: {\n endpoint?: string;\n grantType?: string;\n scope?: string;\n requireValidToken?: boolean;\n } = {\n endpoint: 'token',\n grantType: NbOAuth2GrantType.REFRESH_TOKEN,\n requireValidToken: true,\n };\n}\n\nexport const auth2StrategyOptions: NbOAuth2AuthStrategyOptions = new NbOAuth2AuthStrategyOptions();\n","/**\n * @license\n * Copyright Akveo. All Rights Reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */\nimport { Inject, Injectable } from '@angular/core';\nimport { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';\nimport { ActivatedRoute } from '@angular/router';\nimport { Observable, of as observableOf } from 'rxjs';\nimport { switchMap, map, catchError } from 'rxjs/operators';\nimport { NB_WINDOW } from '@nebular/theme';\n\nimport { NbAuthStrategy } from '../auth-strategy';\nimport { NbAuthIllegalTokenError, NbAuthRefreshableToken, NbAuthToken } from '../../services/token/token';\nimport { NbAuthResult } from '../../services/auth-result';\nimport {\n NbOAuth2AuthStrategyOptions,\n NbOAuth2ResponseType,\n auth2StrategyOptions,\n NbOAuth2GrantType,\n NbOAuth2ClientAuthMethod,\n} from './oauth2-strategy.options';\nimport { NbAuthStrategyClass } from '../../auth.options';\n\n/**\n * OAuth2 authentication strategy.\n *\n * Strategy settings:\n *\n * ```ts\n * export enum NbOAuth2ResponseType {\n * CODE = 'code',\n * TOKEN = 'token',\n * }\n *\n * export enum NbOAuth2GrantType {\n * AUTHORIZATION_CODE = 'authorization_code',\n * PASSWORD = 'password',\n * REFRESH_TOKEN = 'refresh_token',\n * }\n *\n * export class NbOAuth2AuthStrategyOptions {\n * name: string;\n * baseEndpoint?: string = '';\n * clientId: string = '';\n * clientSecret: string = '';\n * clientAuthMethod: string = NbOAuth2ClientAuthMethod.NONE;\n * redirect?: { success?: string; failure?: string } = {\n * success: '/',\n * failure: null,\n * };\n * defaultErrors?: any[] = ['Something went wrong, please try again.'];\n * defaultMessages?: any[] = ['You have been successfully authenticated.'];\n * authorize?: {\n * endpoint?: string;\n * redirectUri?: string;\n * responseType?: string;\n * requireValidToken: true,\n * scope?: string;\n * state?: string;\n * params?: { [key: string]: string };\n * } = {\n * endpoint: 'authorize',\n * responseType: NbOAuth2ResponseType.CODE,\n * };\n * token?: {\n * endpoint?: string;\n * grantType?: string;\n * requireValidToken: true,\n * redirectUri?: string;\n * scope?: string;\n * class: NbAuthTokenClass,\n * } = {\n * endpoint: 'token',\n * grantType: NbOAuth2GrantType.AUTHORIZATION_CODE,\n * class: NbAuthOAuth2Token,\n * };\n * refresh?: {\n * endpoint?: string;\n * grantType?: string;\n * scope?: string;\n * requireValidToken: true,\n * } = {\n * endpoint: 'token',\n * grantType: NbOAuth2GrantType.REFRESH_TOKEN,\n * };\n * }\n * ```\n *\n */\n@Injectable()\nexport class NbOAuth2AuthStrategy extends NbAuthStrategy {\n static setup(options: NbOAuth2AuthStrategyOptions): [NbAuthStrategyClass, NbOAuth2AuthStrategyOptions] {\n return [NbOAuth2AuthStrategy, options];\n }\n\n get responseType() {\n return this.getOption('authorize.responseType');\n }\n\n get clientAuthMethod() {\n return this.getOption('clientAuthMethod');\n }\n\n protected redirectResultHandlers: { [key: string]: Function } = {\n [NbOAuth2ResponseType.CODE]: () => {\n return observableOf(this.route.snapshot.queryParams).pipe(\n switchMap((params: any) => {\n if (params.code) {\n return this.requestToken(params.code);\n }\n\n return observableOf(\n new NbAuthResult(false, params, this.getOption('redirect.failure'), this.getOption('defaultErrors'), []),\n );\n }),\n );\n },\n [NbOAuth2ResponseType.TOKEN]: () => {\n const module = 'authorize';\n const requireValidToken = this.getOption(`${module}.requireValidToken`);\n return observableOf(this.route.snapshot.fragment).pipe(\n map((fragment) => this.parseHashAsQueryParams(fragment)),\n map((params: any) => {\n if (!params.error) {\n return new NbAuthResult(\n true,\n params,\n this.getOption('redirect.success'),\n [],\n this.getOption('defaultMessages'),\n this.createToken(params, requireValidToken),\n );\n }\n return new NbAuthResult(\n false,\n params,\n this.getOption('redirect.failure'),\n this.getOption('defaultErrors'),\n [],\n );\n }),\n catchError((err) => {\n const errors = [];\n if (err instanceof NbAuthIllegalTokenError) {\n errors.push(err.message);\n } else {\n errors.push('Something went wrong.');\n }\n return observableOf(new NbAuthResult(false, err, this.getOption('redirect.failure'), errors));\n }),\n );\n },\n };\n\n protected redirectResults: { [key: string]: Function } = {\n [NbOAuth2ResponseType.CODE]: () => {\n return observableOf(this.route.snapshot.queryParams).pipe(\n map((params: any) => !!(params && (params.code || params.error))),\n );\n },\n [NbOAuth2ResponseType.TOKEN]: () => {\n return observableOf(this.route.snapshot.fragment).pipe(\n map((fragment) => this.parseHashAsQueryParams(fragment)),\n map((params: any) => !!(params && (params.access_token || params.error))),\n );\n },\n };\n\n protected defaultOptions: NbOAuth2AuthStrategyOptions = auth2StrategyOptions;\n\n constructor(protected http: HttpClient, protected route: ActivatedRoute, @Inject(NB_WINDOW) protected window: any) {\n super();\n }\n\n authenticate(data?: any): Observable<NbAuthResult> {\n if (this.getOption('token.grantType') === NbOAuth2GrantType.PASSWORD) {\n return this.passwordToken(data.email, data.password);\n } else {\n return this.isRedirectResult().pipe(\n switchMap((result: boolean) => {\n if (!result) {\n this.authorizeRedirect();\n return observableOf(new NbAuthResult(true));\n }\n return this.getAuthorizationResult();\n }),\n );\n }\n }\n\n getAuthorizationResult(): Observable<any> {\n const redirectResultHandler = this.redirectResultHandlers[this.responseType];\n if (redirectResultHandler) {\n return redirectResultHandler.call(this);\n }\n\n throw new Error(`'${this.responseType}' responseType is not supported,\n only 'token' and 'code' are supported now`);\n }\n\n refreshToken(token: NbAuthRefreshableToken): Observable<NbAuthResult> {\n const module = 'refresh';\n const url = this.getActionEndpoint(module);\n const requireValidToken = this.getOption(`${module}.requireValidToken`);\n\n return this.http.post(url, this.buildRefreshRequestData(token), { headers: this.getHeaders() }).pipe(\n map((res) => {\n return new NbAuthResult(\n true,\n res,\n this.getOption('redirect.success'),\n [],\n this.getOption('defaultMessages'),\n this.createRefreshedToken(res, token, requireValidToken),\n );\n }),\n catchError((res) => this.handleResponseError(res)),\n );\n }\n\n passwordToken(username: string, password: string): Observable<NbAuthResult> {\n const module = 'token';\n const url = this.getActionEndpoint(module);\n const requireValidToken = this.getOption(`${module}.requireValidToken`);\n\n return this.http.post(url, this.buildPasswordRequestData(username, password), { headers: this.getHeaders() }).pipe(\n map((res) => {\n return new NbAuthResult(\n true,\n res,\n this.getOption('redirect.success'),\n [],\n this.getOption('defaultMessages'),\n this.createToken(res, requireValidToken),\n );\n }),\n catchError((res) => this.handleResponseError(res)),\n );\n }\n\n protected authorizeRedirect() {\n this.window.location.href = this.buildRedirectUrl();\n }\n\n protected isRedirectResult(): Observable<boolean> {\n return this.redirectResults[this.responseType].call(this);\n }\n\n protected requestToken(code: string) {\n const module = 'token';\n const url = this.getActionEndpoint(module);\n const requireValidToken = this.getOption(`${module}.requireValidToken`);\n\n return this.http.post(url, this.buildCodeRequestData(code), { headers: this.getHeaders() }).pipe(\n