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

60 lines
1.7 KiB
TypeScript
Raw Normal View History

2020-01-31 10:24:45 +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';
@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): 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()) {
2020-04-01 14:11:44 +00:00
if(this.oauthService.getRefreshToken() != null ) {
this.oauthService.refreshToken().then(() => {
this.store.dispatch(new appCommonActions.InitUser());
return true;
}).catch(() => {
2020-01-31 10:24:45 +00:00
this.oauthService.initCodeFlow(url);
return false;
2020-04-01 14:11:44 +00:00
}
)
} else {
this.oauthService.initCodeFlow(url);
2020-01-31 10:24:45 +00:00
return false;
2020-04-01 14:11:44 +00:00
}
2020-01-31 10:24:45 +00:00
} else {
this.store.dispatch(new appCommonActions.InitUser());
return true;
}
}
}