From 2c246befb9ddc379a10ac4aadd6647d6e8c8911a Mon Sep 17 00:00:00 2001 From: Richard van Laak Date: Fri, 5 Jun 2015 14:07:50 +0200 Subject: [PATCH] Document security.switch_user event ... in the cookbook article about How to Impersonate a User. Added code sample about how to change the locale in case of a sticky locale: http://symfony.com/doc/current/cookbook/session/locale_sticky_session.html --- cookbook/security/impersonating_user.rst | 60 ++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/cookbook/security/impersonating_user.rst b/cookbook/security/impersonating_user.rst index f9003fd9b93..fed2cb5fcfd 100644 --- a/cookbook/security/impersonating_user.rst +++ b/cookbook/security/impersonating_user.rst @@ -151,3 +151,63 @@ setting: ), ), )); + +Events +------ + +The firewall dispatches the ``security.switch_user`` event right after the impersonation +is completed. The :class:`Symfony\\Component\\Security\\Http\\Event\\SwitchUserEvent` is +passed to the listener, and you can use this to get the user that you are now impersonating. + +The cookbook article about +:doc:`Making the Locale "Sticky" during a User's Session ` +does not update the locale when you impersonate a user. The following code sample will show +how to change the sticky locale: + +.. configuration-block:: + + .. code-block:: yaml + + # app/config/services.yml + services: + app.switch_user_listener: + class: AppBundle\EventListener\SwitchUserListener + tags: + - { name: kernel.event_listener, event: security.switch_user, method: onSwitchUser } + + .. code-block:: xml + + + + + + + .. code-block:: php + + // app/config/services.php + $container + ->register('app.switch_user_listener', 'AppBundle\EventListener\SwitchUserListener') + ->addTag('kernel.event_listener', array('event' => 'security.switch_user', 'method' => 'onSwitchUser')) + ; + +.. caution:: + + The listener implementation assumes your ``User`` entity has a ``getLocale()`` method. + +.. code-block:: php + + // src/AppBundle/EventListener/SwitchUserListener.pnp + namespace AppBundle\EventListener; + + use Symfony\Component\Security\Http\Event\SwitchUserEvent; + + class SwitchUserListener + { + public function onSwitchUser(SwitchUserEvent $event) + { + $event->getRequest()->getSession()->set( + '_locale', + $event->getTargetUser()->getLocale() + ); + } + }