【发布时间】:2020-04-09 01:28:36
【问题描述】:
在我的 Symfony 5 项目的 TWIG 视图中,我有以下代码:
<table class="table table-hover table-striped datatable">
<thead>
<tr>
<th>ID</th>
<th>Username</th>
<th>Email</th>
<th>Created at</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td>{{ user.createdAt|date('d/m/Y H:i') }}</td>
</tr>
{% endfor %}
</tbody>
</table>
没有什么令人印象深刻的。我想知道是否有办法检查我的循环中的user 是否具有特定角色,比如说ROLE_STAFF(更准确地说,我想根据层次结构检查它。如果他有一个“继承"ROLE_STAFF,也应该满足条件)。我见过this post,但它已经很老了,我希望从它写出来的那一刻起就已经实现了一些东西。
我尝试在我的User 实体中注入AccessDecisionManagerInterface,但没有任何好的结果。我的方法(此后)不起作用,因为$this->decisionManager 为空。我猜它没有正确注入。我通过构造函数注入它:
public function __construct(AccessDecisionManagerInterface $decisionManager)
{
$this->decisionManager = $decisionManager;
}
public function hasRolePermissions(string $role)
{
$decisionManager = new AccessDecisionManager();
$token = new UsernamePasswordToken($this, '', '', $this->getRoles());
return $this->decisionManager->decide($token, [$role]);
}
虽然我完全可以接受不使用isGranted 的解决方案,例如服务或注入,但我更愿意保持简单。我打算建立一个树枝功能,但我想知道我是否在重新发明轮子。这似乎是一个很常见的问题,所以我希望有一些我不知道的内置功能。
【问题讨论】:
-
如果这是一个简单的检查,不涉及授权并且您没有进行角色继承,为什么不检查
user.roles中的角色数组? -
问题在于它涉及层次结构。如果用户有 ROLE_ADMIN(继承自 ROLE_STAFF)但没有 ROLE_STAFF,那么我无法通过这种方式找到他。
-
这个问题不是标记问题的重复。我希望根据角色层次结构检查用户不是当前用户的权限。