Skip to content

Instantly share code, notes, and snippets.

@simshaun
Created March 31, 2014 18:37
Show Gist options
  • Save simshaun/9899129 to your computer and use it in GitHub Desktop.
Save simshaun/9899129 to your computer and use it in GitHub Desktop.
Example Symfony2 security voter
<?php
namespace S2\AppBundle\Security\Voter;
use FOS\UserBundle\Model\UserInterface;
use JMS\DiExtraBundle\Annotation as DI;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
/**
* @DI\Service("s2.security.admin_bar_voter")
* @DI\Tag("security.voter")
*/
class AdminBarVoter implements VoterInterface
{
public function supportsAttribute($attribute)
{
return $attribute == 'VIEW_ADMIN_BAR';
}
public function supportsClass($class)
{
return true;
}
public function vote(TokenInterface $token, $object, array $attributes)
{
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return VoterInterface::ACCESS_DENIED;
}
foreach ($attributes as $attribute) {
if (!$this->supportsAttribute($attribute)) {
continue;
}
foreach ($user->getRoles() as $role) {
if (stripos($role, '_ADMIN') !== false) {
return VoterInterface::ACCESS_GRANTED;
}
}
}
return VoterInterface::ACCESS_ABSTAIN;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment