我有特定用户拥有的帖子。我创建了一个投票者来检查用户是否拥有帖子,但我也希望管理员(即 ROLE_ADMIN 及以上)能够访问所有帖子。
我已经按照 How to Use Voters to Check User Permissions 食谱条目上的说明(并且几乎复制了代码)。现在我想知道我如何进行检查。想法:
vote
方法做一些事情。 最佳答案
这就是我想出的。基本上覆盖了父 vote()
方法,在其中添加了对角色的检查。角色检查让我有点担心,因为它没有使用任何内置方法,但我不确定它们是否可以访问,并且它不会创建循环(因为角色检查也使用投票者)。我已经标记了自定义的部分。
如果有什么是大不,请告诉我。
<?php
// src/AppBundle/Security/Authorization/Voter/PostVoter.php
namespace AppBundle\Security\Authorization\Voter;
use Symfony\Component\Security\Core\Authorization\Voter\AbstractVoter;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class PostVoter extends AbstractVoter
{
const VIEW = 'view';
const EDIT = 'edit';
/**
* {@inheritDoc}
*/
public function vote(TokenInterface $token, $object, array $attributes)
{
if (!$object || !$this->supportsClass(get_class($object))) {
return self::ACCESS_ABSTAIN;
}
// ----------------------------------
// -- start – custom
$user = $token->getUser();
if ($user instanceof UserInterface) {
if (in_array('ROLE_SUPER_ADMIN', $user->getRoles())) {
return self::ACCESS_GRANTED;
}
}
// -- end – custom
// ----------------------------------
// abstain vote by default in case none of the attributes are supported
$vote = self::ACCESS_ABSTAIN;
foreach ($attributes as $attribute) {
if (!$this->supportsAttribute($attribute)) {
continue;
}
// as soon as at least one attribute is supported, default is to deny access
$vote = self::ACCESS_DENIED;
if ($this->isGranted($attribute, $object, $token->getUser())) {
// grant access as soon as at least one voter returns a positive response
return self::ACCESS_GRANTED;
}
}
return $vote;
}
// ----------------------------------
// -- start – custom
protected function isGranted($attribute, $post, $user = null)
{
switch($attribute) {
case self::VIEW:
if ($post->getIsActive()) {
return true;
}
break;
// must be owned by the current user or the user must be a super admin
case self::EDIT:
// make sure there is a user object (i.e. that the user is logged in)
if (!$user instanceof UserInterface) {
return false;
}
if ($user->getId() === $post->getOwner()->getId()) {
return true;
}
break;
}
return false;
}
// -- end – custom
// ----------------------------------
protected function getSupportedAttributes()
{
return array(self::VIEW, self::EDIT);
}
protected function getSupportedClasses()
{
return array('AppBundle\Entity\Post');
}
}
关于php - Symfony 选民 : how do I check a user's role?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31487118/