Reputation: 3379
Hi everyone im new to Symfony and have a simple problem.
In the security.yml
file I've set some access controlled paths:
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: .*settings, roles: ROLE_USER }
- { path: ^/$, roles: ROLE_USER }
- { path: ^/.*, roles: ROLE_ADMIN }
That so far works as i want to.
Now Im building a menu and want to hide show the navigation items based on its access, so how can i fetch this information?
There has to be some function like:
$securityContext->isUrlGranted( $this->generateUrl('homepage') );
Thanks for your help.
EDIT
Example:
// current user is ROLE_ADMIN:
$acl->isUrlGranted( 'foo/bar' ); // true
$acl->isUrlGranted( 'login' ); // true
// IS_AUTHENTICATED_ANONYMOUSLY
$acl->isUrlGranted( 'login' ); // true
$acl->isUrlGranted( 'something/else' ); // false
// ROLE_USER
$acl->isUrlGranted( 'settings/profile' ); // true
$acl->isUrlGranted( 'foo/bar' ); // false
etc..
Upvotes: 3
Views: 1643
Reputation: 1315
Now there is no simple ways in Symfony
get this information via one function.
To get it you can access security.access_control
parameters in your application using security.access_map
service.
But you can't request it from the container directly, because it's a private service, so have to inject it into another service.
And only then you will be able to write your own Twig
extension with isUrlGranted()
function.
P.S.: My answer is only a short summary of well written answer on the similar question.
Upvotes: 1
Reputation: 2063
if you are using twig in your view ( which should contain the menu ), you can test the user role with:
{# my menu.twig.html #}
{% if app.security.isGranted('ROLE_ADMIN', app.user) %}
....
{% endif %}
You can do the same in your controller by the way, but i supposed that your layout contains the menu so i posted a twig answer. Tell me if it's relevant and helpful for you.
Upvotes: 1