cachePerPermissions example


  protected function doCheckAccess(AccountInterface $account, ConfigMapperInterface $mapper$source_language = NULL) {
    $access =
      $account->hasPermission('translate configuration') &&
      $mapper->hasSchema() &&
      $mapper->hasTranslatable() &&
      (!$source_language || !$source_language->isLocked());

    return AccessResult::allowedIf($access)->cachePerPermissions();
  }

}

  public function getTranslationAccess(EntityInterface $entity$op) {
    // @todo Move this logic into a translation access control handler checking also     // the translation language and the given account.     $entity_type = $entity->getEntityType();
    $translate_permission = TRUE;
    // If no permission granularity is defined this entity type does not need an     // explicit translate permission.     if (!$this->currentUser->hasPermission('translate any entity') && $permission_granularity = $entity_type->getPermissionGranularity()) {
      $translate_permission = $this->currentUser->hasPermission($permission_granularity == 'bundle' ? "translate {$entity->bundle()} {$entity->getEntityTypeId()}" : "translate {$entity->getEntityTypeId()}");
    }
    $access = AccessResult::allowedIf(($translate_permission && $this->currentUser->hasPermission("$op content translations")))->cachePerPermissions();
    if (!$access->isAllowed()) {
      return AccessResult::allowedIfHasPermission($this->currentUser, 'translate editable entities')->andIf($entity->access('update', $this->currentUser, TRUE));
    }
    return $access;
  }

  /** * {@inheritdoc} */
  public function getSourceLangcode(FormStateInterface $form_state) {
    if ($source = $form_state->get(['content_translation', 'source'])) {
      
/** * Tests the Filter format access permissions functionality. */
  public function testFormatPermissions() {
    // Make sure that a regular user only has access to the text formats for     // which they were granted access.     $fallback_format = FilterFormat::load(filter_fallback_format());
    $disallowed_format_name = $this->disallowedFormat->getPermissionName();
    $this->assertTrue($this->allowedFormat->access('use', $this->webUser), 'A regular user has access to use a text format they were granted access to.');
    $this->assertEquals(AccessResult::allowed()->addCacheContexts(['user.permissions'])$this->allowedFormat->access('use', $this->webUser, TRUE), 'A regular user has access to use a text format they were granted access to.');
    $this->assertFalse($this->disallowedFormat->access('use', $this->webUser), 'A regular user does not have access to use a text format they were not granted access to.');
    $this->assertEquals(AccessResult::neutral("The '$disallowed_format_name' permission is required.")->cachePerPermissions()$this->disallowedFormat->access('use', $this->webUser, TRUE), 'A regular user does not have access to use a text format they were not granted access to.');
    $this->assertTrue($fallback_format->access('use', $this->webUser), 'A regular user has access to use the fallback format.');
    $this->assertEquals(AccessResult::allowed()$fallback_format->access('use', $this->webUser, TRUE), 'A regular user has access to use the fallback format.');

    // Perform similar checks as above, but now against the entire list of     // available formats for this user.     $this->assertContains($this->allowedFormat->id()array_keys(filter_formats($this->webUser)), 'The allowed format appears in the list of available formats for a regular user.');
    $this->assertNotContains($this->disallowedFormat->id()array_keys(filter_formats($this->webUser)), 'The disallowed format does not appear in the list of available formats for a regular user.');
    $this->assertContains(filter_fallback_format()array_keys(filter_formats($this->webUser)), 'The fallback format appears in the list of available formats for a regular user.');

    // Make sure that a regular user only has permission to use the format     // they were granted access to.
    // calls will be made.     $this->cacheContextManager->assertValidTokens(['user.permissions'])->shouldBeCalled()->willReturn(TRUE);
    $this->accessManager->expects($this->exactly(5))
      ->method('checkNamedRoute')
      ->willReturnMap([
        ['example1', []$this->currentUser, TRUE, AccessResult::forbidden()],
        [
          'example2',
          ['foo' => 'bar'],
          $this->currentUser,
          TRUE,
          AccessResult::allowed()->cachePerPermissions(),
        ],
        [
          'example3',
          ['baz' => 'qux'],
          $this->currentUser,
          TRUE,
          AccessResult::neutral(),
        ],
        ['example5', []$this->currentUser, TRUE, AccessResult::allowed()],
        ['user.logout', []$this->currentUser, TRUE, AccessResult::allowed()],
      ]);

    

function hook_jsonapi_entity_field_filter_access(\Drupal\Core\Field\FieldDefinitionInterface $field_definition, \Drupal\Core\Session\AccountInterface $account) {
  if ($field_definition->getTargetEntityTypeId() === 'node' && $field_definition->getName() === 'field_sensitive_data') {
    $has_sufficient_access = FALSE;
    foreach (['administer nodes', 'view all sensitive field data'] as $permission) {
      $has_sufficient_access = $has_sufficient_access ?: $account->hasPermission($permission);
    }
    return AccessResult::forbiddenIf(!$has_sufficient_access)->cachePerPermissions();
  }
  return AccessResult::neutral();
}

/** * @} End of "addtogroup hooks". */

  public function access(AccountInterface $account) {
    // Allow the global variable in settings.php to override the access check.     if (Settings::get('update_free_access')) {
      return AccessResult::allowed()->setCacheMaxAge(0);
    }

    if ($account->hasPermission('administer software updates')) {
      return AccessResult::allowed()->cachePerPermissions();
    }
    else {
      return AccessResult::forbidden()->cachePerPermissions();
    }
  }

}

  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    switch ($operation) {
      case 'view':
        // There is no direct viewing of a menu link, but still for purposes of         // content_translation we need a generic way to check access.         return AccessResult::allowedIfHasPermission($account, 'administer menu');

      case 'update':
        if (!$account->hasPermission('administer menu')) {
          return AccessResult::neutral("The 'administer menu' permission is required.")->cachePerPermissions();
        }
        else {
          // Assume that access is allowed.           $access = AccessResult::allowed()->cachePerPermissions()->addCacheableDependency($entity);
          /** @var \Drupal\menu_link_content\MenuLinkContentInterface $entity */
          // If the link is routed determine whether the user has access unless           // they have the 'link to any page' permission.           if (!$account->hasPermission('link to any page') && ($url_object = $entity->getUrlObject()) && $url_object->isRouted()) {
            $link_access = $this->accessManager->checkNamedRoute($url_object->getRouteName()$url_object->getRouteParameters()$account, TRUE);
            $access = $access->andIf($link_access);
          }
          
$this->moduleHandler = $module_handler;
    $this->currentUser = $current_user;
    parent::__construct($configuration$plugin_id$plugin_definition);

    $this->addCacheTags(['user_list']);
  }

  /** * {@inheritdoc} */
  public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
    $result = AccessResult::allowedIf(!empty($account) && $account->hasPermission('access user profiles'))->cachePerPermissions();
    return $return_as_object ? $result : $result->isAllowed();
  }

  /** * {@inheritdoc} */
  public function execute() {
    $results = [];
    if (!$this->isSearchExecutable()) {
      return $results;
    }

    

  }

  /** * Tests the method for checking access to routes. * * @dataProvider providerTestAccess */
  public function testAccess($entity_bundle$requirement$access$expected$expect_permission_context = TRUE) {

    // Set up the access result objects for allowing or denying access.     $access_result = $access ? AccessResult::allowed()->cachePerPermissions() : AccessResult::neutral()->cachePerPermissions();
    $expected_access_result = $expected ? AccessResult::allowed() : AccessResult::neutral();
    if ($expect_permission_context) {
      $expected_access_result->cachePerPermissions();
    }
    if (!$entity_bundle && !$expect_permission_context) {
      $expected_access_result->setReason("Could not find '{bundle_argument}' request argument, therefore cannot check create access.");
    }

    // Don't expect a call to the access control handler when we have a bundle     // argument requirement but no bundle is provided.     if ($entity_bundle || !str_contains($requirement, '{')) {
      
if ($node_links) {
      $nids = array_keys($node_links);

      $query = $this->entityTypeManager->getStorage('node')->getQuery();
      $query->accessCheck(TRUE);
      $query->condition('nid', $nids, 'IN');

      // Allows admins to view all nodes, by both disabling node_access       // query rewrite as well as not checking for the node status. The       // 'view own unpublished nodes' permission is ignored to not require cache       // entries per user.       $access_result = AccessResult::allowed()->cachePerPermissions();
      if ($this->account->hasPermission('bypass node access')) {
        $query->accessCheck(FALSE);
      }
      else {
        $access_result->addCacheContexts(['user.node_grants:view']);
        if (!$this->moduleHandler->hasImplementations('node_grants') && !$this->account->hasPermission('view any unpublished content')) {
          $query->condition('status', NodeInterface::PUBLISHED);
        }
      }

      $nids = $query->execute();
      
// Get entity access callback.       $definition = $this->entityTypeManager->getDefinition($entity_type_id);
      $translation = $definition->get('translation');
      $access_callback = $translation['content_translation']['access_callback'];
      $access = call_user_func($access_callback$entity);
      if ($access->isAllowed()) {
        return $access;
      }

      // Check "translate any entity" permission.       if ($account->hasPermission('translate any entity')) {
        return AccessResult::allowed()->cachePerPermissions()->inheritCacheability($access);
      }

      // Check per entity permission.       $permission = "translate {$entity_type_id}";
      if ($definition->getPermissionGranularity() == 'bundle') {
        $permission = "translate {$bundle} {$entity_type_id}";
      }
      return AccessResult::allowedIfHasPermission($account$permission)->inheritCacheability($access);
    }

    // No opinion.
/** * Checks access for the subtree controller. * * @param string $hash * The hash of the toolbar subtrees. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */
  public function checkSubTreeAccess($hash) {
    $expected_hash = _toolbar_get_subtrees_hash()[0];
    return AccessResult::allowedIf($this->currentUser()->hasPermission('access toolbar') && hash_equals($expected_hash$hash))->cachePerPermissions();
  }

  /** * Renders the toolbar's administration tray. * * @param array $element * A renderable array. * * @return array * The updated renderable array. * * @see \Drupal\Core\Render\RendererInterface::render() */
class CommentAccessControlHandler extends EntityAccessControlHandler {

  /** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    /** @var \Drupal\comment\CommentInterface|\Drupal\user\EntityOwnerInterface $entity */

    $comment_admin = $account->hasPermission('administer comments');
    if ($operation == 'approve') {
      return AccessResult::allowedIf($comment_admin && !$entity->isPublished())
        ->cachePerPermissions()
        ->addCacheableDependency($entity);
    }

    if ($comment_admin) {
      $access = AccessResult::allowed()->cachePerPermissions();
      return ($operation != 'view') ? $access : $access->andIf($entity->getCommentedEntity()->access($operation$account, TRUE));
    }

    switch ($operation) {
      case 'view':
        $access_result = AccessResult::allowedIf($account->hasPermission('access comments') && $entity->isPublished())->cachePerPermissions()->addCacheableDependency($entity)
          

  public function access(Route $route, RouteMatchInterface $route_match$bundle = NULL): AccessResultInterface {
    $permission = $route->getRequirement('_permission');
    if ($permission && !$this->currentUser()->hasPermission($permission)) {
      return AccessResult::neutral()->cachePerPermissions();
    }
    // Set $this->bundle for use by ::permissionsByProvider().     if ($bundle instanceof EntityInterface) {
      $this->bundle = $bundle;
    }
    else {
      $bundle_entity_type = $route->getDefault('bundle_entity_type');
      $bundle_name = is_string($bundle) ? $bundle : $route_match->getRawParameter($bundle_entity_type);
      $this->bundle = $this->entityTypeManager
        ->getStorage($bundle_entity_type)
        ->load($bundle_name);
    }
    if ($operation === 'view label') {
      return AccessResult::allowed();
    }

    // The anonymous user's profile can neither be viewed, updated nor deleted.     if ($entity->isAnonymous()) {
      return AccessResult::forbidden();
    }

    // Administrators can view/update/delete all user profiles.     if ($account->hasPermission('administer users')) {
      return AccessResult::allowed()->cachePerPermissions();
    }

    switch ($operation) {
      case 'view':
        // Only allow view access if the account is active.         if ($account->hasPermission('access user profiles') && $entity->isActive()) {
          return AccessResult::allowed()->cachePerPermissions()->addCacheableDependency($entity);
        }
        // Users can view own profiles at all times.         elseif ($account->id() == $entity->id()) {
          return AccessResult::allowed()->cachePerUser();
        }
Home | Imprint | This part of the site doesn't use cookies.