0

Is there a way in Drupal 10 to programmatically check to see if the current logged in user can access the edit/create/view for each content type.

1

2 Answers 2

3

Use the the access manager service:

$access_manager = \Drupal::service('access_manager');

To check if the current user can edit a specific node:

$has_access = $access_manager->checkNamedRoute('entity.node.edit_form', ['node' => '1']);

Or can create a node for a specific content type:

$has_access = $access_manager->checkNamedRoute('node.add', ['node_type' => 'article']);
1
  • That's perfect, does exactly what I was looking for. Thank you
    – Richard
    Commented Apr 30 at 12:50
1

If you have the entity object you can use access method:

$currentUSer =  \Drupal::currentUser();
// Check different access.
$hasEditAccess =  $entity->access('edit', $currentUSer);
$hasViewAccess =  $entity->access('view', $currentUSer);
$hasCreateAccess =  $entity->access('create', $currentUSer);

Otherwise you can create your own access check function that takes entity type and bundle to, something like:

/**
   * Check user access.
   *
   * @param string $operation
   *   The operation eg view|edit|create.
   * @param string $bundle
   *   Bundle.
   * @param string $entity_type_id
   *   Entity type.
   * @param \Drupal\Core\Session\AccountInterface|NULL $account
   *   User account to check access.
   *
   * @return bool
   */
  function checkUserAccess(string $operation = 'view', string $bundle = 'article', string $entity_type_id = 'node', AccountInterface $account = NULL): bool {
    $account = $account ?: \Drupal::currentUser();
    // Check if the user has the permission to apply operation of this type.
    return $account->hasPermission("$operation any $bundle $entity_type_id");
  }

and then you can check with something like:

checkUserAccess('create', 'page','node', account: $this->currentUser());

1
  • checkUserAccess() assumes all entity types use permissions in the style of \Drupal\entity\EntityPermissionProvider, it ignores admin permissions, and it ignores custom access alters.
    – Andy
    Commented Apr 29 at 19:12

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.