src/Security/Voter/StudentVoter.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
  4. use App\Entity\Student;
  5. use App\Entity\User;
  6. use App\Repository\StudentRepository;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. use Symfony\Component\Security\Core\Security;
  10. use Symfony\Component\Security\Core\User\UserInterface;
  11. class StudentVoter extends Voter
  12. {
  13.     public const VIEW 'VIEW_STUDENT';
  14.     public const VIEW_SETTINGS 'VIEW_STUDENT_SETTINGS';
  15.     public const VIEW_MOBILITIES 'VIEW_STUDENT_SETTINGS';
  16.     public const EDIT_SETTINGS 'EDIT_STUDENT_SETTINGS';
  17.     private Security $security;
  18.     private StudentRepository $studentRepository;
  19.     public function __construct(
  20.         Security $security,
  21.         StudentRepository $studentRepository
  22.     ) {
  23.         $this->security $security;
  24.         $this->studentRepository $studentRepository;
  25.     }
  26.     protected function supports(string $attributemixed $subject): bool
  27.     {
  28.         return in_array($attribute, [
  29.                 self::VIEW,
  30.                 self::VIEW_SETTINGS,
  31.                 self::EDIT_SETTINGS,
  32.                 self::VIEW_MOBILITIES,
  33.             ])
  34.             && ($subject instanceof Paginator
  35.                 || $subject instanceof Student)
  36.         ;
  37.     }
  38.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  39.     {
  40.         /**
  41.          * @var User $user
  42.          */
  43.         $user $token->getUser();
  44.         // if the user is anonymous, do not grant access
  45.         if (!$user instanceof UserInterface) {
  46.             return false;
  47.         }
  48.         if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
  49.             return true;
  50.         }
  51.         $userStudent $user->getStudent();
  52.         // TODO this should just be temporary until Api Platform allows security check on the owning side
  53.         if ($subject instanceof Paginator) {
  54.             $query $subject
  55.                 ->getQuery()
  56.             ;
  57.             $queryParameters $query->getParameters();
  58.             $id $queryParameters[0]
  59.                 ->getValue()
  60.             ;
  61.             $student $this->studentRepository->find($id);
  62.         } else {
  63.             $student $subject;
  64.         }
  65.         return match ($attribute) {
  66.             self::EDIT_SETTINGSself::VIEW_SETTINGSself::VIEWself::VIEW_MOBILITIES => $userStudent && $userStudent->getId() === $student->getId(),
  67.             default => false,
  68.         };
  69.     }
  70. }