<?php
declare(strict_types=1);
namespace App\Bundles\OrganizationBundle\EventListener;
use App\Bundles\OrganizationBundle\Service\UserOrganization\UserOrganizationBinder;
use App\Bundles\OrganizationBundle\Service\UserOrganization\UserOrganizationProvider;
use App\Bundles\UserBundle\Service\User\UserLogoutService;
use App\Platform\Service\SessionProvider;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
#[AsEventListener(event: RequestEvent::class, method: 'onKernelRequest', priority: -254)]
class CheckUserOrganizationInSessionListener
{
public function __construct(
private readonly SessionProvider $sessionProvider,
private readonly UserOrganizationProvider $provider,
private readonly TokenStorageInterface $tokenStorage,
private readonly UserLogoutService $userLogoutService,
) {
}
public function onKernelRequest(RequestEvent $event): void
{
$session = $this->sessionProvider->provide();
if (!$session->has(UserOrganizationBinder::SESSION_USER_ORGANIZATION_KEY)) {
return;
}
if (!$token = $this->tokenStorage->getToken()) {
return;
}
if (!$this->provider->provideUserOrganizationBySession($session)) {
$this->logoutAndRedirectUser($event, $token, $session);
}
}
private function logoutAndRedirectUser(RequestEvent $event, TokenInterface $token, SessionInterface $session): void
{
$this->userLogoutService->logout($event->getRequest(), $token, $session);
$event->setResponse(new RedirectResponse('/login'));
}
}