如何解决Symfony 4 选民检查在 html.twig 中的作用
我创建了一个自定义投票者,它的名字是 CustomVoter。我想检查 html.twig 中的用户角色,如果它有我想做的事情。我的登录用户具有 CustomVoter 中指示的“CAN_REMOVE”角色。不幸的是,它不起作用或无法在 html.twig 中看到选民。有什么问题?
{% if (is_granted(constant('App\\Security\\Voter\\CustomVoter::CAN_REMOVE'))) %}
// do something
{% endif %}
<?PHP
namespace App\Security\Voter;
use App\Entity\User;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class CustomVoter extends Voter
{
const CAN_REMOVE = 'CAN_REMOVE';
/**
* @param string $attribute
* @param mixed $subject
*
* @return bool
*/
protected function supports($attribute,$subject): bool
{
if (!in_array($attribute,[self::CAN_REMOVE])) {
return false;
}
if (!$subject instanceof User) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param User $subject
* @param TokenInterface $token
*
* @return bool
*/
protected function VoteOnAttribute($attribute,$subject,TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
switch ($attribute) {
case self::CAN_REMOVE:
return !empty(array_intersect([UserVoter::ROLE_SUPER_ADMIN,self::CAN_REMOVE],$user->getRoles()));
break;
}
return false;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。