Primo rilascio
This commit is contained in:
24
frontend/nursery-app/src/app/guards/auth.guard.ts
Normal file
24
frontend/nursery-app/src/app/guards/auth.guard.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { AuthService } from '../services/auth.service'; // Importa AuthService
|
||||
import { map, take } from 'rxjs/operators';
|
||||
|
||||
export const authGuard: CanActivateFn = (route, state) => {
|
||||
const authService = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
|
||||
// Usa l'observable isAuthenticated$ per verificare lo stato
|
||||
return authService.isAuthenticated$.pipe(
|
||||
take(1), // Prende solo il valore corrente e completa
|
||||
map(isAuthenticated => {
|
||||
if (isAuthenticated) {
|
||||
return true; // Utente autenticato, permette accesso
|
||||
} else {
|
||||
// Utente non autenticato, reindirizza al login
|
||||
console.log('AuthGuard: User not authenticated, redirecting to login.');
|
||||
router.navigate(['/login']);
|
||||
return false; // Blocca accesso alla rotta
|
||||
}
|
||||
})
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user