src/EventSubscriber/ResellerDocumentAccessSubscriber.php line 29

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Document;
  4. use App\Entity\User;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\Routing\RouterInterface;
  10. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  11. class ResellerDocumentAccessSubscriber implements EventSubscriberInterface
  12. {
  13.     public function __construct(
  14.         private readonly TokenStorageInterface $tokenStorage,
  15.         private readonly RouterInterface $router
  16.     ) {
  17.     }
  18.     public static function getSubscribedEvents(): array
  19.     {
  20.         return [
  21.             KernelEvents::CONTROLLER => 'onKernelController',
  22.         ];
  23.     }
  24.     public function onKernelController(ControllerEvent $event): void
  25.     {
  26.         if (!$event->isMainRequest()) {
  27.             return;
  28.         }
  29.         $user $this->tokenStorage->getToken()?->getUser();
  30.         if (
  31.             !$user instanceof User
  32.             || !in_array('ROLE_RESELLER'$user->getRoles(), true)
  33.             || in_array('ROLE_SUPER_ADMIN'$user->getRoles(), true)
  34.         ) {
  35.             return;
  36.         }
  37.         $request $event->getRequest();
  38.         foreach ($request->attributes->all() as $attribute) {
  39.             if (!$attribute instanceof Document) {
  40.                 continue;
  41.             }
  42.             $resellerUser $attribute->getResellerUser();
  43.             if ($resellerUser instanceof User && $resellerUser->getId() === $user->getId()) {
  44.                 continue;
  45.             }
  46.             if (!$request->hasSession()) {
  47.                 $event->setController(fn () => new RedirectResponse($this->router->generate('index')));
  48.                 return;
  49.             }
  50.             $request->getSession()->getFlashBag()->add('danger''Acces interdit a ce document.');
  51.             $event->setController(fn () => new RedirectResponse($this->router->generate('index')));
  52.             return;
  53.         }
  54.     }
  55. }