Robert W. Hunter
Robert W. Hunter

Reputation: 3003

Symfony2 voters for entire entity permissions

We are setting up Roles in our platform, some of this roles (ROLE_VISITOR, ROLE_REGISTERED) have permissions

CREATE_BLOG_POST, CREATE_BLOG_COMMENT

Theese permissions can be true or false, but as we don't want them as new Roles, but permissions, we should use Voters. An user can also have both permissions, or none.

We want to allow/disallow our users to create a blog post or a blog comment, whenever they are allowed or not, but as Voters works on individual items from an entity (Owner or not owner), I don't know how to continue.

We want total control over CRUD for an entire entity depending on the permission.

I am not showing any of my code because I've tried only what DOC says...http://symfony.com/doc/2.8/cookbook/security/voters.html but I would like some advice or example code in order to achieve this.

I hope I've explained everything.

Upvotes: 0

Views: 500

Answers (1)

Alsatian
Alsatian

Reputation: 3135

Here you have an example without other entity :

<?php
namespace AppBundle\Voters;

use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class BlogVoter  implements VoterInterface
{
    const CREATE_BLOG_COMMENT = 'create_blog_comment';   
    const CREATE_BLOG_POST = 'create_blog_post';     

    public function vote(TokenInterface $token, $object, array $attributes)
    {    
        $user = $token->getUser();

        $supports = false;
        foreach($attributes as $attribute){
            if(in_array($attribute,array(self::CREATE_BLOG_COMMENT,self::CREATE_BLOG_POST))){
                $supports = true;
            }
        }

        if(!$supports){
            return self::ACCESS_ABSTAIN;
        }

        if ($user instanceof UserInterface) {
            $roles = $user->getRoles();

            switch($attribute) {
                case self::CREATE_BLOG_COMMENT:
                    if(in_array('ROLE_VISITOR',$roles)|| in_array('ROLE_REGISTERED',$roles)){
                        return self::ACCESS_GRANTED;
                    }
                break;
                case self::CREATE_BLOG_POST:
                    if(in_array('ROLE_REGISTERED',$roles)){
                        return self::ACCESS_GRANTED;
                    }
                break;
            }
        }

        return self::ACCESS_DENIED;
    }
}

Upvotes: 1

Related Questions