I have a admin panel and I have defined a role for it ROLE_ADMIN
. In my security.yml file I am using a pattern ^/admin/*
so every thing under /admin requires ROLE_ADMIN
. Now in frontend of my app I need to check user role and if role is ROLE_ADMIN
render one file and otherwise render another file. This url does not fall under the pattern defined in security.yml.
So how do I check whether the user is admin or a normal user on the homepage which does not fall under the pattern defined in security.yml ?
Enable the firewall on the whole app using the ^/
pattern, permit anonymous access and use access_control
to restrict access:
security:
firewalls:
secured_area:
pattern: ^/
anonymous: ~
access_control:
- { path: ^/admin, roles: ROLE_ADMIN }
As @itsmequinn suggested, use the isGranted()
method of the security context:
if ($this->get('security.context')->isGranted('ROLE_BRAND')) {
// the user has the ROLE_BRAND role, so act accordingly
}
In Symfony 2.6, security.context
has been split into two separate services. Hence you need to use the security.authorization_checker
service to solve the problem:
if ($this->get('security.authorization_checker')->isGranted('ROLE_BRAND')) {
// the user has the ROLE_BRAND role, so act accordingly
}
Symfony 3.0
Prior to Symfony 2.6
you would use SecurityContext
.SecurityContext
will be deprecated in Symfony 3.0
in favour of the AuthorizationChecker
.
For Symfony 2.6+
& Symfony 3.0
use AuthorizationChecker
.
if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
# User is a ROLE_ADMIN
}
if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) {
# User is a ROLE_ADMIN
}
Similar Question: How to check if an user is logged in Symfony2 inside a controller?
Read more the docs here: AuthorizationChecker
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With