Skip to content

9.3. Custom field access control

Pierre Rudloff edited this page Oct 5, 2022 · 2 revisions

The following document is for RESTful version 1.x.

Public fields defined in an entity resource may specify one or more access_callbacks which determine whether the field should be exposed in the request response.

Note that resources which extend the RestfulDataProviderDbQuery class do not inherit this functionality.

Example use case

I want to hide a field for a certain group of roles (Group A). There is another group of roles (Group B) that will be allowed if the user has an email address from the organization. Group C is always allowed.

Implementation:

'access_callbacks' => array(
    array($this, 'fieldRoleAccess'),
    array(array($this, 'checkEmailDomain'), array('drupal.org')),
  ),
  …
public function fieldRoleAccess(\EntityMetadataWrapper $property_wrapper, $op, \EntityMetadataWrapper $wrapper) {
  $account = $this->getUser();
  if (is_allowed_role($account)) {
    return \RestfulInterface::ACCESS_ALLOW;
  }
  if (is_semi_trusted_role($account)) {
    return \RestfulInterface::ACCESS_IGNORE;
  }
  return \RestfulInterface::ACCESS_DENY;
}

public function fieldDomainAccess(\EntityMetadataWrapper $property_wrapper, $op, \EntityMetadataWrapper $wrapper, $access, $domain) {
  if ($access == \RestfulInterface::ACCESS_IGNORE) {
    return check_domain($this->getUser(), $domain) ? \RestfulInterface::ACCESS_ALLOW : \RestfulInterface::ACCESS_DENY;
  }
  return $access;
}

Group A: DENY, DENY
Group B: IGNORE, GRANT | DENY
Group C: GRANT, GRANT

Clone this wiki locally