All files / src/app/core/utils/authorization-toggle authorization-toggle.service.ts

100% Statements 20/20
93.33% Branches 14/15
100% Functions 5/5
100% Lines 19/19

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 4134x 34x 34x 34x   34x 34x   34x 147x 66x 81x 1x     80x 87x         34x       6x         6x 2x   4x     4x        
import { Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
 
import { getUserPermissions } from 'ish-core/store/customer/authorization';
import { whenTruthy } from 'ish-core/utils/operators';
 
export function checkPermission(userPermissions: string[], permission: string | string[]): boolean {
  if (permission === 'always') {
    return true;
  } else if (permission === 'never') {
    return false;
  } else {
    // eslint-disable-next-line no-param-reassign
    permission = typeof permission === 'string' ? [permission] : typeof permission === 'undefined' ? [] : permission;
    return permission.some(id => userPermissions.includes(id));
  }
}
 
@Injectable({ providedIn: 'root' })
export class AuthorizationToggleService {
  private permissions$: Observable<string[]>;
 
  constructor(store: Store) {
    this.permissions$ = store.pipe(select(getUserPermissions));
  }
 
  isAuthorizedTo(permission: string | string[]): Observable<boolean> {
    // special case shortcut
    if (permission === 'always' || permission === 'never') {
      return of(checkPermission([], permission));
    }
    return this.permissions$.pipe(
      // wait for permissions to be loaded
      whenTruthy(),
      map(permissions => checkPermission(permissions, permission))
    );
  }
}