2019-07-15 14:54:19 +00:00
|
|
|
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';
|
|
|
|
|
|
|
|
|
2019-11-05 16:19:33 +00:00
|
|
|
@Injectable({
|
|
|
|
providedIn: 'root',
|
|
|
|
})
|
2019-07-15 14:54:19 +00:00
|
|
|
export class AuthGuard implements CanActivate, CanLoad, CanActivateChild {
|
|
|
|
|
|
|
|
private loginDispatched = false;
|
|
|
|
private initialized = false;
|
|
|
|
constructor(private oauthService: OAuthService, private router: Router, private store: Store<appCommonReducer.State> ) { }
|
|
|
|
|
|
|
|
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
|
|
|
|
let url: string = state.url;
|
|
|
|
|
|
|
|
return this.checkLogin(url);
|
|
|
|
}
|
|
|
|
|
|
|
|
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
|
|
|
|
let url: string = state.url;
|
|
|
|
|
|
|
|
return this.checkLogin(url);
|
|
|
|
}
|
|
|
|
|
|
|
|
canLoad(route: Route): boolean {
|
|
|
|
return this.checkLogin(route.path);
|
|
|
|
}
|
|
|
|
|
|
|
|
checkLogin(url: string): boolean {
|
|
|
|
if (!this.oauthService.hasValidAccessToken()) {
|
|
|
|
if (!this.loginDispatched) {
|
|
|
|
this.oauthService.silentRefresh().then(info => {
|
|
|
|
this.router.navigateByUrl(url);
|
|
|
|
}).catch(error => {
|
|
|
|
this.loginDispatched = true;
|
|
|
|
this.store.dispatch(new appCommonActions.Login(url));
|
|
|
|
})
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
} else {
|
|
|
|
if (!this.initialized) {
|
|
|
|
this.initialized = true;
|
|
|
|
this.store.dispatch(new appCommonActions.InitUser());
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|