Salud_UT/saludut-inpec/src/app/guards/auth-guard.ts
2025-12-16 19:33:09 -05:00

66 lines
1.6 KiB
TypeScript

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable, map, take } from 'rxjs';
import { AuthService } from '../services/auth';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(
private authService: AuthService,
private router: Router
) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> {
return this.authService.isAuthenticated$.pipe(
take(1),
map(isAuthenticated => {
if (isAuthenticated) {
return true;
} else {
// No está autenticado, redirigir al login
this.router.navigate(['/login'], {
queryParams: { returnUrl: state.url }
});
return false;
}
})
);
}
}
@Injectable({
providedIn: 'root'
})
export class AdminGuard implements CanActivate {
constructor(
private authService: AuthService,
private router: Router
) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> {
return this.authService.currentUser$.pipe(
take(1),
map(user => {
if (user && user.nombre_rol === 'administrador') {
return true;
} else {
// No es administrador, redirigir al dashboard con mensaje de error
this.router.navigate(['/dashboard'], {
queryParams: { error: 'no_admin' }
});
return false;
}
})
);
}
}