You are here

function administerusersbyrole_query_administerusersbyrole_edit_access_alter in Administer Users by Role 8.2

Same name and namespace in other branches
  1. 8.3 administerusersbyrole.module \administerusersbyrole_query_administerusersbyrole_edit_access_alter()

Implements hook_query_TAG_alter().

Modifies the user listing results to exclude user accounts that the logged in user does not have permission to modify.

File

./administerusersbyrole.module, line 137

Code

function administerusersbyrole_query_administerusersbyrole_edit_access_alter(AlterableInterface $query) {
  $account = \Drupal::currentUser();

  // The tag administerusersbyrole_edit_access is used to indicate that we
  // should filter out users where there isn't edit access.
  if (!$account
    ->hasPermission('administer users')) {

    // Exclude the root user.
    $query
      ->condition('users_field_data.uid', 1, '<>');
    $roles = user_roles(TRUE);
    foreach ($roles as $rid => $role) {
      if (!$account
        ->hasPermission(_administerusersbyrole_build_perm_string($rid, 'edit'))) {
        $exclude[$rid] = $rid;
      }
    }

    // Exclude accounts with no roles if the user does not have permission
    // to edit them.
    if (isset($exclude[RoleInterface::AUTHENTICATED_ID])) {
      $query
        ->Join('user__roles', 'ur', 'ur.entity_id=users_field_data.uid');
      unset($exclude[RoleInterface::AUTHENTICATED_ID]);
    }

    // Hide any user accounts that the user does not have permission to edit.
    // If an account has multiple roles, we make sure the current user has
    // permission to edit all assigned roles.
    if (!empty($exclude)) {

      // This code was changed from D7 to workaround D8 core bug https://www.drupal.org/node/2744069.
      // Get a list of uids with roles that the user does not have permission
      // to edit.
      $subquery = \Drupal::database()
        ->select('user__roles', 'ur2');
      $subquery
        ->fields('ur2', array(
        'entity_id',
      ));
      $subquery
        ->condition('ur2.roles_target_id', $exclude, 'IN');

      // Exclude those uids from the result list.
      $query
        ->condition('users_field_data.uid', $subquery, 'NOT IN');
    }
  }
}