src/EventSubscriber/AdminCompanyImpersonationSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Company;
  4. use App\Security\UserSecurityHelper;
  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\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
  10. class AdminCompanyImpersonationSubscriber implements EventSubscriberInterface
  11. {
  12. private const string HEADER_NAME = 'X-Company-Id';
  13. public function __construct(
  14. private readonly UserSecurityHelper $securityHelper,
  15. private readonly EntityManagerInterface $entityManager
  16. ) {
  17. }
  18. public static function getSubscribedEvents(): array
  19. {
  20. return [
  21. KernelEvents::REQUEST => ['onKernelRequest', 7], // Execute before security checks
  22. ];
  23. }
  24. public function onKernelRequest(RequestEvent $event): void
  25. {
  26. if (!$event->isMainRequest()) {
  27. return;
  28. }
  29. try {
  30. if (!$this->securityHelper->isGranted('ROLE_ADMIN')) {
  31. return;
  32. }
  33. $request = $event->getRequest();
  34. $galabCustomerId = $request->headers->get(self::HEADER_NAME);
  35. if (!$galabCustomerId) {
  36. return;
  37. }
  38. $company = $this->entityManager->getRepository(Company::class)
  39. ->findOneBy(['galabCustomerId' => $galabCustomerId]);
  40. if (!$company) {
  41. return;
  42. }
  43. // Store the impersonated company in the request attributes
  44. $request->attributes->set('impersonated_company', $company);
  45. } catch (AuthenticationCredentialsNotFoundException) {
  46. }
  47. }
  48. }