<?php
namespace Social\UserBundle\Listener;
use Doctrine\ORM\EntityManager;
use Social\UserBundle\Entity\User;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\User\UserInterface;
use Social\UserBundle\Service\UserAuthenticationHandler;
use Symfony\Component\Security\Http\Event\SwitchUserEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Exception;
/**
* Class SwitchUserListener
*
* @package Social\UserBundle\Listener
*/
class SwitchUserListener
{
/**
* @var ContainerInterface $container
*/
protected $container;
/**
* @var EntityManager $em
*/
protected $em;
/**
* @var TokenStorageInterface
*/
protected $securityContext;
/**
* @var UserAuthenticationHandler
*/
protected $userAuthentication;
/**
* SwitchUserListener constructor.
*
* @param TokenStorageInterface $securityContext
* @param UserAuthenticationHandler $userAuthenticationHandler
* @param RegistryInterface $registry
*/
public function __construct(
TokenStorageInterface $securityContext,
UserAuthenticationHandler $userAuthenticationHandler,
RegistryInterface $registry
) {
$this->securityContext = $securityContext;
$this->userAuthentication = $userAuthenticationHandler;
$this->em = $registry->getManager();
}
/**
* @param SwitchUserEvent $event
*
* @return RedirectResponse
* @throws Exception
*/
public function onSwitchUser(SwitchUserEvent $event): RedirectResponse
{
$currentUser = null;
if (null !== $this->securityContext->getToken()) {
$currentUser = $this->securityContext->getToken()->getUser();
}
if (null === $currentUser || !$currentUser instanceof UserInterface) {
throw new Exception('Something went bad!');
}
/** @var User $user */
$user = $event->getTargetUser();
if ($user && $user->hasRole(User::ROLE_SUPER_ADMIN)) {
throw new Exception('you cannot impersonate a super admin');
}
if ($user) {
return $this->userAuthentication->main($user);
}
}
}