All files / app/guards admin.guard.ts

100% Statements 31/31
100% Branches 16/16
100% Functions 1/1
100% Lines 31/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71                1x 16x 16x     16x 1x 1x       15x     15x     15x 14x 14x 4x 4x 2x     2x 1x               15x 13x 13x 13x 7x   6x 1x 5x 2x     6x 2x             15x 11x 11x     4x      
import { inject } from '@angular/core';
import { Router, CanActivateFn } from '@angular/router';
import { AuthService } from '../services/auth.service';
 
/**
 * Guard pour protéger les routes admin
 * Redirige vers la page d'accueil si l'utilisateur n'est pas authentifié ou n'est pas admin
 */
export const adminGuard: CanActivateFn = (route, state) => {
  const authService = inject(AuthService);
  const router = inject(Router);
 
  // Vérifier l'authentification
  if (!authService.isAuthenticated()) {
    router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
    return false;
  }
 
  // Forcer la mise à jour du statut admin depuis le token
  authService.refreshAdminStatus();
 
  // Vérifier le statut admin depuis plusieurs sources
  let isAdmin = authService.isAdmin();
  
  // Si le signal isAdmin est false, vérifier directement depuis le token
  if (!isAdmin) {
    const token = authService.getToken();
    if (token) {
      try {
        const payload = JSON.parse(atob(token.split('.')[1]));
        isAdmin = payload.role === 'ROLE_ADMIN';
        
        // Mettre à jour le signal si nécessaire
        if (isAdmin) {
          authService.isAdmin.set(true);
        }
      } catch (e) {
      }
    }
  }
 
  // Vérifier aussi depuis le localStorage (utilisateur stocké)
  if (!isAdmin) {
    try {
      const userStr = localStorage.getItem('currentUser');
      if (userStr && userStr !== 'undefined') {
        const currentUser = JSON.parse(userStr);
        let roleName: string | undefined;
        if (typeof currentUser.role === 'string') {
          roleName = currentUser.role;
        } else if (currentUser.role && typeof currentUser.role === 'object' && currentUser.role.name) {
          roleName = currentUser.role.name;
        }
        
        if (roleName === 'ROLE_ADMIN') {
          isAdmin = true;
        }
      }
    } catch (e) {
    }
  }
 
  if (!isAdmin) {
    router.navigate(['/']);
    return false;
  }
 
  return true;
};