<?php
namespace App\EventListener;
use App\Entity\AbstractCollaborator;
use App\Entity\Agent;
use App\Entity\Cgu;
use App\Message\ConnexionLogsMessage;
use App\Services\CurrencyService;
use Doctrine\ORM\EntityManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class AuthenticationSuccessListener
{
private EntityManagerInterface $manager;
private CurrencyService $currencyService;
private TranslatorInterface $translator;
private MessageBusInterface $bus;
private RequestStack $requestStack;
public function __construct(
EntityManagerInterface $manager,
CurrencyService $currencyService,
TranslatorInterface $translator,
MessageBusInterface $bus,
RequestStack $requestStack
) {
$this->manager = $manager;
$this->currencyService = $currencyService;
$this->translator = $translator;
$this->requestStack = $requestStack;
$this->bus = $bus;
}
public function onAuthenticationSuccessResponse(AuthenticationSuccessEvent $event): void
{
$data = $event->getData();
$qualification = null;
$manager = null;
$collaborator = $event->getUser();
if (!$collaborator instanceof AbstractCollaborator) {
return;
}
if ($collaborator instanceof Agent) {
$qualification = $collaborator->getQualificationLevel()->getLabel();
$manager = [
'firstName' => $collaborator->getManager()->getFirstName(),
'lastName' => $collaborator->getManager()->getLastName(),
'phone' => $collaborator->getManager()->getMainPhone(),
'email' => $collaborator->getManager()->getProfessionalEmail(),
'fullName' => $collaborator->getManager()->getFullName(),
];
}
$data['user'] = [
'id' => $collaborator->getId(),
'roles' => $collaborator->getRoles(),
'firstName' => $collaborator->getFirstName(),
'lastName' => $collaborator->getLastName(),
'fullName' => $collaborator->getFullName(),
'qualification' => $this->translator->trans($qualification, [], 'qualification_levels'),
'avatar' => $collaborator->getFullPathAvatar(),
'manager' => $manager,
'currency' => $this->currencyService->getCurrency(),
'gender' => [
'code' => $collaborator->getGender()->getCode()
],
'termsAccepted' => $collaborator->getCgu() instanceof Cgu ?? false
];
// Add last connection date
$collaborator->setLastConnection(new \DateTime());
$this->manager->persist($collaborator);
$this->manager->flush();
$event->setData($data);
$userData = json_decode($this->requestStack->getCurrentRequest()->getContent());
$this->bus->dispatch(new ConnexionLogsMessage(
$collaborator->getId(),
$userData->ipAddress ?? $_SERVER['REMOTE_ADDR'] ?? 'ND',
$userData->browser ?? 'ND',
new \DateTimeImmutable('now')
));
}
}