New Voter implements VoterInterface

Publié le par Jordan Samouh

When we call the method isGranted in Symfony2, it checks if the current user can access to a page or an object with a mask defined. (ACL/ROLE)
These checking are made by Voter class implemented by the VoterInterface of Symfony2.
All we need to do is to define a new voter class to do some other checkings like some treatments when the user is granted or not, blocks.authorizes a user according his IP….
At first we need to declare a new Voter class:


class MVMVoter implements VoterInterface

{
/**

* Checks if the voter supports the given attribute.

* @param string $attribute An attribute

* @return Boolean true if this Voter supports the attribute, false otherwise

*/

function supportsAttribute($attribute)

{

return true;

}

 

/**

* Checks if the voter supports the given class.

* @param string $class A class name

* @return true if this Voter can process the class

*/

function supportsClass($class)

{

return true;

}

 

/**

* Returns the vote for the given parameters.

*

* This method must return one of the following constants:

* ACCESS_GRANTED, ACCESS_DENIED, or ACCESS_ABSTAIN.

*

* @param TokenInterface $token      A TokenInterface instance

* @param object         $object     The object to secure

* @param array          $attributes An array of attributes associated with the method being invoked

* @return integer either ACCESS_GRANTED, ACCESS_ABSTAIN, or ACCESS_DENIED

*/

function vote(TokenInterface $token, $object, array $attributes)

{

return self::ACCESS_ABSTAIN;

}

Then, we need to create a new service to tag this class as a voter security class

<parameter   key="mvm.voter.class">MVM\MainBundle\Acl\MVMVoter</parameter>

<service id="mvm.voter"  >

<tag name="security.voter"></tag>

</service>

As you can see the VoterClass has a method named vote

This method will be called each time there is a check acl/permission.

Cette entrée a été publiée dans Symfony 2 Utils. Vous pouvez la mettre en favoris avec ce permalien.



2 réponses à New Voter implements VoterInterface

  1. cordoval dit :

    does not make sense why your class just denies access, class MVMVoter implements VoterInterface

    you could have point to the cookbook entry on the documentation for more reference.

    • Jordan Samouh dit :

      Yes of course, it is for example :-)
      In the vote method you do your own logic code.
      For example, if you want to access denied for a list of IPS, do the code here

      Jordan

Répondre à cordoval Annuler la réponse.

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*


3 * two =

Vous pouvez utiliser ces balises et attributs HTML : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>