Skip to content

Commit 2f81cdd

Browse files
rvanlaakweaverryan
authored andcommitted
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 0820635 commit 2f81cdd

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

cookbook/security/impersonating_user.rst

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,3 +151,63 @@ setting:
151151
),
152152
),
153153
));
154+
155+
Events
156+
------
157+
158+
The firewall dispatches the ``security.switch_user`` event right after the impersonation
159+
is completed. The :class:`Symfony\\Component\\Security\\Http\\Event\\SwitchUserEvent` is
160+
passed to the listener, and you can use this to get the user that you are now impersonating.
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 update the locale when you impersonate a user. The following code sample will show
165+
how to change the sticky locale:
166+
167+
.. configuration-block::
168+
169+
.. code-block:: yaml
170+
171+
# app/config/services.yml
172+
services:
173+
app.switch_user_listener:
174+
class: AppBundle\EventListener\SwitchUserListener
175+
tags:
176+
- { name: kernel.event_listener, event: security.switch_user, method: onSwitchUser }
177+
178+
.. code-block:: xml
179+
180+
<!-- app/config/services.xml -->
181+
<service id="app.switch_user_listener" class="AppBundle\EventListener\SwitchUserListener">
182+
<tag name="kernel.event_listener" event="security.switch_user" method="onSwitchUser" />
183+
</service>
184+
185+
.. code-block:: php
186+
187+
// app/config/services.php
188+
$container
189+
->register('app.switch_user_listener', 'AppBundle\EventListener\SwitchUserListener')
190+
->addTag('kernel.event_listener', array('event' => 'security.switch_user', 'method' => 'onSwitchUser'))
191+
;
192+
193+
.. caution::
194+
195+
The listener implementation assumes your ``User`` entity has a ``getLocale()`` method.
196+
197+
.. code-block:: php
198+
199+
// src/AppBundle/EventListener/SwitchUserListener.pnp
200+
namespace AppBundle\EventListener;
201+
202+
use Symfony\Component\Security\Http\Event\SwitchUserEvent;
203+
204+
class SwitchUserListener
205+
{
206+
public function onSwitchUser(SwitchUserEvent $event)
207+
{
208+
$event->getRequest()->getSession()->set(
209+
'_locale',
210+
$event->getTargetUser()->getLocale()
211+
);
212+
}
213+
}

0 commit comments

Comments
 (0)