src/Social/UserBundle/Listener/SwitchUserListener.php line 66

Open in your IDE?
  1. <?php
  2. namespace Social\UserBundle\Listener;
  3. use Doctrine\ORM\EntityManager;
  4. use Social\UserBundle\Entity\User;
  5. use Symfony\Bridge\Doctrine\RegistryInterface;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. use Social\UserBundle\Service\UserAuthenticationHandler;
  9. use Symfony\Component\Security\Http\Event\SwitchUserEvent;
  10. use Symfony\Component\DependencyInjection\ContainerInterface;
  11. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  12. use Exception;
  13. /**
  14.  * Class SwitchUserListener
  15.  *
  16.  * @package Social\UserBundle\Listener
  17.  */
  18. class SwitchUserListener
  19. {
  20.     /**
  21.      * @var ContainerInterface $container
  22.      */
  23.     protected $container;
  24.     /**
  25.      * @var EntityManager $em
  26.      */
  27.     protected $em;
  28.     /**
  29.      * @var TokenStorageInterface
  30.      */
  31.     protected $securityContext;
  32.     /**
  33.      * @var UserAuthenticationHandler
  34.      */
  35.     protected $userAuthentication;
  36.     /**
  37.      * SwitchUserListener constructor.
  38.      *
  39.      * @param TokenStorageInterface     $securityContext
  40.      * @param UserAuthenticationHandler $userAuthenticationHandler
  41.      * @param RegistryInterface         $registry
  42.      */
  43.     public function __construct(
  44.         TokenStorageInterface $securityContext,
  45.         UserAuthenticationHandler $userAuthenticationHandler,
  46.         RegistryInterface $registry
  47.     ) {
  48.         $this->securityContext    $securityContext;
  49.         $this->userAuthentication $userAuthenticationHandler;
  50.         $this->em                 $registry->getManager();
  51.     }
  52.     /**
  53.      * @param SwitchUserEvent $event
  54.      *
  55.      * @return RedirectResponse
  56.      * @throws Exception
  57.      */
  58.     public function onSwitchUser(SwitchUserEvent $event): RedirectResponse
  59.     {
  60.         $currentUser null;
  61.         if (null !== $this->securityContext->getToken()) {
  62.             $currentUser $this->securityContext->getToken()->getUser();
  63.         }
  64.         if (null === $currentUser || !$currentUser instanceof UserInterface) {
  65.             throw new Exception('Something went bad!');
  66.         }
  67.         /** @var User $user */
  68.         $user $event->getTargetUser();
  69.         if ($user && $user->hasRole(User::ROLE_SUPER_ADMIN)) {
  70.             throw new Exception('you cannot impersonate a super admin');
  71.         }
  72.         if ($user) {
  73.             return $this->userAuthentication->main($user);
  74.         }
  75.     }
  76. }