Dynamically adding roles to a user

后端 未结 2 1850
孤独总比滥情好
孤独总比滥情好 2020-12-13 20:58

We are using Symfony2\'s roles feature to restrict users\' access to certain parts of our app. Users can purchase yearly subscriptions and each of our User enti

2条回答
  •  生来不讨喜
    2020-12-13 21:49

    I think you would do better setting up a custom voter and attribute.

    /**
     * @Route("/whatever/")
     * @Template
     * @Secure("SUBSCRIPTION_X")
     */
    public function viewAction()
    {
        // etc...
    }
    

    The SUBSCRIPTION_X role (aka attribute) would need to be handled by a custom voter class.

    class SubscriptionVoter implements VoterInterface
    {
        private $em;
    
        public function __construct($em)
        {
            $this->em = $em;
        }
    
        public function supportsAttribute($attribute)
        {
            return 0 === strpos($attribute, 'SUBSCRIPTION_');
        }
    
        public function supportsClass($class)
        {
            return true;
        }
    
        public function vote(TokenInterface $token, $object, array $attributes)
        {
            // run your query and return either...
            //  * VoterInterface::ACCESS_GRANTED
            //  * VoterInterface::ACCESS_ABSTAIN
            //  * VoterInterface::ACCESS_DENIED
        }
    }
    

    You would need to configure and tag your voter:

    services:
        subscription_voter:
            class: SubscriptionVoter
            public: false
            arguments: [ @doctrine.orm.entity_manager ]
            tags:
                - { name: security.voter }
    

提交回复
热议问题