3

In Magento 2, you can create access control rules for admin users at

System -> User Roles

As a backend Magento programmer, how can you check which rules the currently logged in admin user has assigned? i.e. which object(s) do you need to inject, and which methods do you need to call on them?

1

\Magento\Backend\Model\Auth\Session should give you the current user that is an instance of \Magento\User\Model\User.
From this user, getRole should give you the role that is an instance of \Magento\Authorization\Model\Role.
\Magento\Authorization\Model\Acl\AclRetriever contains a method getAllowedResourcesByRole that receives a parameter $rid (role id).
I didn't test this, but I think you can combine the 2 above into this:

protected $aclRetriever;
protected $authSession;
public function __construct(
    ....
    \Magento\Authorization\Model\Acl\AclRetriever $aclRetriever,
    \Magento\Backend\Model\Auth\Session $authSession, 
    ....
) {
    ....
    $this->aclRetriever = $aclRetriever;
    $this->authSession = $authSession;
    ....
}

then have a method like this:

public function getAllowedResources()
{
    $user = $this->authSession->getUser();
    $role = $user->getRole();
    $resources = $this->aclRetriever->getAllowedResourcesByRole($role->getId());
    return $resources;
}

if the current user has access everywhere you should get an array with only one element Magento_Backend::all.
If you have custom access for the current user you should get an array with elements that look like this [Namespace]_[Module]::[resource]_[subresource]. Basically, the id attributes of the resource tags you have in the acl.xml files.

1

Use Magento\Framework\Authorization\PolicyInterface

Please find the example of usage at \Magento\Framework\Authorization::isAllowed

    $resourceString = "[Namespace]_[Module]::[resource]_[subresource]"; 
    //example "Magento_Backend::admin"
    $roleId = $user->getAclRole();
    return $this->aclPolicy->isAllowed($roleId, $resourceString);
0

Because of the accepted answer's statements "I didn't test this", and "should", let me put in some test results here.

The $resources variable will be an array of strings. I made a slightly different function myself:

public function getIsAllowed($resource) { // like a string, e.g. "Magento_Backend::cache" for Cache Management
    $role = $this->authSession->getUser()->getRole();
    $resources = $this->aclRetriever->getAllowedResourcesByRole($role->getId());
    return in_array($resource, $resources) or in_array("Magento_Backend::all", $resources);
}

which allows for easier checks - as you'll probably want to do a membership check with a special case for Magento_Backend::all anyway.

Constructing the block like the accepted answer will work straight away.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.