import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, } from '@angular/router'; import { filter, map, take, tap, switchMap } from 'rxjs/operators'; import { Observable } from 'rxjs'; import { environment } from 'projects/core/src//environment'; import { MwAppConfigService } from 'projects/core/src//config'; import { MwAuthService } from '../auth.service'; import { MwUserService } from '../user.service'; @Injectable() export class MwAuthGuard implements CanActivate { private isDebug = false; constructor( private readonly userService: MwUserService, private readonly configService: MwAppConfigService, private readonly authService: MwAuthService ) { this.configService .getConfig() .pipe(take(1)) .subscribe((config) => (this.isDebug = config.debug === true)); } canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable | boolean { if ( environment.skipAuthRoutes.some((skipRoute) => state.url.includes(skipRoute) ) ) { return true; } let result = this.authService.loggedIn$.pipe( tap((isLoggedIn) => { if (!isLoggedIn) { this.authService.authorize(state.url); } }), switchMap(() => this.userService.userProfile$), map((profile) => !!profile) ); result = result.pipe( tap((canAccess) => { this.log( `${canAccess ? 'Allow access page' : 'Page access restricted'}` ); }), filter((canAccess) => canAccess) ); return result; } private log(message: string): void { if (this.isDebug) { // tslint:disable-next-line:no-console console.debug(`MwAuthGuard: ${message}`); } } }