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()) { if(this.oauthService.getRefreshToken() != null ) { this.oauthService.refreshToken().then(() => { this.store.dispatch(new appCommonActions.InitUser()); resolve(true); }).catch(() => { resolve(false); this.oauthService.initCodeFlow(url); }) } else { resolve(false); this.oauthService.initCodeFlow(url); } } else { this.store.dispatch(new appCommonActions.InitUser()); return(true); } }); } }