Skip to content

Commit fe36cb3

Browse files
authored
Update 4. Utilize ACL to set menu items and permissions.md
1 parent bce3197 commit fe36cb3

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

6. Developing with Adminhtml/4. Utilize ACL to set menu items and permissions.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,66 @@ menu.xml - `urn:magento:module:Magento_Backend:/etc/menu.xsd` - flat structure
2929
- System > Permissions > All Users to view and create new users and associate to a role. There are two tabs 1 is user info the other is User Role where you define the Role for this user. You can only select 1 role per user.
3030

3131
*How can you do that programmatically?*
32+
- You can leverage \Magento\Authorization\Model\Acl\AclRetriever. That as a few methods that will help
33+
34+
```php
35+
/**
36+
* Get a list of available resources using user details
37+
*
38+
* @param string $userType
39+
* @param int $userId
40+
* @return string[]
41+
* @throws AuthorizationException
42+
* @throws LocalizedException
43+
*/
44+
public function getAllowedResourcesByUser($userType, $userId)
45+
{
46+
if ($userType == UserContextInterface::USER_TYPE_GUEST) {
47+
return [self::PERMISSION_ANONYMOUS];
48+
} elseif ($userType == UserContextInterface::USER_TYPE_CUSTOMER) {
49+
return [self::PERMISSION_SELF];
50+
}
51+
try {
52+
$role = $this->_getUserRole($userType, $userId);
53+
if (!$role) {
54+
throw new AuthorizationException(
55+
__('We can\'t find the role for the user you wanted.')
56+
);
57+
}
58+
$allowedResources = $this->getAllowedResourcesByRole($role->getId());
59+
} catch (AuthorizationException $e) {
60+
throw $e;
61+
} catch (\Exception $e) {
62+
$this->logger->critical($e);
63+
throw new LocalizedException(
64+
__(
65+
'Something went wrong while compiling a list of allowed resources. '
66+
. 'You can find out more in the exceptions log.'
67+
)
68+
);
69+
}
70+
return $allowedResources;
71+
}
72+
73+
/**
74+
* Get a list of available resource using user role id
75+
*
76+
* @param string $roleId
77+
* @return string[]
78+
*/
79+
public function getAllowedResourcesByRole($roleId)
80+
{
81+
$allowedResources = [];
82+
$rulesCollection = $this->rulesCollectionFactory->create();
83+
$rulesCollection->getByRoles($roleId)->load();
84+
$acl = $this->aclBuilder->getAcl();
85+
/** @var \Magento\Authorization\Model\Rules $ruleItem */
86+
foreach ($rulesCollection->getItems() as $ruleItem) {
87+
$resourceId = $ruleItem->getResourceId();
88+
if ($acl->has($resourceId) && $acl->isAllowed($roleId, $resourceId)) {
89+
$allowedResources[] = $resourceId;
90+
}
91+
}
92+
return $allowedResources;
93+
}
94+
```

0 commit comments

Comments
 (0)