Roles in symfony

1

I have several roles set in Symfony hierarchically

      ROLE_1: [ROLE_2]                

      ROLE_2: [ROLE_3, ROLE_4] 

      ROLE_3: [ROLE_4]         

      ROLE_4: [ROLE_4]        

in a twig I need to execute an action strictly for the user with ROLE_3, but I have not achieved it with the following conditional, because Role 1 and 2 also contain their characteristics

{% if is_granted('ROLE_3') %}

    //Accion ver un elemento html
{% endif %}

How can I make this conditional run strictly for the user with role_3 (so Role_1, Role_2 and Role_4 can not do it), without removing the hierarchies?

    
asked by BBarret 16.06.2017 в 17:07
source

2 answers

0

As you have it structured, you can not do it. But you have the option of consulting the role of the user in question and see if it is the role you are interested in:

{% if app.user.role == 'ROLE_3' %}
{% endif %}

Normally, when you implement UserInterface or AdvanceUserInterface you should have a getRole method that is also accessible from Twig. If that were not the case, it's easy to implement a method, it's simple.

    
answered by 20.06.2017 в 09:09
0

Although they can do it as you indicate, inside your security config you must have it configured in a similar way to this

#app/config/security.yml
security:
    role_hierarchy:
      ROLE_1: ROLE_2
      ROLE_2: [ROLE_3, ROLE_4]  
      ROLE_3: ROLE_4  

Finally, inside Twig

{% if is_granted('IS_AUTHENTICATED_FULLY') %}
<p>Username: {{ app.user.username }}</p>
{% endif %}

Likewise, you can also deny inside your controller

public function helloAction($name)
{
  if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
        throw $this->createAccessDeniedException();
    }
}

** Documentation extracted on Symfony 3.3

    
answered by 04.07.2017 в 17:54