FarmMapsLib/projects/common/src/fm/services/auth-guard.service.ts
Peter Bastiani fd3545523e
All checks were successful
FarmMaps.Develop/FarmMapsLib/develop This commit looks good
Remove annoying 'debugger' statement.
2020-02-03 10:32:15 +01:00

67 lines
2.0 KiB
TypeScript

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