【问题标题】:Check specific user permission in a twig view在树枝视图中检查特定用户权限
【发布时间】: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-&gt;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,那么我无法通过这种方式找到他。
  • 这个问题不是标记问题的重复。我希望根据角色层次结构检查用户不是当前用户的权限。
  • 这能回答你的问题吗? Get ROLE of a user not logged in TWIG Symfony2

标签: php symfony


【解决方案1】:

您可以使用RoleHierarchy 类查找当前用户的所有“可访问”角色。

在 Symfony 框架中,此类可用作 security.role_hierarchy 服务(可自动装配为 Symfony\Component\Security\Core\Role\RoleHierarchyInterface)。

// check for ROLE_STAFF while taking the role hierarchy into account
$isStaff = in_array(
    'ROLE_STAFF',
    $roleHierarchy->getReachableRoles($user->getRoles())
);

您可以写a custom Twig extension (e.g. a custom Twig test) 以便能够在您的模板中执行此操作。

【讨论】:

  • 谢谢。我想我是对的,然后我将不得不编写我的 TWIG 扩展。我想知道为什么它没有包含在框架中,它看起来很基础。
  • 警告:RoleHierarchyInterface 中的方法名称在 Symfony 5.0.7 中是 getReachableRoleNames 而不是 getReachableRoles
猜你喜欢
  • 2016-01-10
  • 1970-01-01
  • 2015-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多