How to identify if a user is being impersonated in Symfony2?

Viewed 7454

In an application built with Symfony2 we want superadmins to be able to impersonate other users. This is easily done by giving the superadmin user the ROLE_ALLOWED_TO_SWITCH role. The switching is implemented with a call to "somewhere?_switch_user=" as suggesed in the reference documentation.

The problem however, is to detect in a template if the current user is actually impersonated so as to print a link to "somewhere?_switch_user=_exit" on the page, thus enabling the impersonating user to return to her real user.

4 Answers

If you need to test role from the previous admin user :

Working on Symfony 3.4

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