<?php
namespace Nellapp\Bundle\SDKBundle\Auth\EventSubscriber;
use Nellapp\Bundle\SDKBundle\Auth\Entity\UserInterface;
use Nellapp\Bundle\SDKBundle\Routing\Utils\DomainsRoutingUtils;
use Nellapp\Bundle\SDKBundle\Sync\ApiClient\Account\SsoClient;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
class LoginSubscriber implements EventSubscriberInterface
{
private ?array $pendingPayload = null;
public function __construct(
private DomainsRoutingUtils $domainsRoutingUtils,
private SsoClient $ssoClient,
private LoggerInterface $logger,
)
{
}
public static function getSubscribedEvents(): array
{
return [
LoginSuccessEvent::class => 'onLoginSuccess',
KernelEvents::TERMINATE => 'onTerminate',
];
}
public function onLoginSuccess(LoginSuccessEvent $event): void
{
$request = $event->getRequest();
$user = $event->getUser();
$session = $request->getSession();
if (!$user instanceof UserInterface || !$session) {
return;
}
// DeviceId cookie should already been set through DeviceIdSubscriber on pre-oauth requests
$deviceId = $request->cookies->get('DEVICE_ID');
if (!$deviceId) {
return;
}
$this->pendingPayload = [
'appName' => $this->domainsRoutingUtils->getAppName(),
'userId' => $user->getId(),
'sessionId' => $session->getId(),
'deviceId' => $deviceId,
'userAgent' => $request->headers->get('User-Agent'),
'ipAddress' => $request->getClientIp(),
];
}
public function onTerminate(TerminateEvent $event): void
{
if (!$this->pendingPayload) {
return;
}
try {
$this->ssoClient->postRegister($this->pendingPayload);
} catch (\Exception $e) {
$this->logger->error($e);
}
$this->pendingPayload = null;
}
}