Score:0

Add access to a single node programatically via ACL module

ng flag

I spent a day trying to figure out why my code doesn't work. I'm trying to add access to a user on a single node programmatically. It saves record in DB and when I visit Access control page for a given node, user is listed under USER ACCESS CONTROL LISTS. However, when I visit the node as that user, I get access denied. I tried all sorts of combinations but my current code is something like this:

$node,$account = 'comes from previous logic, .irrelevant...';
$acl_id = content_access_get_acl_id($node, 'view');

$connection = Database::getConnection();
//check record exists!
$result = $connection->select('acl_user', 'au')
->fields('au')
->condition('au.acl_id', $acl_id)
->condition('au.uid', $account->id())
->execute();
$rows = $result->fetchAll();
if(empty($rows)) {
 $connection->insert('acl_user')
  ->fields([
  'acl_id' => $acl_id,
  'uid' => $account->id(),
 ])->execute();

 $settings = content_access_get_per_node_settings($course_node);
 //dpm($settings,'settings');
\Drupal::entityTypeManager()->getAccessControlHandler('node')->writeGrants($node);
\Drupal::moduleHandler()->invokeAll('user_acl', $settings);

$grants = \Drupal::moduleHandler()->invokeAll('node_access_records', [$node]);
\Drupal::moduleHandler()->alter('node_access_records', $grants, $node);


$node->save();
if(node_access_needs_rebuild()) {
  node_access_rebuild();
  node_access_needs_rebuild(FALSE);
}

foreach (Cache::getBins() as $cache_backend) {
  $cache_backend->deleteAll();
}

Any feedback?

Kevin avatar
in flag
This is all custom code? No contributed module?
ng flag
The above code is all custom however the base functionality comes from acl module. It works via administration interface but I need to add or remove access programmatically in custom code. I think I'm bypassing some kind of hook that causes my issues.
Kevin avatar
in flag
It doesn't show how this code is called
ng flag
It's called from a controller but I don't think it's important where is it called from.
Kevin avatar
in flag
It is important if it isn't working.
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.