src/EventSubscriber/File/FileReadSubscriber.php line 29

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\File;
  3. use App\Entity\File\OSFile;
  4. use App\Security\Voter\OSFileAccessVoter;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\HttpKernel\UriSigner;
  10. use Symfony\Component\Security\Core\Security;
  11. class FileReadSubscriber implements EventSubscriberInterface
  12. {
  13.     public function __construct(private UriSigner $uriSigner, private Security $security, private EntityManagerInterface $manager){}
  14.     public static function getSubscribedEvents(): array
  15.     {
  16.         return [
  17.             KernelEvents::REQUEST => 'onKernelRequest',
  18.         ];
  19.     }
  20.     /**
  21.      * @throws InvalideFileSignatureException
  22.      * @throws FileAccessNotGrantedException
  23.      */
  24.     public function onKernelRequest(RequestEvent $event): void
  25.     {
  26.         $request $event->getRequest();
  27.         if (!$event->isMainRequest() ) {
  28.             return;
  29.         }
  30.         $secureRoute= ["file-read""file-download"];
  31.         if (!in_array($request->get('_route'), $secureRoutetrue)) {
  32.             return;
  33.         }
  34.         if ($request->get('_hash') && !$this->uriSigner->checkRequest($request)) {
  35.             throw new InvalideFileSignatureException($request);
  36.         }
  37.         $doc$this->manager->getRepository(OSFile::class)->find($request->get('id'));
  38.         if(!$this->security->isGranted(OSFileAccessVoter::DOWNLOAD$doc)){
  39.             throw new FileAccessNotGrantedException($request$docOSFileAccessVoter::DOWNLOAD);
  40.         }
  41.     }
  42. }