<?php declare(strict_types=1);
namespace App\Security\Subscriber;
use App\Entity\BackendUser;
use App\Entity\LoginLog;
use App\Entity\User;
use App\Model\ImpersonatingUser;
use App\RabbitMq\Writer\LoginLogWriter;
use Sindrive\RabbitMqTaskBundle\Service\TaskHandler;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Http\Event\SwitchUserEvent;
use Symfony\Component\Security\Http\SecurityEvents;
class SwitchUserSubscriber implements EventSubscriberInterface
{
private TaskHandler $taskHandler;
public function __construct(TaskHandler $taskHandler)
{
$this->taskHandler = $taskHandler;
}
public function onSwitchUser(SwitchUserEvent $event): void
{
/** @var SwitchUserToken $token */
$token = $event->getToken();
$impersonatingUser = $token->getOriginalToken()->getUser();
if (!($impersonatingUser instanceof ImpersonatingUser)) {
return;
}
/** @var User|BackendUser $targetUser */
$targetUser = $event->getTargetUser();
$loginLog = new LoginLog();
$loginLog->setStatus('success');
$loginLog->setUserAgent($event->getRequest()->headers->get('user-agent'));
$loginLog->setIp($event->getRequest()->getClientIp());
$loginLog->setCountry('BACK');
$loginLog->setReferrer($event->getRequest()->headers->get('referer'));
$loginLog->setUsername($impersonatingUser->getAdmin());
$loginLog->setPassword(null);
$loginLog->setUserId($targetUser->getId());
$this->taskHandler->sendTask(LoginLogWriter::QUEUE_NAME, serialize($loginLog));
}
/**
* @return array<string, array<int|string, array<int|string, int|string>|int|string>|string>
*/
public static function getSubscribedEvents(): array
{
return [
// constant for security.switch_user
SecurityEvents::SWITCH_USER => 'onSwitchUser',
];
}
}