<?php
namespace App\EventSubscribers\Main;
use App\Events\Main\Registration\SecurityEvent;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
/**
* Class SecuritySubscriber
* @package App\EventSubscribers\Main
*/
class SecuritySubscriber implements EventSubscriberInterface
{
const
REGISTRATION_COMPLETED = 'on.registration.completed',
USER_LOGGED_IN = 'user.logged.in'
;
private SessionInterface $session;
private ?Request $request;
public function __construct(
private RequestStack $requestStack,
private TokenStorageInterface $tokenStorage,
private EventDispatcherInterface $eventDispatcher,
private EntityManagerInterface $entityManager
) {
$this->request = $this->requestStack->getCurrentRequest();
if ($this->request instanceof Request) {
$this->session = $this->request->getSession();
}
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return array(
self::REGISTRATION_COMPLETED => "loginUser",
self::USER_LOGGED_IN => "loginUser",
);
}
/**
* @param SecurityEvent $event
*/
public function loginUser(SecurityEvent $event)
{
// we logged in the user after registration completed
$user = $event->getUser();
$request = $event->getRequest();
$token = new UsernamePasswordToken($user, 'user', $user->getRoles());
$this->tokenStorage->setToken($token);
$this->session->set('_security_user', serialize($token));
if ($user->getUserLocale() != $request->getLocale()) {
$user->setUserLocale($request->getLocale());
$this->entityManager->flush();
}
$event = new InteractiveLoginEvent($request, $token);
$this->eventDispatcher->dispatch($event, "security.interactive_login");
}
}