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?