0

I am working on a Drupal 9 project. I need to restrict access to the node with id 1083 for "delegate" user role. For this I have used hook_node_access_records() and hook_node_grants():

/**
 * Implements hook_node_access_records().
 */
function wtotfaf_user_node_access_records(NodeInterface $node) {
  $grants = [];
  if ($node->id() == 1083) {
    $grants[] = [
      'realm' => 'delegate_view_activity_tracker',
      // The naming of the realm is up to you.
      'gid' => 12,
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
    ];
    $grants[] = [
      'realm' => 'administrator_view_activity_tracker',
      // The naming of the realm is up to you.
      'gid' => 11,
      'grant_view' => 1,
      'grant_update' => 1,
      'grant_delete' => 1,
    ];
    $grants[] = [
      'realm' => 'editor_view_activity_tracker',
      // The naming of the realm is up to you.
      'gid' => 13,
      'grant_view' => 1,
      'grant_update' => 1,
      'grant_delete' => 1,
    ];
  }
  return $grants;
}

/**
 * Implements hook_node_grants().
 */
function wtotfaf_user_node_grants($account, $op) {
  $grants = [];
  $roles = $account->getRoles();
  if (in_array('administrator', $roles)) {
    $grants['administrator_view_activity_tracker'] = [11];
  }
  elseif (in_array('delegate', $roles)) {
    $grants['delegate_view_activity_tracker'] = [12];
  }
  elseif (in_array('editor', $roles)) {
    $grants['editor_view_activity_tracker'] = [13];
  }
  return $grants;
}

In db I have this: enter image description here

Node with id 251 is not available for other roles after my changes. What is wrong with the code? How can I restrict access for the 'delegate' user role only for the node id 1083?

4
  • 4
    You should use one of the various access control modules instead
    – Kevin
    Oct 28 '21 at 15:36
  • 4
    Sounds like you want drupal.org/project/nodeaccess
    – Joseph
    Oct 28 '21 at 15:47
  • Thanks a lot for the suggestions. I have fixed it with grants. I have forgotten to rebuild permissions. Oct 29 '21 at 16:25
  • I'd personally rely on hook_node_access() which will bring you the entity, the operation and the Account Interface. Based on that I'd do my return and I would call cachePerPermissions() to ensure this doesn't slow down anything.
    – jbarrio
    Nov 1 '21 at 18:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.