Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
775 views
in Technique[技术] by (71.8m points)

symfony - symfony2: check isGranted for a route

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')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 AcmeFooBundle;

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 = SymfonyComponentHttpFoundationRequest::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: 'AcmeFooBundlePathRoles'
        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
      }
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...