0

i created a custom voter it's name CustomVoter. I want to check user role in html.twig and if it has role i want to do something. My logged user has 'CAN_REMOVE' role that indicated in CustomVoter. Unfortunately it is not working or cannot see voter in html.twig. What is the problem?

{% if (is_granted(constant('App\\Security\\Voter\\CustomVoter::CAN_REMOVE'))) %}
  // do something
{% endif %}

<?php
    namespace App\Security\Voter;
    
    use App\Entity\User;
    use Symfony\Component\Security\Core\User\UserInterface;
    use Symfony\Component\Security\Core\Authorization\Voter\Voter;
    use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
    
    class CustomVoter extends Voter
    {
        const CAN_REMOVE = 'CAN_REMOVE';
    
        /**
         * @param string $attribute
         * @param mixed  $subject
         *
         * @return bool
         */
        protected function supports($attribute, $subject): bool
        {
            if (!in_array($attribute, [self::CAN_REMOVE])) {
                return false;
            }
    
            if (!$subject instanceof User) {
                return false;
            }
    
            return true;
        }
    
        /**
         * @param string         $attribute
         * @param User           $subject
         * @param TokenInterface $token
         *
         * @return bool
         */
        protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
        {
            $user = $token->getUser();
            if (!$user instanceof UserInterface) {
                return false;
            }
    
            switch ($attribute) {
                case self::CAN_REMOVE:
                    return !empty(array_intersect([UserVoter::ROLE_SUPER_ADMIN, self::CAN_REMOVE], $user->getRoles()));
                    break;
            }
    
            return false;
        }
    }
  • 2
    _"Not working"_ is not a helpful description of the problem - there are several points that can go wrong. Have you tried debugging the issue? The first step would be dumping something from the `supports` method to see if your custom voter is even triggered. If it is, then you'd have to establish what `supports` returns. If it returns true, then you move on to debugging `voteOnAttribute`. – El_Vanja Feb 25 '21 at 10:34
  • @El_Vanja I got my problem where is thanks for your opinion. In supports method i check subject is user and it returns false because of i do not send any user object from html.twig. İf i use like this is_granted(constant('App\\Security\\Voter\\CustomVoter::CAN_REMOVE'), app.user)) it works : ) – Erdem Nayir Feb 25 '21 at 13:50

0 Answers0