import { Injectable } from '@angular/core'; import { CanActivate, Router, CanLoad, Route, CanActivateChild , ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { Store } from '@ngrx/store'; import { OAuthService } from 'angular-oauth2-oidc'; import * as appCommonReducer from '../reducers/app-common.reducer' import * as appCommonActions from '../actions/app-common.actions'; @Injectable({ providedIn: 'root', }) export class AuthGuard implements CanActivate, CanLoad, CanActivateChild { constructor(private oauthService: OAuthService, private router: Router, private store: Store ) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise { let url: string = state.url; return this.checkLogin(url); } canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise { let url: string = state.url; return this.checkLogin(url); } canLoad(route: Route): Promise { return this.checkLogin(route.path); } checkLogin(url: string): Promise { return new Promise((resolve) => { if (!this.oauthService.hasValidAccessToken()) { console.debug("No valid token"); if(this.oauthService.getRefreshToken() != null ) { console.debug("We have a refresh token"); this.oauthService.refreshToken().then(() => { this.store.dispatch(new appCommonActions.InitUser()); resolve(true); }).catch(() => { console.debug("Error refreshing"); this.oauthService.initCodeFlow(url); resolve(false); }) } else { console.debug("No refresh token"); this.oauthService.initCodeFlow(url); resolve(false); } } else { console.debug("Valid token init user"); this.store.dispatch(new appCommonActions.InitUser()); return(true); } }); } }