Created
March 31, 2014 18:37
-
-
Save simshaun/9899129 to your computer and use it in GitHub Desktop.
Example Symfony2 security voter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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