如何使用 Voter 过滤 EntityType 字段

问题描述 投票:0回答:1

我需要使用投票者筛选 EntityType 字段中显示的选项。

我有一个用户实体,它与 CustomerGroup、CustomerEntity 和 CustomerSite 有一些关系。 例如,我在客户组中有一个投票者。我可以根据列表视图中当前用户的角色来过滤结果。我使用“array_filter”函数来使其工作。用户对象示例:

$users = $this->getDoctrine()->getRepository(User::class)->findBy(array('isDeleted' => 0));
$users = array_filter($users, function (User $user) {
     return $this->isGranted('view', $user);
});

我用谷歌搜索了很多页面但没有成功!我尝试在 CustomerGroupRepository 中创建一个自定义函数,并从 FormType 中的 query_builder 选项调用它:它引发错误。请参阅下面: CustomerGroupRepository.php :

public function findAllGranted()
    {
        $customerGroups = $this->createQueryBuilder('cg')
            ->orderBy('cg.name', 'ASC')
        ->getQuery()->getArrayResult();

        $customerGroups = array_filter($customerGroups, function (CustomerGroup $group) {
            return $this->security->isGranted('view', $group);
        });

        return $customerGroups;
    }

以及带有 query_builder 选项的 Buildform 函数:

public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->add('email')
            ->add('firstName')
            ->add('lastName')
            ->add('isActive')
            ->add('CustomerGroup', EntityType::class, [
                'class' => CustomerGroup::class,
                'label' => 'name',
                'query_builder' => function(CustomerGroupRepository $er) {
                    return $er->findAllGranted();
                },
                'is_granted_disabled' => $options['is_granted_disabled'],
                'is_granted_attribute' => 'ROLE_ADMIN',
                'is_granted_subject_path' => 'parent.data',
                'choice_label' => 'name',
                'multiple' => false,
                'expanded' => false
            ]);
        $builder->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'onPreSetDataEntity'));
        $builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmitEntity'));
        $builder->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'onPreSetDataSite'));
        $builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmitSite'));

我得到的错误:

Argument 1 passed to App\Repository\CustomerGroupRepository::App\Repository\{closure}() must be an instance of App\Entity\CustomerGroup, array given

GroupVoter.php :


namespace App\Security\Voter;

use App\Entity\CustomerGroup;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;

class GroupVoter extends Voter
{
    private $security;

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

    protected function supports($attribute, $subject)
    {
        // replace with your own logic
        // https://symfony.com/doc/current/security/voters.html
        return in_array($attribute, ['view', 'edit'])
            && $subject instanceof CustomerGroup;
    }

    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
    {
        $user = $token->getUser();
        // if the user is anonymous, do not grant access
        if (!$user instanceof UserInterface) {
            return false;
        }

        // ... (check conditions and return true to grant permission) ...
        switch ($attribute) {
            case 'edit':
                // logic to determine if the user can EDIT
                // return true or false
                break;
            case 'view':
                return $this->canView($subject, $user);
                break;
        }

        return false;
    }

    /**
     * @param CustomerGroup $object
     * @param User $loggedUser
     * @return bool
     */
    public function canView(CustomerGroup $object, User $loggedUser)
    {
        if($this->security->isGranted('ROLE_ADMIN'))
            return true;

        elseif($this->security->isGranted('ROLE_GROUP_MANAGER'))
        {
            if($object === $loggedUser->getCustomerGroup())
                return true;
        }
        elseif($this->security->isGranted('ROLE_ENTITY_MANAGER'))
        {
            if($object === $loggedUser->getCustomerEntity()->getCustomerGroup())
                return true;
        }
        elseif($this->security->isGranted('ROLE_TECHNICIAN'))
        {
            $customerSites = $loggedUser->getCustomerSites();
            foreach ($customerSites as $site)
            {
                static $retour = false;
                if($site->getCustomerEntity()->getCustomerGroup() === $object)
                    $retour = true;
            }
            return $retour;

        }



        return false;
    }
}

UserFormType.php:


namespace App\Form;

use App\Entity\CustomerEntity;
use App\Entity\CustomerGroup;
use App\Entity\CustomerSite;
use App\Entity\User;
use App\Repository\CustomerGroupRepository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;


class UserFormType extends AbstractType
{
    private $tokenStorage;
    private $em;

    public function __construct(TokenStorageInterface $tokenStorage, EntityManagerInterface $em)
    {
        $this->tokenStorage = $tokenStorage;
        $this->em = $em;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->add('email')
            ->add('firstName')
            ->add('lastName')
            ->add('isActive')
            ->add('CustomerGroup', EntityType::class, [
                'class' => CustomerGroup::class,
                'label' => 'name',
                'is_granted_disabled' => $options['is_granted_disabled'],
                'is_granted_attribute' => 'ROLE_ADMIN',
                'is_granted_subject_path' => 'parent.data',
                'choice_label' => 'name',
                'multiple' => false,
                'expanded' => false
            ]);
        $builder->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'onPreSetDataEntity'));
        $builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmitEntity'));
        $builder->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'onPreSetDataSite'));
        $builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmitSite'));

    }

    ...

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
            'is_granted_attribute' => null,
            'is_granted_subject_path' => null,
            'is_granted_hide' => false,
            'is_granted_disabled' => false
        ]);
    }
}

Symfony 不会过滤表单中 CustomerGroup 字段中的可用选项。 即使我的角色不允许,我也可以查看所有客户组。

编辑:也许我应该使用“选择”属性。我需要访问 CustomerGroupRepository 才能做到这一点!

php forms symfony symfony4 symfony-voter
1个回答
1
投票

我已经通过在存储库中创建自定义“FindByGranted”函数来设法使其工作。 例如:

public function findAllGranted()
    {
        $customerGroups = $this->createQueryBuilder('cg')
            ->orderBy('cg.name', 'ASC')
        ->getQuery()->execute();

        $customerGroups = array_filter($customerGroups, function (CustomerGroup $group) {
            return $this->security->isGranted('view', $group);
        });
        return $customerGroups;
    }

然后我从 formType 调用这个函数

© www.soinside.com 2019 - 2024. All rights reserved.