<?php
namespace App\EventListener;
use App\Entity\Project;
use App\Repository\ProjectRepository;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTDecodeFailureException;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class JwtCreatedListener
{
private RequestStack $requestStack;
private ProjectRepository $projectRepository;
private TokenStorageInterface $tokenStorage;
private JWTTokenManagerInterface $JWTTokenManager;
public function __construct(
RequestStack $requestStack,
ProjectRepository $projectRepository,
TokenStorageInterface $tokenStorage,
JWTTokenManagerInterface $JWTTokenManager,
) {
$this->requestStack = $requestStack;
$this->projectRepository = $projectRepository;
$this->tokenStorage = $tokenStorage;
$this->JWTTokenManager = $JWTTokenManager;
}
public function onJWTCreated(JWTCreatedEvent $event): void
{
$data = $event->getData();
$user = $event->getUser();
if (!$user instanceof UserInterface) {
return;
}
$requestData = json_decode($this->requestStack->getCurrentRequest()->getContent());
if (empty($requestData->projectId)) {
return;
}
$project = $this->getCurrentProject();
if ($project instanceof Project) {
$data['hasCatalog'] = $project->isCatalogAllowed();
$data['lastCatalogUpdate'] = $project->getLastUpdated()->format('Y-m-d H:i:s');
$data['lastUpdateDelayAlert'] = $project->getLastUpdateAlert();
$data['competitorsCompany'] = $project->getCompetitors();
$data['projectId'] = $project->getId();
}
$event->setData($data);
}
/**
* @throws JWTDecodeFailureException
*/
private function getCurrentProject(): ?Project
{
$rawData = $this->requestStack->getCurrentRequest()->getContent();
if (null != $rawData) {
$data = json_decode($rawData);
if (!isset($data->projectId)) {
return null;
}
$projectId = $data->projectId;
} else {
$token = $this->tokenStorage->getToken();
$user = $token?->getUser();
if ($user) {
$datas = $this->JWTTokenManager->decode($token);
$projectId = $datas['projectId'];
}
}
if (empty($projectId)) {
return null;
}
$project = $this->projectRepository->find($projectId);
if (!$project) {
return null;
}
return $project;
}
}