<?php
declare(strict_types=1);
namespace App\EventListener;
use App\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Event\AuthenticationSuccessEvent;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface;
class BlockedOrganizationListener
{
/**
* @var Security
*/
private $security;
/**
* @var UrlGeneratorInterface
*/
private $router;
/**
* @param Security $security
* @param UrlGeneratorInterface $router
*/
public function __construct(Security $security, UrlGeneratorInterface $router)
{
$this->router = $router;
$this->security = $security;
}
/**
* @param RequestEvent $event
*/
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
if (\in_array($request->get('_route'), ['profile_organization_blocked', 'user_logout'])) {
return;
}
if (!$event->isMasterRequest()
|| (null === $this->security->getToken())
|| ($this->security->getToken() instanceof AnonymousToken)
|| !($this->security->getUser() instanceof User)) {
// don't do anything if it's not the master request
return;
}
/** @var User $user */
$user = $this->security->getUser();
if (($user->getOrganization() && $user->getOrganization()->isActive())
|| ($user->isSystemUser())) {
// don't do anything if users organization is active
return;
}
$response = new RedirectResponse($this->router->generate('profile_organization_blocked'));
$event->setResponse($response);
}
}