Reference-based user access restrictions in Drupal 8

Created on 23 January 2016, almost 9 years ago
Updated 5 April 2023, over 1 year ago

If anybody is trying to achieve this in Drupal 8, then here's a custom module you can tweak according to your needs. This implementation grants access to the node ONLY IF the logged in user is referenced through the field attached to the node, all other users are denied access.

user_access_restrictions.info.yml

name: User access restrictions
description: Restricts access to CONTENT_TYPE nodes if user is not referenced.
package: Custom

type: module
core: 8.x

user_access_restrictions.module

use Drupal\Core\Access\AccessResult;

function user_access_restrictions_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {
  if ($node->bundle() == 'CONTENT_TYPE') {
    $users = $node->get('REFERENCE_FIELD_NAME')->getValue();
    if (!empty($users)) {
      foreach ($users as $user) {
        if ($user['target_id'] == $account->id()) {
          return AccessResult::allowed()->cachePerUser()->cacheUntilEntityChanges($node);
        }
      }
    }
    return AccessResult::forbidden()->cachePerUser()->cacheUntilEntityChanges($node);
  }
  return AccessResult::neutral();
}

Notes: CONTENT_TYPE signifies the content type machine name that has the reference field in question, REFERENCE_FIELD_NAME signifies the machine name of the user referencing field (e.g. "field_user_reference").

🌱 Plan
Status

Needs review

Version

3.0

Component

Code

Created by

🇪🇪Estonia minff

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024