0
votes

I'm writing a template in twig for my symfony4 project. I want to access the user object of the impersonator user. NOT the user that is being impersonated.

I found a solution, but both PhpStorm and the Symfony toolbar tell me that my code is deprecated:

{% if is_granted("ROLE_PREVIOUS_ADMIN") %}
    {% for role in app.token.roles %}
        {% if role.role == "ROLE_PREVIOUS_ADMIN" %}
            {{ role.source.user.username }}
        {% endif %}
    {% endfor %}
{% endif %}

Though my code does work as (not) expected, the following two error messages appear in the web debug toolbar:

10:16:10 php User Deprecated: The Symfony\Component\Security\Core\Authentication\Token\AbstractToken::getRoles() method is deprecated since Symfony 4.3. Use the getRoleNames() method instead.

and

10:16:10 php User Deprecated: The "Symfony\Component\Security\Core\Role\SwitchUserRole" class is deprecated since version 4.3 and will be removed in 5.0. Use strings as roles instead.

1
@ElliotBrl Yes, I have. I want to access the user object from twig itself. I dont't want to pass parameters from symfony to twig because this is in my main template and I don't want to pass this parameter every time I render a template. Or is there something I miss? I am new to symfony, by the way. I always did some silly hard coding in php itself without a framework.ykahveci
Well the notice states the solution, {% for role in app.token.getRoleNames() %}, twig will auto-translate app.token.roles to app.token.getRoles()DarkBee
Solved it thanks, silly me!ykahveci
@DarkBee I deleted it because unfortunately it doesn't work now. I thought it worked, but when testing I just wasn't impersonating anyone, that's why the error was gone. So I will have to find another solution than to use app.token.getRoleNames in the for-loop. When I dump the deprecated content of app.token.getRoles it gives me a huge output including the information of the impersonator user. getRoleNames unfortunately does just what you think it would do: it gives you the role names, but no further information. Now I cant even edit the "It works" comment anymoreykahveci

1 Answers

1
votes

I found a solution myself! I looked at the https://symfony.com/doc/current/security/impersonating_user.html#finding-the-original-user code and applied the functions to the app.token variable in twig.

Forget that for loop! Just use:

{{ app.token.getOriginalToken().getUser() }}

Or short:

{{ app.token.originalToken.user }}