Search code examples
symfonyimpersonation

Symfony get original user after impersonate another


I'm using Symfony 3.4 and I'm working with the Impersonate user feature : https://symfony.com/doc/3.4/security/impersonating_user.html

I need when I impersonate an user to get the original user.. I don't know how can I do that.

During impersonation, the user is provided with a special role called ROLE_PREVIOUS_ADMIN, is there a way to change this role ?

For example if my original user is ROLE_ADMIN, the special role is ROLE_PREVIOUS_ADMIN, but if my original user is ROLE_SOMETHING, the custom role should be : ROLE_PREVIOUS_SOMETHING

I just need to have a way to get the original user or at least get his roles.

Thanks !


Solution

  • I found a solution :

    public function isImpersonatorAdmin()
    {
        $impersonatorUser = false;
    
        if ($this->security->isGranted('ROLE_PREVIOUS_ADMIN')) {
            foreach ($this->security->getToken()->getRoles() as $role) {
                if ($role instanceof SwitchUserRole) {
                    $impersonatorUser = $role->getSource()->getUser()->hasRole('ROLE_ADMIN');
                    break;
                }
            }
        }
    
        return $impersonatorUser;
    }
    

    This function return true if the impersonator is ROLE_ADMIN.