In an application built with Symfony2 we want superadmins to be able to impersonate other users. This is easily done by giving the superadmin user the ROLE_ALLOWED_TO_SWITCH role. The switching is implemented with a call to "somewhere?_switch_user=" as suggesed in the reference documentation.
The problem however, is to detect in a template if the current user is actually impersonated so as to print a link to "somewhere?_switch_user=_exit" on the page, thus enabling the impersonating user to return to her real user.
I haven't been using Symfony2 for a while so I'm not sure, but when you switch to another user you gain all roles assigned to that user and one extra role: ROLE_PREVIOUS_ADMIN
. So I guess all you need to do is to use voter to check whether such a role is assigned to the current user using voter.
// Twig {% if is_granted('ROLE_PREVIOUS_ADMIN') %} <a href="...?_switch_user=_exit">EXIT</a> {% endif %} // PHP <?php if ($view['security']->isGranted('ROLE_PREVIOUS_ADMIN')): ?> <a href="...?_switch_user=_exit">EXIT</a> <?php endif ?>
An example of how to get more details about the impersonator:
use Symfony\Component\Security\Core\Role\SwitchUserRole; $sec = $this->get('security.context'); if($sec->isGranted('ROLE_PREVIOUS_ADMIN')) { foreach($sec->getToken()->getRoles() as $role) { if ($role instanceof SwitchUserRole) { $admin_user = $role->getSource()->getUser(); } } }
You then have admin_user as the original user object. Remember to use the SwitchUserRole.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With