fix 401 loop hell

This commit is contained in:
Chris Chen
2026-05-27 15:09:05 -07:00
parent e83fa4c2e9
commit d79b1faa8f
13 changed files with 196 additions and 90 deletions
+13 -13
View File
@@ -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;
})
);
}
}
+27
View File
@@ -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;
}
}