Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: How to display admin-account name while impersonating user-account?

Tags:

twig

symfony

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.

like image 612
ioleo Avatar asked May 03 '12 11:05

ioleo


2 Answers

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

like image 128
Matt Avatar answered Nov 18 '22 09:11

Matt


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.

like image 29
Jonathan Avatar answered Nov 18 '22 08:11

Jonathan