问题描述
我创建了一个自定义投票者,它的名字是 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 (将#修改为@)