2013-04-09 144 views
5

我正在使用帶有FosUserBundle的SonataAdminBundle。我的儀表板中有一些問題。Sonata Admin Bundle儀表板過濾器角色和DDBB權限過濾器實體

在我的應用程序中,我有資源,公司和用戶。用戶屬於公司,並且可以創建屬於他的公司的資源。所有這些過程都將在儀表板中完成,所有角色都可以訪問。

我試圖做的是每個人都可以訪問儀表板,但是當用戶選擇一個實體(資源)在儀表板中列出時,只有他的公司的實體纔會顯示。例如,兩家公司可以創建一輛車(資源),但每家公司只能看到他自己的車輛(資源)。

最後,我想讓儀表板過濾連接的用戶公司的實體。 有沒有什麼方法可以在Sonata中創建一個查詢,只顯示一些實體,取決於用戶的Company_Id和BBDD中映射的資源的Company_Id?

回答

4

最簡單的方法是編輯查詢並檢查編輯/顯示操作中的訪問權限。

事情是這樣的:

管理類

/** 
* {@inheritdoc} 
*/ 
public function createQuery($context = 'list') 
{ 
    $user = $this->getConfigurationPool()->getContainer()->get('security.context')->getToken()->getUser(); 

    /** @var \Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery @query */ 
    $query = $this->getModelManager()->createQuery($this->getClass(), 'o'); 
    if (!$this->isGranted('MASTER')) { 
     $query 
      ->where('entity.user = :user') 
      ->setParameter('user', $user) 
     ; 
    } 

    return $query; 
} 

如果用戶沒有掌握,他只能看到他自己的實體。

您還可以實現管理類等hasSubjectAccess方法:

/** 
* Check whether the user has access to the subject 
* 
* @return bool 
*/ 
protected function hasSubjectAccess() 
{ 
    $user = $this->getConfigurationPool()->getContainer()->get('security.context')->getToken()->getUser(); 
    if (!$this->isGranted('MASTER') && $this->getSubject()->getUser() !== $user) { 
     return false; 
    } 

    return true; 
} 

,並在編輯和顯示形式執行這種檢查:

/** 
* {@inheritdoc} 
*/ 
protected function configureFormFields(FormMapper $formMapper) 
{ 
    if (!$this->hasSubjectAccess()) { 
     throw new AccessDeniedException(); 
    } 

    // ... 
} 

另一種方式是實現ACL。您可以閱讀official documentation

+0

謝謝,這是我在尋找,但我仍然有一些疑問。我寫了新的答案,因爲它太長了。 – Angel 2013-04-10 08:26:53

1

更多有關最後,我得到這樣的:

public function createQuery($context = 'list') 
    $query = $this->getModelManager()->createQuery($this->getClass(), 'entity'); 

    if (($this->getClass() instanceof \Sademer\CoreBundle\Entity\Resource) 
    || (is_subclass_of($this->getClass(), \Sademer\CoreBundle\Entity\Resource'))) 
    { 
      $query->select ('e'); 
      $query->from($this->getClass(), 'e'); 
      $query->from('CoreBundle\Entity\Resource', 'r'); 
      $query->where('e.id = r.id AND r.company = :company'); 
      $query->setParameter('company', 5); 
    } 
} 
1

對我來說的createQuery()函數沒有工作。可能是由於Sonata Admin的版本。無論如何,我的工作是configureDatagridFilters()函數。

它做相同的工作爲的createQuery,看起來是這樣的:

protected function configureDatagridFilters(DatagridMapper $datagridMapper) 
{ 
    $qb = $datagridMapper 
     ->getDatagrid() 
     ->getQuery() 
     ->getQueryBuilder(); 

    $qb->andWhere(
     // Your where clause here 
    ); 
    $qb->setParameter(); // Set Parameter 
}