0

I use Node access user reference module in many projects. I have a very similar task: Grant access to a profile page for those user who is referenced in that profile. Unfortunately, Node access user reference doesn't work in this case, since it's not a node but a different kind of entity. Is there any solution for this task?

  • Should be easy getting this work in a custom module. Just get current user's bid with global $user, iterate through referenced users and if current $user->uid matches with any iteration item then just provide access. – AltaGrade Mar 28 '18 at 19:26
1

Here is ready to use code. For this to work you need to enable the Entity reference module, add entity reference field on admin/config/people/accounts/fields page targeting user entity and setting to unlimited, and finally giving access to View user profiles to all authenticated user role members.

Create my_module.info file and paste:

name = My Module
description = Does awesome things. Makes tea. Washes up. Favours of a personal nature.
dependencies[] = entityreference
core = 7.x

Create my_module.module file and paste:

/**
 * Implements hook_user_view_alter().
 */
function my_module_user_view_alter(&$build) {
  global $user;
  if ($build['#account']->uid == $user->uid || in_array('administrator', array_values($user->roles))) {
    // Return early if user is administrator or is at their own profile.
    return;
  } elseif (isset($build['field_users'])) {
    foreach ($build['field_users']['#object']->field_users[LANGUAGE_NONE] as $key => $referenced) {
      if ($user->uid == $referenced['target_id']) {
        return;
      }
    }
  }
  drupal_access_denied();
}

Go to a user profile, add some user references and try to view that user's profile as the referenced user to gain access and then as non-referenced user to get denied access.

  • Thanks a lot. I'm working on an other issue, after that I will try this out. – StG Apr 5 '18 at 16:04
  • Any update on this? Takes couple minutes to test the code. – AltaGrade Apr 9 '18 at 16:36
  • I'm really grateful your help but this site is a 'side project' besides my other daily tasks. Please, be patient, I hope I can test it soon. – StG Apr 11 '18 at 6:44
  • Finally I have had some time to test your suggestions, thank you for your patience. Basically it seems to be working more or less, but I have still got a few Issues:<br/> 1. drupal_access_denied() renders a full page, it duplicates the header 2. This solution works only if all users got View user profiles permission. – StG Jun 4 '18 at 12:48
  • After drupal_access_denied(); an exit; command must be placed in order to avoid double page rendering. Apart from this it's a useful sugestion, thanks a lot! – StG Jun 5 '18 at 12:39

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.