<?php
namespace App\EventSubscriber;
use App\Entity\Document;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class ResellerDocumentAccessSubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly TokenStorageInterface $tokenStorage,
private readonly RouterInterface $router
) {
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
public function onKernelController(ControllerEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
$user = $this->tokenStorage->getToken()?->getUser();
if (
!$user instanceof User
|| !in_array('ROLE_RESELLER', $user->getRoles(), true)
|| in_array('ROLE_SUPER_ADMIN', $user->getRoles(), true)
) {
return;
}
$request = $event->getRequest();
foreach ($request->attributes->all() as $attribute) {
if (!$attribute instanceof Document) {
continue;
}
$resellerUser = $attribute->getResellerUser();
if ($resellerUser instanceof User && $resellerUser->getId() === $user->getId()) {
continue;
}
if (!$request->hasSession()) {
$event->setController(fn () => new RedirectResponse($this->router->generate('index')));
return;
}
$request->getSession()->getFlashBag()->add('danger', 'Acces interdit a ce document.');
$event->setController(fn () => new RedirectResponse($this->router->generate('index')));
return;
}
}
}