phpformssymfonysymfony4symfony-voter

How to filter EntityType Field with Voter


I need to filter options displayed in an EntityType Field with Voters.

I have a User Entity which has some relations to CustomerGroup, CustomerEntity and CustomerSite. I have a Voter on, for example, Customer Group. I can filter the results depending on the current user's Role in a list view. I use an 'array_filter' function to make it work. Example on User Object :

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

I've googled a lot of pages without any success ! I tried to create a custom function in the CustomerGroupRepository and call it from the query_builder option in FormType : it throws an error. See just below : 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;
    }

And the Buildform function with the query_builder option :

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'));

The Error I get :

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

The 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;
    }
}

The 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
        ]);
    }
}

The options available in CustomerGroup field in the form are not filtered by Symfony. I can see all CustomerGroups even if my ROLE doesn't allow them.

EDIT : Maybe I should use the 'choises' attribute. I need to access the CustomerGroupRepository to do that !


Solution

  • I've managed to make it works by making a custom "FindByGranted" function in a repository. Fo example :

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

    I then call this function from the formType