11

if I have the current user object, how can i get a list of all of the permissions he has in drupal 8 custom module ? I dont want to check for one particular permission which would be $current_user->hasPermission("permission_name").

I want to get the entire list of his permissions.

thanks

1 Answer 1

20

Can you try the following snippet:

$user = \Drupal::currentUser();
$user_roles = $user->getRoles();
$roles_permissions = user_role_permissions($user_roles);

This will give you permissions grouped by roles. But most likely you want them in one array.

Therefore you can use this

$final_array = array();
foreach ($roles_permissions as $role_key => $permissions) {
  foreach ($permissions as $permission) {
    $final_array[] = $permission;
  }
}

In case you want to load different user than the currently logged-in user, you can use

$some_user = \Drupal\user\Entity\User::load(123);

Where 123 stands for the user id. For more information:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Entity.php/function/Entity%3A%3Aload/8.2.x

Best regards,

Oleg

2
  • This will get the current logged in user, not any user. But, in theory the script/snippet could be modified to load a specific user by their id and then view the role permissions they have.
    – tenken
    Commented Mar 13, 2017 at 14:27
  • Yes @tenken, you are correct. I saw in the question $current_user, so I assumed we are talking about the currently logged in user. #TODO, add a script for loading different user. Commented Mar 13, 2017 at 14:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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