8000 [DX] Provide an easy way to check if a user has a security role · Issue #14048 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content
[DX] Provide an easy way to check if a user has a security role #14048
Closed
@javiereguiluz

Description

@javiereguiluz

The problem

As many of you know, the getRoles() method of the UserInterface doesn't take into account the role hierarchy that you may have defined in your application.

That's why usually you must end up with a code similar to the following:

use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
use Symfony\Component\Security\Core\User\UserInterface;

private $roleHierarchy;

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

private function userHasRole(UserInterface $user, $roleName)
{
    if (null === $this->roleHierarchy) {
        return in_array($roleName, $user->getRoles(), true);
    }

    foreach ($this->roleHierarchy->getReachableRoles($user->getRoles()) as $role) {
        if ($roleName === $role->getRole()) {
            return true;
        }
    }

    return false;
}

The solution

The obvious solution would be to provide a method such as ->hasRole(string $role_name). What do you think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0