import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, CanLoad, Route, UrlSegment, Router, } from '@angular/router'; import { map, take, switchMap, filter } from 'rxjs/operators'; import { Observable, of } from 'rxjs'; import { environment } from 'projects/core/src//environment'; import { OIDCEffects } from '../../@store/oidc.effects'; import { MwUserService } from '../user.service'; import { MwAuthService } from '../auth.service'; import { MwCorePreferenceService } from '../preference.service'; @Injectable() export class MwCompanyGuard implements CanActivate, CanLoad { private hasAccess$ = this.userService.userProfile$.pipe( filter((profile) => !!profile), map((profile) => { const hasAccess = profile?.hasAccessToModule === true && profile?.companyHasAccessToModule === true; if (!hasAccess && MwCompanyGuard.isCompanyProtectedRoute()) { this.router.navigate(['no-access']); } return hasAccess; }), take(1) ); private isActiveCompany$ = this.authService.activeCompany$ .pipe( switchMap((activeCompany) => activeCompany?.companyId && activeCompany.companyId > 0 ? this.preferenceService.preference$ : of(false) ), take(1) ) .pipe( map((activeCompany) => { if (!activeCompany && MwCompanyGuard.isCompanyProtectedRoute()) { this.router.navigate(['unauthorized', 'for-company']); return false; } return true; }) ); static isCompanyProtectedRoute(): boolean { let isProtected = true; const storedRoute = OIDCEffects.getStoredRedirectRoute(); if (storedRoute) { isProtected = !environment.skipCompanyProtectionRoutes?.some( (skipRoute) => storedRoute.includes(skipRoute) ); } return isProtected; } constructor( private readonly authService: MwAuthService, private readonly userService: MwUserService, private readonly preferenceService: MwCorePreferenceService, private readonly router: Router ) {} canLoad(route: Route, segments: UrlSegment[]): Observable { return this.isActiveCompany$.pipe( filter((result) => result), switchMap(() => this.hasAccess$) ); } canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable { return this.isActiveCompany$.pipe( filter((result) => result), switchMap(() => this.hasAccess$) ); } }