Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2: check isGranted for a route

Tags:

symfony

supposed having certain route string like "/path/index.html" protected by firewall, how to chek whether current user is able to access it?

Thanks in advance!

I am sorry, I should have been more explicit: I have an array of route names and I construct a menu. A lot of users with different roles can access a page with this menu. The purpose is to show only accessible liks in this menu for a particular user.

Something like:

'security_context'->'user'->isGranted('/path/index.html')
like image 566
VladRia Avatar asked Jul 29 '14 12:07

VladRia


1 Answers

This answer is based on your comments: You should get the roles needed to access that route.to that you need access to the security.access_map service which is private.so it has to be injected directly.e.g: you can create a path_roles service like such that you can get the roles for a certain path:

namespace Acme\FooBundle;

class PathRoles
{
    protected $accessMap;

    public function __construct($accessMap)
    {
        $this->accessMap = $accessMap;
    }

    public function getRoles($path)
    { //$path is the path you want to check access to

        //build a request based on path to check access
        $request = Symfony\Component\HttpFoundation\Request::create($path, 'GET');
        list($roles, $channel) = $this->accessMap->getPatterns($request);//get access_control for this request

        return $roles;
    }
}

now declare it as a service:

services:
    path_roles:
        class: 'Acme\FooBundle\PathRoles'
        arguments: ['@security.access_map']

now use that service in your controller to get the roles for the path and construct your menu based on those roles and isGranted.i.e:

  //code from controller
  public function showAction(){
      //do stuff and get the link path for the menu,store it in $paths
      $finalPaths=array();
      foreach($paths as $path){
      $roles = $this->get('path_roles')->getRoles($path);
      foreach($roles as $role){
          $role = $role->getRole();//not sure if this is needed
          if($this->get('security.context')->isGranted($role)){
              $finalPaths[] = $path;
              break;
          }
      }
     //now construct your menu based on $finalPaths
      }
  }
like image 182
user2268997 Avatar answered Nov 06 '22 08:11

user2268997