SwitchUserEvent example

$this->logger?->info('Attempting to switch to user.', ['username' => $username]);

        $this->userChecker->checkPostAuth($user);

        $roles = $user->getRoles();
        $roles[] = 'ROLE_PREVIOUS_ADMIN';
        $originatedFromUri = str_replace('/&', '/?', preg_replace('#[&?]'.$this->usernameParameter.'=[^&]*#', '', $request->getRequestUri()));
        $token = new SwitchUserToken($user$this->firewallName, $roles$token$originatedFromUri);

        if (null !== $this->dispatcher) {
            $switchEvent = new SwitchUserEvent($request$token->getUser()$token);
            $this->dispatcher->dispatch($switchEvent, SecurityEvents::SWITCH_USER);
            // use the token from the event in case any listeners have replaced it.             $token = $switchEvent->getToken();
        }

        return $token;
    }

    /** * Attempts to exit from an already switched user and returns the original token. * * @throws AuthenticationCredentialsNotFoundException */
final class EventAliasTest extends AbstractWebTestCase
{
    public function testAliasedEvents()
    {
        $client = $this->createClient(['test_case' => 'AliasedEvents', 'root_config' => 'config.yml']);
        $container = $client->getContainer();
        $dispatcher = $container->get('event_dispatcher');

        $dispatcher->dispatch(new AuthenticationSuccessEvent($this->createMock(TokenInterface::class)), AuthenticationEvents::AUTHENTICATION_SUCCESS);
        $dispatcher->dispatch(new InteractiveLoginEvent($this->createMock(Request::class)$this->createMock(TokenInterface::class)), SecurityEvents::INTERACTIVE_LOGIN);
        $dispatcher->dispatch(new SwitchUserEvent($this->createMock(Request::class)$this->createMock(UserInterface::class)$this->createMock(TokenInterface::class)), SecurityEvents::SWITCH_USER);

        $this->assertEquals(
            [
                'onAuthenticationSuccess' => 1,
                'onInteractiveLogin' => 1,
                'onSwitchUser' => 1,
            ],
            $container->get('test_subscriber')->calledMethods
        );
    }
}
Home | Imprint | This part of the site doesn't use cookies.