allerta-vvf/frontend/src/app/_guards/authorize.guard.ts

41 lines
1.2 KiB
TypeScript
Raw Normal View History

2021-12-24 15:21:22 +01:00
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from '../_services/auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthorizeGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {
}
2023-02-23 00:25:23 +01:00
checkAuthAndRedirect(
2021-12-24 15:21:22 +01:00
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
2023-02-23 00:25:23 +01:00
): boolean {
2021-12-24 15:21:22 +01:00
console.log(this.authService, route, state);
2023-06-06 18:53:49 +02:00
if(this.authService.profile.id === undefined) {
2021-12-24 15:21:22 +01:00
console.log("not logged in");
this.router.navigate(['login', state.url.replace('/', '')]);
return false;
} else {
return true;
}
}
2023-02-23 00:25:23 +01:00
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if(this.authService.authLoaded) {
return this.checkAuthAndRedirect(route, state);
} else {
return new Observable<boolean>((observer) => {
this.authService.authChanged.subscribe({
next: () => { observer.next(this.checkAuthAndRedirect(route, state)); }
})
});
}
}
2021-12-24 15:21:22 +01:00
}