Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify if a user is being impersonated in Symfony2?

Tags:

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.

like image 908
Aleksander Krzywinski Avatar asked Jun 16 '11 12:06

Aleksander Krzywinski


2 Answers

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 ?> 
like image 82
Crozin Avatar answered Oct 06 '22 01:10

Crozin


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.

like image 29
Sirhara Avatar answered Oct 06 '22 01:10

Sirhara