youshido-php / GraphQLBundle

Pure PHP implementation of GraphQL Server – Symfony Bundle
MIT License
284 stars 44 forks source link

Implement security voter #58

Open PGBastien opened 7 years ago

PGBastien commented 7 years ago

The documentation talking about security https://github.com/Youshido/GraphQLBundle#using-security-voter but i get an Access denied 403 every time.

LiFeAiR commented 6 years ago

use Implement like this

class GraphQLVoter extends Voter
{
    /** @var RolesCheckerService */
    protected $rolesChecker;

    public function setRolesChecker(RolesCheckerService $rolesChecker)
    {
        $this->rolesChecker = $rolesChecker;
    }

    /**
     * {@inheritdoc}
     */
    protected function supports($attribute, $subject)
    {
        return in_array(
            $attribute,
            [
                SecurityManagerInterface::RESOLVE_FIELD_ATTRIBUTE,
                SecurityManagerInterface::RESOLVE_ROOT_OPERATION_ATTRIBUTE,
            ],
            true
        );
    }

    /**
     * {@inheritdoc}
     *
     * @param Mutation $subject
     */
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
    {
        $user = $token->getUser();

        if (! $user instanceof UserInfo) {
            return false;
        }

        if (SecurityManagerInterface::RESOLVE_FIELD_ATTRIBUTE === $attribute) {
            return true;
        }

        if (SecurityManagerInterface::RESOLVE_ROOT_OPERATION_ATTRIBUTE === $attribute) {
            return $this->rolesChecker->hasAccessTo($subject->getName());
        }

        return true;
    }
}