import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; import { BusService } from '@creedinteractive/onguard-ng-services'; import { LaunchpadWebConfiguration } from '@creedinteractive/onguard-models'; import { AuthenticationService } from '../services/authentication/authentication.service'; import { LaunchpadWebConfigurationService } from '../launchpad-web-configuration.service'; import { LaunchpadEventsService } from '../services/launchpad-events/launchpad-events.service'; @Injectable({ providedIn: 'root', }) export class LaunchpadLoginGuard implements CanActivate { private config: LaunchpadWebConfiguration; constructor( private authenticationService: AuthenticationService, private bus: BusService, private events: LaunchpadEventsService, private launchpadService: LaunchpadWebConfigurationService, private router: Router, ) { if (typeof launchpadService?.config === 'undefined') { throw new Error('Missing configuration options'); } this.config = launchpadService.config; } canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { console.log(`Login Guard. jwt=${this.authenticationService.jwt} state.url=${state.url}`); if (this.authenticationService.jwt && !next.queryParams.sso_origin) { console.log(`Login Guard. Prevent activation of route '${state.url}'`); this.router.navigate(['/']); return false; } else if (!this.authenticationService.jwt && next.queryParams.sso_token) { console.log('Login Guard. Request Login from Inventory Asset API / LaunchPad'); this.bus.publish(this.events.user.sso_auth.requested, next.queryParams.sso_token); return false; } else { console.log(`Login Guard. Activate route '${state.url}'`); const redirectLocation = state.url !== '/login' ? state.url : ''; window.location.href = `${this.config.ssoUrl + this.config.ssoLoginRoute}?sso_origin=${ this.config.appSsoIdentity }&redirect=${encodeURI(redirectLocation)}`; return false; } } }