授予其他用户

sma*_*erx 6 symfony

在我阅读了食谱中的这一章之后

http://symfony.com/doc/current/cookbook/security/entity_provider.html

我创建了一个实现“AdvancedUserInterface”的实体“User”和一个实现“RoleInterface”的实体“Roles”。我还在“security.yml”中创建了一个角色结构。

用户和角色之间的关系是“多对多”关系。

一切安好。

对于登录用户,我可以检查这样的授权:

$this->get('security.context')->isGranted("ROLE_EDITOR");
Run Code Online (Sandbox Code Playgroud)

但是如何检查数据库中其他用户的此授权?

有像吗?

$this->get('security.context')->isGranted("ROLE_EDITOR", $user);
Run Code Online (Sandbox Code Playgroud)

leb*_*cht 1

不知道现在是否有内置的东西,但构建起来非常简单:

class RoleCheckerService
{
    private const PROVIDER_KEY = 'role-check';
    /**
     * @var RoleHierarchyInterface
     */
    private $roleHierarchy;

    public function __construct(RoleHierarchyInterface $roleHierarchy)
    {
        $this->roleHierarchy = $roleHierarchy;
    }

    final public function isGranted(User $user, string $role): bool 
    {
        $token = new PreAuthenticatedToken($user, null, self::PROVIDER_KEY, $user->getRoles());
        $reachableRoles = $this->roleHierarchy->getReachableRoles($token->getRoles());

        foreach ($reachableRoles as $reachableRole) {
            if ($reachableRole->getRole() === $role) {
                return true;
            }
        }

        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)