1

I have added private message module for one of my project which has it's own entity. I need to check whether the user is having access to that entity content or not. The module has it's menu item defined in the module's routing.yml

e.g.:

entity.private_message_thread.canonical:
  path: '/private_messages/{private_message_thread}'
  defaults:
    _entity_view: 'private_message_thread'
    _title: 'Private Messages'
  requirements:
    _entity_access: 'private_message_thread.view'

How could I check whether the user has view access to the above menu path?

2 Answers 2

4

I have tested the entity access and $entity->access('view', $account); that worked in my case. I earlier used the optional $account parameter so that it could check the currently logged in user.

I loaded my entity with:

$entity_manager = \Drupal::entityTypeManager();
$thread_entity = $entity_manager->getStorage('private_message_thread')->load('private_message_thread_id');

I wanted to check whether the user has permission to view entity by code. Below is the code for the same I did in my case:

$account = \Drupal::currentUser();
$entity_manager = \Drupal::entityTypeManager();
$entity = $entity_manager->getStorage('private_message_thread')->load('private_message_thread_id');
$check = $entity->access('view', $account);

Please let me know if you have a better answer over the same.

2

You can check annotations of those entities and find access handler.

e.g.

/**
 * Defines the Private Message Thread entity.
 *
 * @ContentEntityType(
 *   id = "private_message_thread",
 *   label = @Translation("Private Message Thread"),
 *   handlers = {
 *     "view_builder" = "Drupal\private_message\Entity\Builder\PrivateMessageThreadViewBuilder",
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "access" = "Drupal\private_message\Entity\Access\PrivateMessageThreadAccessControlHandler",
 ...

As you can see, there is access handler. Now you know how it works.

  protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
    if ($account->hasPermission('use private messaging system')) {
      switch ($operation) {
        case 'view':
          if ($entity->isMember($account->id())) {
            $messages = $entity->filterUserDeletedMessages($account);
            if (count($messages)) {
              return AccessResult::allowed();
            }
          }
          ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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