<?php
namespace Roothirsch\DamBundle\Filter;
use ApiPlatform\Core\EventListener\EventPriorities;
use Roothirsch\CoreBundle\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use TYPO3\CMS\Extbase\Object\ObjectManagerInterface;
class FileAccessUserInjection implements EventSubscriberInterface
{
/**
* @var ObjectManager
*/
protected $entityManager;
/**
* @var RouterInterface
*/
private $router;
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
public function __construct(
EntityManagerInterface $entityManager,
RouterInterface $router,
TokenStorageInterface $tokenStorage
) {
$this->entityManager = $entityManager;
$this->router = $router;
$this->tokenStorage = $tokenStorage;
}
/**
* Returns an array of event names this subscriber wants to listen to.
*
* The array keys are event names and the value can be:
*
* * The method name to call (priority defaults to 0)
* * An array composed of the method name to call and the priority
* * An array of arrays composed of the method names to call and respective
* priorities, or 0 if unset
*
* For instance:
*
* * array('eventName' => 'methodName')
* * array('eventName' => array('methodName', $priority))
* * array('eventName' => array(array('methodName1', $priority), array('methodName2')))
*
* @return array The event names to listen to
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['onKernelRequest', EventPriorities::PRE_READ],
];
}
public function onKernelRequest(\Symfony\Component\HttpKernel\Event\RequestEvent $event)
{
if ($this->router->getContext()->getPathInfo() === '/login') {
return;
}
/** Blocking this filter on any request that is performing a persistent action */
if(in_array($event->getRequest()->getMethod(), ["PUT", "POST", "DELETE"] )){
return;
}
$filter = $this->entityManager->getFilters()->enable('file_access_filter');
if ($this->tokenStorage->getToken() && $this->tokenStorage->getToken()->getUser() instanceof User) {
$filter->setUser($this->tokenStorage->getToken()->getUser());
}
}
}