src/Security/Voter/UtilisateurVoter.php line 20

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * Copyright (C) Office National de Publication et de Communication - All Rights Reserved
  5.  *
  6.  * Unauthorized copying of this file, via any medium is strictly prohibited by law
  7.  * This file is proprietary and confidential
  8.  */
  9. namespace App\Security\Voter;
  10. use App\Entity\Utilisateur;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  13. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  14. use Symfony\Component\Security\Core\Security;
  15. final class UtilisateurVoter extends Voter
  16. {
  17.     public const IMPERSONATE 'impersonate';
  18.     /**
  19.      * @var Security
  20.      */
  21.     private $security;
  22.     /**
  23.      * @var EntityManagerInterface
  24.      */
  25.     private $entityManager;
  26.     public function __construct(Security $securityEntityManagerInterface $entityManager)
  27.     {
  28.         $this->security $security;
  29.         $this->entityManager $entityManager;
  30.     }
  31.     protected function supports($attribute$subject): bool
  32.     {
  33.         return
  34.             self::IMPERSONATE === $attribute &&
  35.             $subject instanceof Utilisateur;
  36.     }
  37.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  38.     {
  39.         if (self::IMPERSONATE !== $attribute) {
  40.             return false;
  41.         }
  42.         // D'abbord, il faut avoir le role ROLE_ALLOWED_TO_SWITCH
  43.         if (!$this->security->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
  44.             return false;
  45.         }
  46.         // Admin peut se passe pour n'importe qui
  47.         // if ($this->security->isGranted(['ROLE_ADMIN', 'ROLE_REDACTEUR'])) {
  48.             if ($this->security->isGranted('ROLE_ADMIN') || $this->security->isGranted('ROLE_REDACTEUR')) {
  49.                 return true;
  50.         }
  51.         // Délégue peut se passer par ses établissements
  52.         if ($this->security->isGranted('ROLE_DELEGUE') && $subject->hasRole('ROLE_RESPONSABLE_ETABLISSEMENT')) {
  53.             $repository $this->entityManager->getRepository(Utilisateur::class);
  54.             $user $token->getUser();
  55.             $etabs $subject->getEtablissementsResponsable();
  56.             foreach ($etabs as $etab) {
  57.                 if ($repository->isDelegueOf($user$etab)) {
  58.                     return true;
  59.                 }
  60.             }
  61.         }
  62.         return false;
  63.     }
  64. }