Get Impersonated User in voter – Symfony 4

  php, symfony, symfony4

I have created a voter to manage impersonation in my project. However, I need to check some properties on my impersonated User to see if the impersonator can actually impersonate this user.

Here is my voter:


namespace AppSecurityVoter;

use SymfonyComponentHttpFoundationRequestStack;
use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
use SymfonyComponentSecurityCoreAuthorizationVoterVoter;
use SymfonyComponentSecurityCoreSecurity;
use SymfonyComponentSecurityCoreUserUserInterface;

class SwitchUserVoter extends Voter
{
    private $security;
    private $requestStack;

    public function __construct(Security $security, RequestStack $requestStack)
    {
        $this->security = $security;
        $this->requestStack = $requestStack;
    }

    protected function supports($attribute, $subject): bool
    {
        return in_array($attribute, ['CAN_SWITCH_USER'])
            && $subject instanceof UserInterface;
    }

    protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
    {
        $user = $token->getUser();

        // if the user is anonymous or if the subject is not a user, do not grant access
        if (!$user instanceof UserInterface || !$subject instanceof UserInterface) {
            return false;
        }

        if (!$this->security->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
            return false;
        }

        $request = $this->requestStack->getCurrentRequest();

        if (!$request->headers->has('HTTP_X_SWITCH_USER')) {
            return false;
        }

        // Getting my user object here by querying my database with the HTTP_X_SWITCH_USER value

        return false;
    }
}

What I do for now is I use my HTTP_X_SWITCH_USER header (which contains user email) to get my user by querying my database.

Does symfony have some "built-in" way to get the impersonated user. Something like this :

$user = $token->getUser(); // The impersonator user
$user = $token->getImpersonatedUser(); // The impersonated user

Thanks for your help !

Source: Ask PHP

LEAVE A COMMENT