5 Sep.2017

Drupal 10: How to prevent access to pages for an anonymous user

For members only

Suppose before you is the task to prohibit access to some pages for an anonymous user.

For this, there are several great modules in Drupal, some of them:

These modules are very good and customizable, but what if for some reason you try to avoid unnecessary modules on the site and need a very simple solution?

In this case, we can use a very short code in our module.

All we need is to create a boolean field called "For members only" (field_protected_page is machine name) and add some PHP code.

File
YOURMODULE.module
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
 
/**
 * Implements hook_entity_access().
 */
function YOURMODULE_entity_access(EntityInterface $entity, $operation, AccountInterface $account) {
  switch ($operation) {
    case 'view':
 
      if ($account->isAnonymous()
        && $entity->hasField('field_protected_page')
        && $entity->get('field_protected_page')->getString() === '1') {
        return AccessResult::forbidden(t('For internal using.'))
          ->cachePerPermissions()
          ->addCacheableDependency($entity);
      }
      break;
 
    default:
      // Nothing to do.
  }
 
  return AccessResult::neutral();
}

You just need to create hook_entity_access and check the user and the value of the field.

Conclusion

Voilà! As you see everything is very simple and easy. I hope you are like it.

And of course, I will be happy with any comments and new ideas. Until next time...

Ruslan Piskarov

Ukraine
PHP/WEB Developer / Drupal Expert. More than 11 years of experience delivering Drupal based General Purpose solutions for different sectors such as Job Boards, Product Portfolios, Geo Coding, Real Estate solutions, E-Commerce, Classifieds, Corporate and online Magazines/Newspapers.