Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ROLE of a user not logged in TWIG Symfony2

Tags:

twig

symfony

I would like to know how can i know if a user is granted when it's not the current user in twig.

I use this code for the current user:

{% if is_granted('ROLE_USER') %}
    <a href="...">Delete</a>
{% endif %}

But i would like to be able to do the same thing with ohter users that are not logged in at the moment. Thank you.

Edit: In fact i think there isn't a direct way with twig to test role of a user that is not authenticated. So i did it directly in the twig template, test if a user is admin or not, then set var. (in my question i was searching how to do in a list of users.)

{% set from_user_is_admin = false %}
{% for role in from_user.getRoles() %} 
    {% if role == 'ROLE_ADMIN' %}{% set from_user_admin = true %}{% endif %}
    {% if role == 'ROLE_SUPER_ADMIN' %}{% set from_user_admin = true %}{% endif %}
{% endfor %}
{% if from_user_admin == false %}THIS USER IS NOT ADMIN{% endif %}
like image 436
Rmannn Avatar asked Jan 31 '12 13:01

Rmannn


2 Answers

I think it would be much easier if you implemented an isGranted function in the User entity:

Class User implements UserInterface {
    ...
    public function isGranted($role)
    {
        return in_array($role, $this->getRoles());
    }
}

You can now easily check for granted roles in every layer of your application. In PHP:

$user->isGranted("USER_ADMIN")

Or in Twig:

user.granted("USER_ADMIN")

If you need to check a role for the current user, you can do this in Twig:

app.user.granted("USER_ADMIN")

Note: the variable "app" is globally defined.

Note 2: this code may throw an exception if you use it outside the secured area of your app, since app.user would be NULL.

like image 79
Webberig Avatar answered Sep 17 '22 21:09

Webberig


You can use similar statement to the above with "not" :

{% if not is_granted('ROLE_USER') %}
    <a href="...">Delete</a>
{% endif %}

or use else statement:

{% if is_granted('ROLE_USER') %}
    <a href="...">Delete</a>
{% else %}
    {# something else for guest user, not logged in #}
{% endif %}
like image 34
Krzysztof Lenda Avatar answered Sep 19 '22 21:09

Krzysztof Lenda