All files / src/app/core/guards authorization-toggle.guard.ts

93.75% Statements 15/16
100% Branches 1/1
66.66% Functions 2/3
93.75% Lines 15/16

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 3731x 31x 31x 31x   31x 31x         31x 8x 8x 8x   8x             8x 1x 1x             7x        
import { inject } from '@angular/core';
import { ActivatedRouteSnapshot, Router, UrlTree } from '@angular/router';
import { Observable, race, timer } from 'rxjs';
import { map } from 'rxjs/operators';
 
import { AuthorizationToggleService } from 'ish-core/utils/authorization-toggle/authorization-toggle.service';
import { HttpStatusCodeService } from 'ish-core/utils/http-status-code/http-status-code.service';
 
/**
 * Checks whether the user has the permission to enter the route and redirects to the error page in case of failure
 */
export function authorizationToggleGuard(route: ActivatedRouteSnapshot): Observable<boolean | UrlTree> {
  const authorizationToggleService = inject(AuthorizationToggleService);
  const router = inject(Router);
  const httpStatusCodeService = inject(HttpStatusCodeService);
 
  return race(
    // try to wait for permission loading and return appropriate result
    authorizationToggleService.isAuthorizedTo(route.data.permission),
    // timeout and forbid visiting page
    timer(4000).pipe(map(() => false))
  ).pipe(
    map(enabled => {
      if (!enabled) {
        httpStatusCodeService.setStatus(404, false);
        return router.createUrlTree(['/error'], {
          queryParams: {
            error: 'missing-permission',
            value: route.data.permission,
          },
        });
      }
      return true;
    })
  );
}