簡體   English   中英

Sonata User Bundle - 如何限制用戶只能編輯自己的個人資料?

[英]Sonata User Bundle - How to restrict users to only be able to edit their own profile?

我正在使用 Symfony 5 和 Sonata User Bundle 5 的開發快照,正如標題所說,我想限制活動(經過身份驗證的)用戶只能編輯他自己的個人資料(而不是所有人的個人資料)具有相同角色的其他用戶)。 目前我只能選擇全部或全部,因為權限由角色處理,並且具有相同角色的所有用戶都具有相同的權限。 誰能把我推向正確的方向?

我想做和你一樣的事情(使用 sf 5.4、SonataAdminBundle 4.14 和 SonataUserBundle 5.3),我最終使用了自定義 controller 以及preEditpreShow方法。

<?php
namespace App\Controller;

use Sonata\AdminBundle\Controller\CRUDController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use App\Entity\SonataUserUser;

class CustomCRUDController extends CRUDController
{
    const deniedMessage = "Put your custom access denied message here.";
    
    public function __construct(Security $security)
    {
       $this->security = $security;
    }
    
    protected function preEdit(Request $request, object $object): ?Response
    {
        if ($object instanceof SonataUserUser) {
            if (!$this->security->isGranted('ROLE_SUPER_ADMIN') &&
                $this->security->getUser()->getId() != $object->getId()) {
                throw new AccessDeniedException(SELF::deniedMessage);
             }
        }

        return null;
    }

    protected function preShow(Request $request, object $object): ?Response
    {
        if ($object instanceof SonataUserUser) {
            if (!$this->security->isGranted('ROLE_SUPER_ADMIN') &&
                $this->security->getUser() != $object->getId()) {
                throw new AccessDeniedException(SELF::deniedMessage);
            }
        }

        return null;
    }
}

sonata_admin.yaml

sonata_admin:
    default_controller: App\Controller\CustomCRUDController

有了這個,沒有角色ROLE_SUPER_ADMIN的用戶應該不能編輯或顯示其他用戶。

我不知道這是否是正確的方法,或者它是否是一個可靠的無錯誤解決方案,但它似乎對我有用。

僅供參考:如果他們需要正確實施更復雜的邏輯,也可以使用自定義選民

@perfetzki 我遲到了六個月,但我希望這對其他人有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM