You are here

function userprotect_entity_field_access in User protect 8

Implements hook_entity_field_access().

If the field in question is a field on the user entity, protection rules are checked to verify if access to edit the field is allowed.

See also

userprotect_user_access()

File

./userprotect.module, line 121
Allows admins to protect users from being edited or cancelled.

Code

function userprotect_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemList $items = NULL) {
  if (is_null($items)) {

    // Sometimes no field item list is passed. In this case, there is nothing
    // for userprotect to check.
    return AccessResult::neutral();
  }
  if ($operation != 'edit') {

    // Field access checks are limited to the edit operation.
    return AccessResult::neutral();
  }
  if ($field_definition
    ->getTargetEntityTypeId() != 'user') {

    // Access checks are only performed on user entities.
    return AccessResult::neutral();
  }

  // Get entity for which field access is checked.
  $entity = $items
    ->getEntity();
  if ($entity
    ->isNew()) {

    // Access checks are only performed on existing users.
    return AccessResult::neutral();
  }

  // Check access based on the field's name.
  $name = $field_definition
    ->getName();
  switch ($name) {
    case 'name':
    case 'mail':
    case 'pass':
    case 'status':
    case 'roles':

      // User protect defines each protection as an operation on the entity. See
      // userprotect_user_access().
      $entity_operation = 'user_' . $name;
      return $entity
        ->access($entity_operation, $account) ? AccessResult::neutral() : AccessResult::forbidden();

    // Make sure this module also works when role_delegation is enabled.
    case 'role_change':
      $entity_operation = 'user_roles';
      return $entity
        ->access($entity_operation, $account) ? AccessResult::neutral() : AccessResult::forbidden();
  }

  // The field is not one of the fields that userprotect supports.
  return AccessResult::neutral();
}