<?php
namespace Labas\EventListener;
use App\Entity\Central\Client\Client;
use App\Entity\Central\User\User;
use App\Service\AppManager;
use App\Utils\ClientUtils;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class ContextListener
{
private TokenStorageInterface $tokenStorage;
private RouterInterface $router;
private FlashBagInterface $flashBag;
private AppManager $appManager;
public function __construct(AppManager $appManager, TokenStorageInterface $tokenStorage, RouterInterface $router, FlashBagInterface $flashBag)
{
$this->tokenStorage = $tokenStorage;
$this->router = $router;
$this->flashBag = $flashBag;
$this->appManager = $appManager;
}
public function setClient(RequestEvent $requestEvent)
{
$token = $this->tokenStorage->getToken();
$user = $token !== null ? $token->getUser() : null;
$client = $user instanceof User ? $user->getClient() : null;
$clientCode = ClientUtils::LABAS;
if ($client instanceof Client) {
foreach($user->getRoles() as $roles){
if ($roles === 'ROLE_LABAS') {
$client->setCode($clientCode);
}
}
}
if ($client instanceof Client && $client->getCode() !== $clientCode) {
$response = new RedirectResponse($this->router->generate('labas_logout'));
$requestEvent->setResponse($response);
$requestEvent->stopPropagation();
$this->flashBag->add('ERROR', 'ui.permission_denied');
} else {
$this->appManager->findAndSetClient('code', $clientCode);
// $this->appManager->findAndSetClient('code', 'testflight');
}
}
}