6

Searching the answer for How to get user permissions for the role Administrator? I found that if you try to get the permissions for the admin user you will get an empty array.

From Role::getPermissions():

  /**
   * Returns a list of permissions assigned to the role.
   *
   * @return array
   *   The permissions assigned to the role.
   */
  public function getPermissions() {
    if ($this->isAdmin()) {
      return [];
    }
    return $this->permissions;
  }

But if the admin user have all the permissions why Drupal just return an empty array?

3
  • 1
    Does this happen for "super admin" (user 1) only? or does this still happen even for other "admins" (admins that are not user 1) ?
    – No Sssweat
    Apr 7, 2017 at 3:16
  • 1
    @NoSssweat I haven't test it but I think that is for all the admin users public function isAdmin() { return (bool) $this->is_admin; } Apr 7, 2017 at 3:35
  • 1
    @NoSssweat It happens for all the users having the role that in admin/config/people/accounts you set as Administrator role.
    – apaderno
    Apr 7, 2017 at 4:59

1 Answer 1

7

That is because a role that is marked with is_admin (which from the UI is possible for just a single role) has all the permissions. Consider it as an extension of the user #1 concept; the difference is that there is just a user #1, but there could be many users assigned to the role marked as is_admin.
In fact, the code does the same it does for the user #1: It explicitly checks for the role being is_admin. So, returning an array of permissions that will never be used doesn't make sense. See Role::hasPermission().

  if ($this->isAdmin()) {
    return TRUE;
  }
  return in_array($permission, $this->permissions);

Similar code is present in other functions/methods, for example Role::revokePermission().

  if ($this->isAdmin()) {
    return $this;
  }
  $this->permissions = array_diff($this->permissions, array($permission));
  return $this;

As for why Drupal uses that code, it is because from the UI it is possible to change which role is marked as is_admin, including one for which permissions were already set. Once it is marked is_admin, the permissions explicitly set can be ignored, but they are kept, just in case you change from the UI the role marked as is_admin. In such case, you would not want to set again the permissions you set for the old is_admin role.

1
  • makes sense, and interesting think about the permissions, thanks kiam. Apr 7, 2017 at 13:29

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.