fix 401 loop hell
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map, catchError } from 'rxjs/operators';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { AuthService } from '../../shared/services/auth.service';
|
||||
|
||||
@Injectable({
|
||||
@@ -14,19 +14,19 @@ export class AuthGuard implements CanActivate {
|
||||
) { }
|
||||
|
||||
canActivate(
|
||||
route: ActivatedRouteSnapshot,
|
||||
_route: ActivatedRouteSnapshot,
|
||||
state: RouterStateSnapshot
|
||||
): Observable<boolean> | Promise<boolean> | boolean {
|
||||
// Check if user is authenticated
|
||||
if (this.authService.isAuthenticated()) {
|
||||
return true;
|
||||
}
|
||||
return this.authService.whenSessionReady().pipe(
|
||||
map(() => {
|
||||
if (this.authService.isAuthenticated()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Store the attempted URL for redirecting after login
|
||||
this.authService.setRedirectUrl(state.url);
|
||||
|
||||
// Redirect to login page
|
||||
this.router.navigate(['/login']);
|
||||
return false;
|
||||
this.authService.setRedirectUrl(state.url);
|
||||
this.router.navigate(['/login']);
|
||||
return false;
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { CanActivate, ActivatedRouteSnapshot, Router } from '@angular/router';
|
||||
import { AuthService } from '../../shared/services/auth.service';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class RoleGuard implements CanActivate {
|
||||
constructor(
|
||||
private authService: AuthService,
|
||||
private router: Router
|
||||
) { }
|
||||
|
||||
canActivate(route: ActivatedRouteSnapshot): boolean {
|
||||
const requiredRoles = route.data['roles'] as string[] | undefined;
|
||||
if (!requiredRoles?.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const user = this.authService.getCurrentUser();
|
||||
const allowed = user?.roles?.some(r => requiredRoles.includes(r)) ?? false;
|
||||
|
||||
if (!allowed) {
|
||||
this.router.navigate(['/user-portal/dashboard']);
|
||||
}
|
||||
|
||||
return allowed;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user