Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check for user role in symfony2 for urls not falling under patterns defined security.yml?

Tags:

php

symfony

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 ?

like image 634
aditya Avatar asked Sep 05 '12 18:09

aditya


2 Answers

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
}
like image 137
Elnur Abdurrakhimov Avatar answered Oct 23 '22 12:10

Elnur Abdurrakhimov


SecurityContext will be deprecated in 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.


Symfony 2.5 (and below)

if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
    # User is a ROLE_ADMIN
}

Symfony 2.6 (and above)

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

like image 20
Anil Avatar answered Oct 23 '22 14:10

Anil