I want to display something like that:
Case 1: "logged in as USER"
@ UserName [ logout ]
No problems here, i just do:
@ {{ app.user.username}} [ <a href="{{ path("logout") }}">logout</a> ]
Case 2: "logged in as ADMIN"
@ AdminName [ logout ]
The same works here:
@ {{ app.user.username}} [ <a href="{{ path("logout") }}">logout</a> ]
Case 3: "logged in as ADMIN impersonating a USER"
AdminName @ UserName [ return ]
Now thats a problem:
{{ ??..what here..?? }} @ {{ app.user.username}} [ <a href="{{ (app.request.getRequestUri ~ '?_switch_user=_exit') }}">return</a> ]
This is the only solution I know... it seems a lot of code for a sipmle displaying username :/
{# iterating through user roles to find ROLE_PREVIOUS_ADMIN #}
{% for role in app.security.token.roles %}
{% if role.source is defined %}
{{ role.source.user.username }}
{% endif %}
{% endfor %}
@ {{ app.user.username }} [ <a href="{{ (app.request.getRequestUri ~ '?_switch_user=_exit') }}">return</a> ]
Is there any other way? I need a pure TWIG solution -> this is supposed to be part of my main twig template (that is extended by all other templates) -> I can't add controller code to all actions, just to display username.
With the idea you have proposed above,.. can you not just create a custom twig extension that encompasses your logic from your twig template so that you can just call myCustomTwigFunction
within your twig template and it will output the original users name?
See http://symfony.com/doc/current/cookbook/templating/twig_extension.html for more info about custom twig extensions
The code you'd have in your Twig extension file would be...
$roles = $this->container->get('security.context')->getToken()->getRoles();
foreach ($roles as $role) {
if (method_exists($role, 'getSource')) {
return ($role->getSource()->getUser()->getUsername());
}
}
Where $container is a class variable of the DI Container on your twig extension class
For anyone looking for a solution for Symfony 4.3/4.4/5.0:
{% if is_granted('ROLE_PREVIOUS_ADMIN') %}
{% for role in app.token.roles %}
{% if role.role == 'ROLE_PREVIOUS_ADMIN' %}
Admin username is {{ role.source.user.username }}
{% endif %}
{% endfor %}
{% endif %}
From Symfony 5.1 onwards, use IS_IMPERSONATOR
in place of ROLE_PREVIOUS_ADMIN
.
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