Skip to content

Commit 11ec6e4

Browse files
committed
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
1 parent 4fc429e commit 11ec6e4

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

cookbook/security/impersonating_user.rst

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,3 +151,49 @@ setting:
151151
),
152152
),
153153
));
154+
155+
Events
156+
------
157+
158+
The firewall dispatches the ``security.switch_user`` event right after the impersonation
159+
completed. The ``SwitchUserEvent`` is passed to the listener, based on which you are able
160+
to get the target user you impersonate.
161+
162+
The cookbook article about
163+
:doc:`Making the Locale "Sticky" during a User's Session </cookbook/session/locale_sticky_session>`
164+
does not take any changing locale into account. The following code sample will show how to change the sticky locale:
165+
166+
.. configuration-block::
167+
168+
.. code-block:: yaml
169+
170+
# app/config/services.yml
171+
services:
172+
app.switch_user_listener:
173+
class: AppBundle\EventListener\SwitchUserListener
174+
tags:
175+
- { name: kernel.event_listener, event: security.switch_user, method: onSwitchUser }
176+
177+
.. caution::
178+
179+
The listener implementation assumes your ``User`` entity has ``getLocale()``.
180+
181+
.. code-block:: php
182+
183+
// src/AppBundle/EventListener/SwitchUserListener.pnp
184+
185+
use Symfony\Component\Security\Http\Event\SwitchUserEvent;
186+
187+
class SwitchUserListener
188+
{
189+
/**
190+
* @param SwitchUserEvent $event
191+
*/
192+
public function onSwitchUser(SwitchUserEvent $event)
193+
{
194+
$event->getRequest()->getSession()->set(
195+
'_locale',
196+
$event->getTargetUser()->getLocale()
197+
);
198+
}
199+
}

0 commit comments

Comments
 (0)