isForbidden example


  protected function assertAccess(AccessResultInterface $expected_access_result, array $expected_cache_contexts, array $expected_cache_tags, AccessResultInterface $actual): void {
    $this->assertSame($expected_access_result->isAllowed()$actual->isAllowed());
    $this->assertSame($expected_access_result->isForbidden()$actual->isForbidden());
    $this->assertSame($expected_access_result->isNeutral()$actual->isNeutral());

    $actual_cache_contexts = $actual->getCacheContexts();
    sort($expected_cache_contexts);
    sort($actual_cache_contexts);
    $this->assertSame($expected_cache_contexts$actual_cache_contexts);

    $actual_cache_tags = $actual->getCacheTags();
    sort($expected_cache_tags);
    sort($actual_cache_tags);
    $this->assertSame($expected_cache_tags$actual_cache_tags);
  }
    $entity->save();

    // If the ID has been set as part of the create ensure it has been set     // correctly.     if (isset($entity_create_values['id'])) {
      $this->assertSame($entity_create_values['id']$entity->id());
    }
    // The UUID is hard-coded by the data provider.     $this->assertSame('60e3a179-79ed-4653-ad52-5e614c8e8fbe', $entity->uuid());
    $this->assertFalse($entity->get('uuid')->access('edit'));
    $access_result = $entity->get('uuid')->access('edit', NULL, TRUE);
    $this->assertTrue($access_result->isForbidden());
    $this->assertEquals('The entity UUID cannot be changed.', $access_result->getReason());

    // Ensure the ID is still not allowed to be edited.     $this->assertFalse($entity->get('id')->access('edit'));
    $access_result = $entity->get('id')->access('edit', NULL, TRUE);
    $this->assertTrue($access_result->isForbidden());
    $this->assertEquals('The entity ID cannot be changed.', $access_result->getReason());
  }

  public function providerTestFieldAccess() {
    return [
      
    $this->drupalGet('admin/reports/status');
    $this->clickLink('Rebuild permissions');
    $this->submitForm([], 'Rebuild permissions');
    $this->assertSession()->pageTextContains('The content access permissions have been rebuilt.');

    // Test if the rebuild by user that cannot bypass node access and does not     // have access to the nodes has been successful.     $this->assertFalse($this->adminUser->hasPermission('bypass node access'));
    $this->assertNull(\Drupal::state()->get('node.node_access_needs_rebuild'), 'Node access permissions have been rebuilt');
    foreach ($nodes as $node) {
      $this->assertTrue($grant_storage->access($node, 'view', $this->webUser)->isAllowed(), 'After rebuilding node access the grant storage returns allowed for the node author.');
      $this->assertFalse($grant_storage->access($node, 'view', $this->adminUser)->isForbidden(), 'After rebuilding node access the grant storage returns forbidden for the admin user.');
    }
    $this->assertEmpty(\Drupal::service('node.grant_storage')->checkAll($this->webUser), 'There is no all realm access record');

    // Test an anonymous node access rebuild from code.     $this->drupalLogout();
    node_access_rebuild();
    foreach ($nodes as $node) {
      $this->assertTrue($grant_storage->access($node, 'view', $this->webUser)->isAllowed(), 'After rebuilding node access the grant storage returns allowed for the node author.');
      $this->assertFalse($grant_storage->access($node, 'view', $this->adminUser)->isForbidden(), 'After rebuilding node access the grant storage returns forbidden for the admin user.');
    }
    $this->assertEmpty(\Drupal::service('node.grant_storage')->checkAll($this->webUser), 'There is no all realm access record');
  }
$neutralAccessible = $this->createAccessibleDouble(AccessResult::neutral());

    // Ensure that groups with no dependencies return a neutral access result.     $this->assertTrue((new AccessGroupAnd())->access('view', $this->account, TRUE)->isNeutral());

    $andNeutral = new AccessGroupAnd();
    $andNeutral->addDependency($allowedAccessible)->addDependency($neutralAccessible);
    $this->assertTrue($andNeutral->access('view', $this->account, TRUE)->isNeutral());

    $andForbidden = $andNeutral;
    $andForbidden->addDependency($forbiddenAccessible);
    $this->assertTrue($andForbidden->access('view', $this->account, TRUE)->isForbidden());

    // Ensure that groups added to other groups works.     $andGroupsForbidden = new AccessGroupAnd();
    $andGroupsForbidden->addDependency($andNeutral)->addDependency($andForbidden);
    $this->assertTrue($andGroupsForbidden->access('view', $this->account, TRUE)->isForbidden());
    // Ensure you can add a non-group accessible object.     $andGroupsForbidden->addDependency($allowedAccessible);
    $this->assertTrue($andGroupsForbidden->access('view', $this->account, TRUE)->isForbidden());
  }

}
->orIf($forbidIfNotReusable())
        ->orIf(AccessResult::allowedIfHasPermissions($account[
          'administer block content',
        ])),

      default => parent::checkAccess($entity$operation$account),
    };

    // Add the entity as a cacheable dependency because access will at least be     // determined by whether the block is reusable.     $access->addCacheableDependency($entity);
    if ($entity->isReusable() === FALSE && $access->isForbidden() !== TRUE) {
      if (!$entity instanceof DependentAccessInterface) {
        throw new \LogicException("Non-reusable block entities must implement \Drupal\block_content\Access\DependentAccessInterface for access control.");
      }
      $dependency = $entity->getAccessDependency();
      if (empty($dependency)) {
        // If an access dependency has not been set let modules set one.         $event = new BlockContentGetDependencyEvent($entity);
        $this->eventDispatcher->dispatch($event, BlockContentEvents::BLOCK_CONTENT_GET_DEPENDENCY);
        $dependency = $event->getAccessDependency();
        if (empty($dependency)) {
          return AccessResult::forbidden("Non-reusable blocks must set an access dependency for access control.");
        }
$response = new Response('', $code);
            $this->assertTrue($response->isEmpty());
        }

        $response = new Response('', 200);
        $this->assertFalse($response->isEmpty());
    }

    public function testIsForbidden()
    {
        $response = new Response('', 403);
        $this->assertTrue($response->isForbidden());

        $response = new Response('', 200);
        $this->assertFalse($response->isForbidden());
    }

    public function testIsOk()
    {
        $response = new Response('', 200);
        $this->assertTrue($response->isOk());

        $response = new Response('', 404);
        

  public function testSetAccessDependency($use_set_first) {
    $testRefinable = new RefinableDependentAccessTraitTestClass();

    if ($use_set_first) {
      $testRefinable->setAccessDependency($this->forbidden);
    }
    else {
      $testRefinable->addAccessDependency($this->forbidden);
    }
    $accessResult = $testRefinable->getAccessDependency()->access('view', $this->account, TRUE);
    $this->assertTrue($accessResult->isForbidden());
    $this->assertEquals('Because I said so', $accessResult->getReason());

    // Calling setAccessDependency() replaces the existing dependency.     $testRefinable->setAccessDependency($this->neutral);
    $dependency = $testRefinable->getAccessDependency();
    $this->assertNotInstanceOf(AccessGroupAnd::class$dependency);
    $accessResult = $dependency->access('view', $this->account, TRUE);
    $this->assertTrue($accessResult->isNeutral());
    $this->assertEquals('I have no opinion', $accessResult->getReason());
  }

  
$this->assertSame(Cache::PERMANENT, $access->getCacheMaxAge());
  }

  /** * Tests the construction of an AccessResult object. * * @covers ::neutral */
  public function testConstruction() {
    $verify = function DAccessResult $access) {
      $this->assertFalse($access->isAllowed());
      $this->assertFalse($access->isForbidden());
      $this->assertTrue($access->isNeutral());
      $this->assertDefaultCacheability($access);
    };

    // Verify the object when using the constructor.     $a = new AccessResultNeutral();
    $verify($a);

    // Verify the object when using the ::create() convenience method.     $b = AccessResult::neutral();
    $verify($b);

    
    // 3. Neither access result is 'forbidden' and both are cacheable: inherit     // the other's cacheability metadata because it may turn into a     // 'forbidden' for another value of the cache contexts in the     // cacheability metadata. In other words: this is necessary to respect     // the contagious nature of the 'forbidden' access result.     // e.g. we have two access results A and B. Neither is forbidden. A is     // globally cacheable (no cache contexts). B is cacheable per role. If we     // don't have merging case 3, then A->orIf(B) will be globally cacheable,     // which means that even if a user of a different role logs in, the     // cached access result will be used, even though for that other role, B     // is forbidden!     if ($this->isForbidden() || $other->isForbidden()) {
      $result = static::forbidden();
      if (!$this->isForbidden() || ($this->getCacheMaxAge() === 0 && $other->isForbidden())) {
        $merge_other = TRUE;
      }

      if ($this->isForbidden() && $this instanceof AccessResultReasonInterface && $this->getReason() !== '') {
        $result->setReason($this->getReason());
      }
      elseif ($other->isForbidden() && $other instanceof AccessResultReasonInterface && $other->getReason() !== '') {
        $result->setReason($other->getReason());
      }
    }

function hook_entity_field_access_alter(array &$grants, array $context) {
  /** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
  $field_definition = $context['field_definition'];
  if ($field_definition->getName() == 'field_of_interest' && $grants['node']->isForbidden()) {
    // Override node module's restriction to no opinion (neither allowed nor     // forbidden). We don't want to provide our own access hook, we only want to     // take out node module's part in the access handling of this field. We also     // don't want to switch node module's grant to     // AccessResultInterface::isAllowed() , because the grants of other modules     // should still decide on their own if this field is accessible or not     $grants['node'] = AccessResult::neutral()->inheritCacheability($grants['node']);
  }
}

/** * Acts when initializing a fieldable entity object. * * This hook runs after a new entity object or a new entity translation object * has just been instantiated. It can be used to set initial values, e.g. to * provide defaults. * * @param \Drupal\Core\Entity\FieldableEntityInterface $entity * The entity object. * * @ingroup entity_crud * @see hook_ENTITY_TYPE_field_values_init() */
    // - No modules say to deny access.     // - At least one module says to grant access.     $access = array_merge(
      $this->moduleHandler()->invokeAll('entity_access', [$entity$operation$account]),
      $this->moduleHandler()->invokeAll($entity->getEntityTypeId() . '_access', [$entity$operation$account])
    );

    $return = $this->processAccessHookResults($access);

    // Also execute the default access check except when the access result is     // already forbidden, as in that case, it can not be anything else.     if (!$return->isForbidden()) {
      $return = $return->orIf($this->checkAccess($entity$operation$account));
    }
    $result = $this->setCache($return$cid$operation$langcode$account);
    return $return_as_object ? $result : $result->isAllowed();
  }

  /** * Determines entity access. * * We grant access to the entity if both of these conditions are met: * - No modules say to deny access. * - At least one module says to grant access. * * @param \Drupal\Core\Access\AccessResultInterface[] $access * An array of access results of the fired access hook. * * @return \Drupal\Core\Access\AccessResultInterface * The combined result of the various access checks' results. All their * cacheability metadata is merged as well. * * @see \Drupal\Core\Access\AccessResultInterface::orIf() */
Home | Imprint | This part of the site doesn't use cookies.