Last active
August 13, 2024 19:16
-
-
Save marcoiosif/ac10d8973de1b0981d2be472de75e454 to your computer and use it in GitHub Desktop.
Symfony avoid log out after update roles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\EventSubscriber; | |
use App\Entity\User; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
use Symfony\Component\HttpKernel\Event\RequestEvent; | |
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; | |
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; | |
class RefreshRolesSubscriber implements EventSubscriberInterface | |
{ | |
public function __construct | |
( | |
private TokenStorageInterface $tokenStorage | |
){} | |
public function onKernelRequest(RequestEvent $event): void | |
{ | |
if (!$event->isMainRequest()) { | |
// don't do anything if it's not the main request | |
return; | |
} | |
$token = $this->tokenStorage->getToken(); | |
if($token instanceof UsernamePasswordToken) $this->refreshRoles($token, $event); | |
} | |
private function refreshRoles(UsernamePasswordToken $token, RequestEvent $event):void | |
{ | |
$user = $token->getUser(); | |
if($user instanceof User && $event->getRequest()->getSession()->get('user_roles') != $user->getRoles()) | |
{ | |
$token = new UsernamePasswordToken($user, $token->getFirewallName(), $user->getRoles()); | |
$this->tokenStorage->setToken($token); | |
$event->getRequest()->getSession()->set('_security_' . $token->getFirewallName(), serialize($token)); | |
$event->getRequest()->getSession()->set('user_roles', $user->getRoles()); | |
} | |
} | |
public static function getSubscribedEvents() | |
{ | |
return [ | |
'kernel.request' => 'onKernelRequest', | |
]; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\Entity; | |
use Symfony\Component\Security\Core\User\EquatableInterface; | |
class User implements EquatableInterface | |
{ | |
public function isEqualTo(UserInterface $user): bool | |
{ | |
return $this->getUserIdentifier() == $user->getUserIdentifier(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment