<?php
namespace App\Subscriber;
use App\Service\User\UserPermissionsHelper;
use Oz\ApiNvl\Model\User;
use App\Service\User\UserDecorator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
/**
*
*/
class ApiAuthenticationSubscriber implements EventSubscriberInterface
{
/**
* @var UserDecorator
*/
private $userDecorator;
/**
* @var UserPermissionsHelper
*/
private $userPermissionsHelper;
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
/**
* @param UserDecorator $userDecorator
* @param UserPermissionsHelper $userPermissionsHelper
* @param TokenStorageInterface $tokenStorage
*/
public function __construct(
UserDecorator $userDecorator,
UserPermissionsHelper $userPermissionsHelper,
TokenStorageInterface $tokenStorage)
{
$this->userDecorator = $userDecorator;
$this->userPermissionsHelper = $userPermissionsHelper;
$this->tokenStorage = $tokenStorage;
}
/**
* @return array[]
*/
public static function getSubscribedEvents(): array
{
return [
SecurityEvents::INTERACTIVE_LOGIN => ['interactiveLogin', 50],
];
}
/**
* @param InteractiveLoginEvent $interactiveLoginEvent
*
* @throws ClientExceptionInterface
* @throws DecodingExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
* @throws TransportExceptionInterface
*/
public function interactiveLogin(InteractiveLoginEvent $interactiveLoginEvent): void
{
/** @var User $user */
$user = $interactiveLoginEvent->getAuthenticationToken()->getUser();
$this->userPermissionsHelper->setUserPermissionsRoles($user);
$roles = $user->getRoles();
$token = $interactiveLoginEvent->getAuthenticationToken();
$firewallName = 'main';
$newToken = new UsernamePasswordToken($user, $token->getCredentials(), $firewallName, $roles);
$this->tokenStorage->setToken($newToken);
$request = $interactiveLoginEvent->getRequest();
$request->getSession()->set('_security_' . $firewallName, serialize($newToken));
if (!$user instanceof User) {
return;
}
// j'ai décommenté car si je laisse ça déconnecte mon user
// $this->userDecorator->setUserInfo($user);
// $this->userDecorator->setUserPermissions($user);
}
}