src/Subscriber/CheckCredentialListener.php line 30

  1. <?php declare(strict_types=1);
  2. namespace App\Subscriber;
  3. use App\Exception\CompanyNotFoundException;
  4. use App\Service\DataService;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\RequestStack;
  7. use Symfony\Component\HttpFoundation\Session\Session;
  8. use Symfony\Component\Security\Core\Event\AuthenticationSuccessEvent;
  9. class CheckCredentialListener implements EventSubscriberInterface
  10. {
  11.     private RequestStack $requestStack;
  12.     private DataService $dataService;
  13.     public function __construct(RequestStack $requestStackDataService $dataService)
  14.     {
  15.         $this->requestStack $requestStack;
  16.         $this->dataService $dataService;
  17.     }
  18.     public static function getSubscribedEvents(): array
  19.     {
  20.         return [
  21.             AuthenticationSuccessEvent::class => ['postCheckCredentials'256]
  22.         ];
  23.     }
  24.     public function postCheckCredentials(AuthenticationSuccessEvent $event): void
  25.     {
  26.         $request $this->requestStack->getMainRequest();
  27.         if (str_contains($request?->attributes->get('_route') ?? '''admin')
  28.         || str_contains($request?->attributes->get('_route') ?? '''Api')) {
  29.             return;
  30.         }
  31.         if (null === $request) {
  32.             throw new CompanyNotFoundException();
  33.         }
  34.         $company $this->dataService->findCompanyByApiKey($request->get('_password'));
  35.         if (null === $company) {
  36.             throw new CompanyNotFoundException();
  37.         }
  38.         $request->getSession()->set(DataService::COMPANY_ID_SESSION_KEY$company->getId());
  39.     }
  40. }