Skip to content

Instantly share code, notes, and snippets.

@Swop
Created July 2, 2013 23:16
Show Gist options
  • Save Swop/5914086 to your computer and use it in GitHub Desktop.
Save Swop/5914086 to your computer and use it in GitHub Desktop.
<?php
namespace Foo\BarBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class ArticleController extends Controller
{
public function editAction(Article article)
{
if (false === $securityContext->isGranted('ROLE_ARTICLE_EDIT', $article) {
throw new AccessDeniedHttpException();
}
// Access granted
}
}
<?php
namespace Foo\BarBundle\Security;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class OwnerVoter implements VoterInterface
{
public function supportsAttribute($attribute)
{
return 1 === preg_match('/^ROLE_ARTICLE_/', $attribute);
}
public function supportsClass($class)
{
return true;
}
public function vote(TokenInterface $token, $object, array $attributes)
{
$vote = VoterInterface::ACCESS_ABSTAIN;
foreach ($attributes as $attribute) {
if (false === $this->supportsAttribute($attribute)) {
continue;
}
$user = $token->getUser();
$vote = VoterInterface::ACCESS_DENIED;
// Check if the current user is the auhtor of the article
if ($object->getAuthor()->getId() === $user->getId()) {
$vote = VoterInterface::ACCESS_GRANTED;
}
}
return $vote;
}
}
# Administrators can edit any articles
security:
role_hierarchy:
ROLE_ADMIN:
- ROLE_USER
- ROLE_ARTICLE_EDIT
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<parameters>
<parameter key="foo.bar.security.ownervoter.class">Foo\BarBundle\Security\OwnerVoter</parameter>
</parameters>
<services>
<service id="foo.bar.security.ownervoter" class="%foo.bar.security.ownervoter.class%" public="false">
<tag name="security.voter" />
</service>
</services>
</container>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment