2019-01-18 18:03:45 +01:00
|
|
|
import { Injectable } from '@angular/core';
|
|
|
|
import { ActivatedRouteSnapshot, CanActivate, CanLoad, Route, Router, RouterStateSnapshot } from '@angular/router';
|
2023-10-17 16:13:34 +02:00
|
|
|
import { AuthService, ResolutionContext } from './services/auth/auth.service';
|
2023-10-11 16:53:12 +02:00
|
|
|
import { from, Observable, of as observableOf } from 'rxjs';
|
|
|
|
import { catchError, map, tap } from 'rxjs/operators';
|
2019-01-18 18:03:45 +01:00
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class AuthGuard implements CanActivate, CanLoad {
|
2023-10-11 16:53:12 +02:00
|
|
|
constructor(private authService: AuthService, private router: Router) {
|
2019-01-18 18:03:45 +01:00
|
|
|
}
|
|
|
|
|
2023-10-11 16:53:12 +02:00
|
|
|
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
|
2019-01-18 18:03:45 +01:00
|
|
|
const url: string = state.url;
|
2023-10-17 16:13:34 +02:00
|
|
|
const authContext = route.data ? route.data['authContext'] as ResolutionContext : null;
|
|
|
|
return this.applyGuard(url, authContext);
|
2019-01-18 18:03:45 +01:00
|
|
|
}
|
|
|
|
|
2023-10-11 16:53:12 +02:00
|
|
|
canLoad(route: Route): Observable<boolean> {
|
2019-01-18 18:03:45 +01:00
|
|
|
const url = `/${route.path}`;
|
2023-10-17 16:13:34 +02:00
|
|
|
const authContext = route.data ? route.data['authContext'] as ResolutionContext : null;
|
|
|
|
return this.applyGuard(url, authContext);
|
2023-10-11 16:53:12 +02:00
|
|
|
}
|
|
|
|
|
2023-10-17 16:13:34 +02:00
|
|
|
private applyGuard(url: string, authContext: ResolutionContext) {
|
|
|
|
return this.checkLogin(url, authContext).pipe(tap(loggedIn => {
|
2023-10-11 16:53:12 +02:00
|
|
|
if (!loggedIn) {
|
|
|
|
this.router.navigate(['/unauthorized'], { queryParams: { returnUrl: url } });
|
2023-10-17 16:13:34 +02:00
|
|
|
} else {
|
|
|
|
const authorized = this.authService.hasAccessToken() && this.authService.authorize(authContext);
|
|
|
|
if(!authorized){
|
|
|
|
this.router.navigate(['/unauthorized']);
|
|
|
|
}else{
|
|
|
|
return authorized;
|
|
|
|
}
|
2023-10-11 16:53:12 +02:00
|
|
|
}
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
2023-10-17 16:13:34 +02:00
|
|
|
private checkLogin(url: string, authContext: ResolutionContext): Observable<boolean> {
|
2023-10-11 16:53:12 +02:00
|
|
|
if (!this.authService.isLoggedIn()) { return observableOf(false); }
|
|
|
|
|
|
|
|
return this.authService.hasAccessToken()
|
|
|
|
? observableOf(true)
|
|
|
|
: from(this.authService.refreshToken()).pipe(
|
|
|
|
catchError(x => observableOf(false)));
|
2019-01-18 18:03:45 +01:00
|
|
|
}
|
|
|
|
}
|