FarmMapsLib/projects/common/src/fm/services/auth-guard.service.ts

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 {
constructor(private oauthService: OAuthService, private router: Router, private store: Store<appCommonReducer.State> ) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
let url: string = state.url;
return this.checkLogin(url);
}
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
let url: string = state.url;
return this.checkLogin(url);
}
canLoad(route: Route): Promise<boolean> {
return this.checkLogin(route.path);
}
checkLogin(url: string): Promise<boolean> {
return new Promise<boolean>((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);
}
});
}
}