src/EventSubscriber/SwitchUserSubscriber.php line 24

  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\Routing\RouterInterface;
  5. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  6. use Symfony\Component\Security\Http\Event\SwitchUserEvent;
  7. use Symfony\Component\Security\Http\SecurityEvents;
  8. use Symfony\Bundle\SecurityBundle\Security;
  9. use Symfony\Component\HttpFoundation\RedirectResponse;
  10. use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
  11. class SwitchUserSubscriber implements EventSubscriberInterface
  12. {
  13.     protected $router;
  14.     protected $roleHierarchy;
  15.     public function __construct(RouterInterface $routerRoleHierarchyInterface $roleHierarchy) {
  16.         $this->router $router;
  17.         $this->roleHierarchy $roleHierarchy;
  18.     }
  19.     
  20.     public function onSwitchUser(SwitchUserEvent $event): void
  21.     {
  22.         $user $event->getTargetUser();
  23.         if ($this->hasRole($user"ROLE_ADMIN")) :
  24.             $response = new RedirectResponse($this->router->generate('admin_default'), 302);
  25.             $response->send();
  26.         endif;
  27.         if ($this->hasRole($user"ROLE_CUSTOMER")) :
  28.             $response = new RedirectResponse($this->router->generate('customer_default'), 302);
  29.             $event->getRequest()->getSession()->set('username''impersonator');
  30.             $response->send();
  31.         endif;
  32.         if ($this->hasRole($user"ROLE_WRITER")) :
  33.             $response = new RedirectResponse($this->router->generate('writer_default'), 302);
  34.             $event->getRequest()->getSession()->set('username''impersonator');
  35.             $response->send();
  36.         endif;
  37.     }
  38.     private function hasRole(\App\Entity\User $userstring $role): bool 
  39.     {
  40.         $reachableRoles $this->roleHierarchy->getReachableRoleNames($user->getRoles());
  41.         foreach ($reachableRoles as $reachableRole) {
  42.             if ($reachableRole === $role) {
  43.                 return true;
  44.             }
  45.         }
  46.         return false;
  47.     }
  48.     public static function getSubscribedEvents(): array
  49.     {
  50.         return [
  51.             SecurityEvents::SWITCH_USER => 'onSwitchUser',
  52.         ];
  53.     }
  54. }