2016-11-28 63 views
3

我已經像在文檔中一樣實施了克隆操作。如何限制對創建該對象的用戶的克隆操作訪問權限?如何根據用戶無法訪問自定義操作 - Sonata管理員

我的操作中已經存在拒絕異常檢查,但是如果用戶不是該對象的作者,我該如何將該按鈕隱藏在列表視圖中。用戶仍然應該能夠列出訂單並顯示它。

這是我的路線:

protected function configureRoutes(RouteCollection $collection) 
{ 
    $collection->add('clone', $this->getRouterIdParameter().'/clone'); 
} 

而我的列表域:

protected function configureListFields(ListMapper $listMapper) 
{ 
    $listMapper 
     ->add('_action', 'actions', array(
      'actions' => array(
       'show' => array(), 
       'edit' => array(), 
       'clone' => array(
        'template' => 'AppBundle:Sonata/Button:clone_button.html.twig' 
       ), 
      ), 'label' => 'Actions' 
     )) 
    ; 
} 

和我的克隆行動:

public function cloneAction($id = null) 
{ 
    $object = $this->admin->getSubject(); 
    if (!$object) { 
     throw new NotFoundHttpException(sprintf('Unable to find the object with id : %s', $id)); 
    } 

    If (!$object->isAuthor($this->getUser())) { 
     throw new AccessDeniedException(); 
    } 

    $clonedObject = clone $object; 

    $this->admin->create($clonedObject); 
    $this->addFlash('sonata_flash_success', 'Cloned successfully'); 
    return new RedirectResponse($this->admin->generateUrl('edit', array('id' => $clonedObject->getId()))); 
} 

正如你可以在我的克隆行動看,我檢查用戶是否是訂單的作者。但是,如何通過檢查我的isAuthor函數完全刪除列表中的按鈕?

因爲現在用戶可以看到該按鈕,但是如果他未經授權克隆該訂單,並且他單擊該按鈕,他將得到拒絕訪問的異常。所以我不想顯示按鈕。 編輯按鈕的計數相同。

我想到的是這樣的:

protected function configureRoutes(RouteCollection $collection) 
{ 
    $user = $this->getConfigurationPool()->getContainer()->get('security.token_storage') 
      ->getToken()->getUser(); 

    If (!$object->isAuthor($user)) { 
     $collection->remove('edit'); 
     $collection->remove('clone'); 
    } 
} 

但顯然這不能做。

有沒有人有一個想法如何做到這一點?

回答

2

我會創建a Symfony Voter並從操作中刪除檢查。該檢查將完成,在選民外部的行動中,並可以在任何地方完成,包括模板。你應該檢查模板,它可能已經做了檢查。

另外,題外話題提示,總是提供一個消息在你的例外。

throw new AccessDeniedException('Not an author of this object'); 
+0

好的,那會讓我做一些事情更容易。但現在問題仍然存在,如果用戶無法訪問,我該如何隱藏路線?該按鈕將保持在那裏,如果有人點擊它將拋出異常。如果用戶可以使用它,我只想顯示按鈕。如果我使用純Symfony,很容易做到這一點。但現在我用了奏鳴曲。 –

+1

檢查模板,但正如我所說,可能已經有一個檢查嗎?或者你自己寫了模板?它應該在路由和對象中使用'is_granted()',這將調用選舉器。 – greg0ire

+0

所以第0步,如果你想解決這個問題,並找到我們的按鈕模板 – greg0ire