All files / src/app/core/services/token token.service.ts

75% Statements 27/36
65% Branches 13/20
61.11% Functions 11/18
74.28% Lines 26/35

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 12932x 32x 32x               32x     32x 32x 32x 32x                                       32x   2x   2x 2x   2x             2x   2x             2x 2x     2x 2x                           1x       1x                                         2x       2x   2x                 2x 2x                  
import { HttpHeaders } from '@angular/common/http';
import { Injectable, Injector } from '@angular/core';
import {
  AuthConfig,
  OAuthInfoEvent,
  OAuthService,
  OAuthStorage,
  OAuthSuccessEvent,
  TokenResponse,
} from 'angular-oauth2-oidc';
import { BehaviorSubject, Observable, filter, first, from, map, noop, switchMap, take } from 'rxjs';
 
import { FetchTokenOptions, GrantType } from 'ish-core/models/token/token.interface';
import { ApiService } from 'ish-core/services/api/api.service';
import { ApiTokenService } from 'ish-core/utils/api-token/api-token.service';
import { InstanceCreators } from 'ish-core/utils/instance-creators';
import { whenTruthy } from 'ish-core/utils/operators';
 
function storageFactory(): OAuthStorage {
  const prefix = 'icm_' as const;
  Iif (!SSR) {
    return {
      getItem(key: string): string {
        return localStorage.getItem(`${prefix}${key}`);
      },
      removeItem(key: string): void {
        return localStorage.removeItem(`${prefix}${key}`);
      },
      setItem(key: string, data: string): void {
        return localStorage.setItem(`${prefix}${key}`, data);
      },
    };
  }
}
 
@Injectable({ providedIn: 'root' })
export class TokenService {
  private oAuthService: OAuthService;
  private serviceConfigured$ = new BehaviorSubject<boolean>(false);
 
  constructor(private apiService: ApiService, private apiTokenService: ApiTokenService, parent: Injector) {
    this.oAuthService = InstanceCreators.getOAuthServiceInstance(parent, storageFactory);
 
    this.apiService
      .constructUrlForPath('token', {
        sendCurrency: true,
        sendLocale: true,
      })
      .pipe(
        whenTruthy(),
        filter(url => !url.startsWith('/')), // url should not be relative
        take(1),
        map<string, AuthConfig>(url => ({
          tokenEndpoint: url,
          requireHttps: url.startsWith('https'),
          timeoutFactor: 0.5,
        }))
      )
      .subscribe(conf => {
        this.oAuthService.configure(conf);
        this.serviceConfigured$.next(true);
      });
 
    this.setApiTokenCookie$().subscribe(noop);
    this.setupRefreshTokenMechanism$().subscribe(noop);
  }
 
  /**
   * Fetches a new user token. Based on the grantType the user has to apply certain token options to the method.
   *
   * @param grantType   The given type ('anonymous', 'password', 'client_credentials', 'refresh_token') is used to specify, how the user token should be fetched.
   */
  fetchToken<T extends 'anonymous'>(grantType: T): Observable<TokenResponse>;
  fetchToken<T extends GrantType, R extends FetchTokenOptions<T>>(grantType: T, options: R): Observable<TokenResponse>;
  fetchToken<T extends GrantType, R extends FetchTokenOptions<T>>(
    grantType: T,
    options?: R
  ): Observable<TokenResponse> {
    return this.serviceConfigured$.pipe(
      whenTruthy(),
      first(),
      switchMap(() =>
        from(
          this.oAuthService?.fetchTokenUsingGrant(
            grantType,
            options ?? {},
            new HttpHeaders({ 'content-type': 'application/x-www-form-urlencoded' })
          )
        )
      )
    );
  }
 
  logOut() {
    this.oAuthService.logOut(true);
  }
 
  /**
   * Refresh existing tokens, when token is about to expire
   *
   * @returns {TokenResponse} updated tokens
   */
  private setupRefreshTokenMechanism$(): Observable<TokenResponse> {
    return this.serviceConfigured$.pipe(
      whenTruthy(),
      first(),
      switchMap(() =>
        this.oAuthService.events.pipe(
          filter(
            event => event instanceof OAuthInfoEvent && event.type === 'token_expires' && event.info === 'access_token'
          ),
          switchMap(() => from(this.oAuthService.refreshToken()))
        )
      )
    );
  }
 
  private setApiTokenCookie$() {
    return this.oAuthService.events.pipe(
      filter(event => event instanceof OAuthSuccessEvent && event.type === 'token_received'),
      map(() =>
        this.apiTokenService.setApiToken(this.oAuthService.getAccessToken(), {
          expires: new Date(this.oAuthService.getAccessTokenExpiration()),
        })
      )
    );
  }
}