Skip to main content
Category:

Code snippet that can be used to to disable access to known user pages in Drupal 8.

 

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\UserInterface;

/**
 * @param UserInterface $entity
 * @param $op
 * @param AccountInterface $account
 * @return AccessResult|\Drupal\Core\Access\AccessResultForbidden|\Drupal\Core\Access\AccessResultNeutral
 */
function mymodule_user_access(UserInterface $entity, $op, AccountInterface $account) {
  if ($entity->id() == $account->id()) {
    switch ($op) {
      case 'update':
      case 'view':
      case 'user_name':
      case 'user_mail':
      case 'user_pass':
      case 'user_edit':
      case 'user_delete':
        $user_roles = $account->getRoles();
        if (!in_array('administrator', $user_roles)) {
          return AccessResult::forbidden();
        }
        break;
    }
  }
  return AccessResult::neutral();
}

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook