Home > OS >  Symfony 5 Doctrine - Add a Filter to every request, based on current user
Symfony 5 Doctrine - Add a Filter to every request, based on current user

Time:12-23

I'm trying to dynamically set a "tenant_id" filter on some actions of my Controllers.

I've built a class which extends SQLFilter and put inside addFilterConstraint the logic to do that.

The problem is the dynamic "tenant" parameter:

If I put this piece of code inside each of my Controllers actions it works:

$em->getFilters()->getFilter('tenant')->setParameter('tenant_id', $security->getUser()->getTenant()->getId());

Of course this is not maintainable so I'm trying to move this logic somewhere else to make it cleaner and easier to maintain.

I'm thinking to something like an Event, but I would need to dispatch an Event on every Request, when the Security has already done it's job and then I'd need to modify the EntityManager.

Any idea?

Thanks

CodePudding user response:

You are looking for an event subscriber (Ref)

Here is an example you can use showing access to the entity manager and security classes. place this file in src/EventSubscriber/TenantFilterEventSubscriber.php this will then run on every request.

namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\Security\Core\Security;
use Doctrine\ORM\EntityManagerInterface;

class TenantFilterEventSubscriber implements EventSubscriberInterface
{
    protected $security;

    public function __construct(Security $security, EntityManagerInterface $entityManager)
    {
        $this->security = $security;
        $this->entityManager = $entityManager;
    }

    public function onKernelController(ControllerEvent $event)
    {
        $controller = $event->getController();

        if (!is_array($controller)) return;

        if ($controller[0] instanceof YourController) {
            $user = $this->security->getUser();

            if (null !== $user) {
                // Do stuff
            }
        }
    }

    public static function getSubscribedEvents()
    {
        return array(
            'kernel.controller' => 'onKernelController',
        );
    }
}
  • Related