Score:0

Restrict access to specific node by role

jp flag

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?

Kevin avatar
in flag
You should use one of the various access control modules instead
in flag
Sounds like you want https://www.drupal.org/project/nodeaccess
Asatur Vardanyan avatar
jp flag
Thanks a lot for the suggestions. I have fixed it with grants. I have forgotten to rebuild permissions.
jbarrio avatar
cn flag
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.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.