src/Subscriber/CheckCredentialListener.php line 30
<?php declare(strict_types=1);
namespace App\Subscriber;
use App\Exception\CompanyNotFoundException;
use App\Service\DataService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Core\Event\AuthenticationSuccessEvent;
class CheckCredentialListener implements EventSubscriberInterface
{
private RequestStack $requestStack;
private DataService $dataService;
public function __construct(RequestStack $requestStack, DataService $dataService)
{
$this->requestStack = $requestStack;
$this->dataService = $dataService;
}
public static function getSubscribedEvents(): array
{
return [
AuthenticationSuccessEvent::class => ['postCheckCredentials', 256]
];
}
public function postCheckCredentials(AuthenticationSuccessEvent $event): void
{
$request = $this->requestStack->getMainRequest();
if (str_contains($request?->attributes->get('_route') ?? '', 'admin')
|| str_contains($request?->attributes->get('_route') ?? '', 'Api')) {
return;
}
if (null === $request) {
throw new CompanyNotFoundException();
}
$company = $this->dataService->findCompanyByApiKey($request->get('_password'));
if (null === $company) {
throw new CompanyNotFoundException();
}
$request->getSession()->set(DataService::COMPANY_ID_SESSION_KEY, $company->getId());
}
}