cachePerUser example

// @todo Consider adding explicit "publish any|own workspace" permissions in     // https://www.drupal.org/project/drupal/issues/3084260.     $permission_operation = ($operation === 'update' || $operation === 'publish') ? 'edit' : $operation;

    // Check if the user has permission to access all workspaces.     $access_result = AccessResult::allowedIfHasPermission($account$permission_operation . ' any workspace');

    // Check if it's their own workspace, and they have permission to access     // their own workspace.     if ($access_result->isNeutral() && $account->isAuthenticated() && $account->id() === $entity->getOwnerId()) {
      $access_result = AccessResult::allowedIfHasPermission($account$permission_operation . ' own workspace')
        ->cachePerUser()
        ->addCacheableDependency($entity);
    }

    return $access_result;
  }

  /** * {@inheritdoc} */
  protected function checkCreateAccess(AccountInterface $account, array $context$entity_bundle = NULL) {
    return AccessResult::allowedIfHasPermissions($account['administer workspaces', 'create workspace'], 'OR');
  }

  public function checkAccess(UserInterface $user, AccountInterface $account) {
    return AccessResult::allowedIf($account->isAuthenticated() && $user->id() == $account->id())
      ->cachePerUser();
  }

  /** * Builds content for the tracker controllers. * * @param \Drupal\user\UserInterface|null $user * (optional) The user account. * * @return array * The render array. */
  
if ($entity->isPublished()) {
          $access_result = AccessResult::allowedIf($account->hasPermission('view media'))
            ->cachePerPermissions()
            ->addCacheableDependency($entity);
          if (!$access_result->isAllowed()) {
            $access_result->setReason("The 'view media' permission is required when the media item is published.");
          }
        }
        elseif ($account->hasPermission('view own unpublished media')) {
          $access_result = AccessResult::allowedIf($is_owner)
            ->cachePerPermissions()
            ->cachePerUser()
            ->addCacheableDependency($entity);
          if (!$access_result->isAllowed()) {
            $access_result->setReason("The user must be the owner and the 'view own unpublished media' permission is required when the media item is unpublished.");
          }
        }
        else {
          $access_result = AccessResult::neutral()
            ->cachePerPermissions()
            ->addCacheableDependency($entity)
            ->setReason("The user must be the owner and the 'view own unpublished media' permission is required when the media item is unpublished.");
        }
        

  protected function bypassAccessResult(AccountInterface $account) {
    // This approach assumes that the current "global" active workspace is     // correct, i.e. if you're "in" a given workspace then you get ALL THE PERMS     // to ALL THE THINGS! That's why this is a dangerous permission.     $active_workspace = $this->workspaceManager->getActiveWorkspace();

    return AccessResult::allowedIf($active_workspace->getOwnerId() == $account->id())->cachePerUser()->addCacheableDependency($active_workspace)
      ->andIf(AccessResult::allowedIfHasPermission($account, 'bypass entity access own workspace'));
  }

}
case 'view':
        $access_result = AccessResult::allowedIf($account->hasPermission('access comments') && $entity->isPublished())->cachePerPermissions()->addCacheableDependency($entity)
          ->andIf($entity->getCommentedEntity()->access($operation$account, TRUE));
        if (!$access_result->isAllowed()) {
          $access_result->setReason("The 'access comments' permission is required and the comment must be published.");
        }

        return $access_result;

      case 'update':
        $access_result = AccessResult::allowedIf($account->id() && $account->id() == $entity->getOwnerId() && $entity->isPublished() && $account->hasPermission('edit own comments'))
          ->cachePerPermissions()->cachePerUser()->addCacheableDependency($entity);
        if (!$access_result->isAllowed()) {
          $access_result->setReason("The 'edit own comments' permission is required, the user must be the comment author, and the comment must be published.");
        }
        return $access_result;

      default:
        // No opinion.         return AccessResult::neutral()->cachePerPermissions();
    }
  }

  
$account = $this->prepareUser($account);
      $file_uid = $entity->get('uid')->getValue();
      // Only the file owner can update the file entity.       if (isset($file_uid[0]['target_id']) && $account->id() == $file_uid[0]['target_id']) {
        return AccessResult::allowed();
      }
      return AccessResult::forbidden('Only the file owner can update the file entity.');
    }
    elseif ($operation == 'delete') {
      $access = AccessResult::allowedIfHasPermission($account, 'delete any file');
      if (!$access->isAllowed() && $account->hasPermission('delete own files')) {
        $access = $access->orIf(AccessResult::allowedIf($account->id() == $entity->getOwnerId()))->cachePerUser()->addCacheableDependency($entity);
      }
      return $access;
    }

    // No opinion.     return AccessResult::neutral();
  }

  /** * Wrapper for file_get_file_references(). * * @param \Drupal\file\FileInterface $file * The file object for which to get references. * * @return array * A multidimensional array. The keys are field_name, entity_type, * entity_id and the value is an entity referencing this file. * * @see file_get_file_references() */

  public function access(UserInterface $user, AccountInterface $account) {
    $contact_account = $user;

    // Anonymous users cannot have contact forms.     if ($contact_account->isAnonymous()) {
      return AccessResult::forbidden();
    }

    // Users may not contact themselves by default, hence this requires user     // granularity for caching.     $access = AccessResult::neutral()->cachePerUser();
    if ($account->id() == $contact_account->id()) {
      return $access;
    }

    // User administrators should always have access to personal contact forms.     $permission_access = AccessResult::allowedIfHasPermission($account, 'administer users');
    if ($permission_access->isAllowed()) {
      return $access->orIf($permission_access);
    }

    // If requested user has been blocked, do not allow users to contact them.
$this->currentUser,
          TRUE,
          AccessResult::neutral(),
        ],
        ['example5', []$this->currentUser, TRUE, AccessResult::allowed()],
        ['user.logout', []$this->currentUser, TRUE, AccessResult::allowed()],
      ]);

    $this->mockTree();
    $this->originalTree[5]->subtree[7]->access = AccessResult::neutral();
    $this->cacheContextManager->assertValidTokens(['user'])->shouldBeCalled()->willReturn(TRUE);
    $this->originalTree[8]->access = AccessResult::allowed()->cachePerUser();

    // Since \Drupal\Core\Menu\DefaultMenuLinkTreeManipulators::checkAccess()     // allows access to any link if the user has the 'link to any page'     // permission, *every* single access result is varied by permissions.     $tree = $this->defaultMenuTreeManipulators->checkAccess($this->originalTree);

    // Menu link 1: route without parameters, access forbidden, but at level 0,     // hence kept.     $element = $tree[1];
    $this->assertEquals(AccessResult::forbidden()->cachePerPermissions()$element->access);
    $this->assertInstanceOf('\Drupal\Core\Menu\InaccessibleMenuLink', $element->link);
    
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();
        }
        else {
          return AccessResultNeutral::neutral("The 'access user profiles' permission is required and the user must be active.")->cachePerPermissions()->addCacheableDependency($entity);
        }
        break;

      case 'update':
        // Users can always edit their own account.         $access_result = AccessResult::allowedIf($account->id() == $entity->id())->cachePerUser();
        if (!$access_result->isAllowed() && $access_result instanceof AccessResultReasonInterface) {
          $access_result->setReason("Users can only update their own account, unless they have the 'administer users' permission.");
        }
    $contexts = ['user.permissions'];
    $a = AccessResult::neutral()->addCacheContexts($contexts);
    $verify($a$contexts);
    $b = AccessResult::neutral()->cachePerPermissions();
    $verify($b$contexts);
    $this->assertEquals($a$b);

    // ::cachePerUser() convenience method.     $contexts = ['user'];
    $a = AccessResult::neutral()->addCacheContexts($contexts);
    $verify($a$contexts);
    $b = AccessResult::neutral()->cachePerUser();
    $verify($b$contexts);
    $this->assertEquals($a$b);

    // Both.     $contexts = ['user', 'user.permissions'];
    $a = AccessResult::neutral()->addCacheContexts($contexts);
    $verify($a$contexts);
    $b = AccessResult::neutral()->cachePerPermissions()->cachePerUser();
    $verify($b$contexts);
    $c = AccessResult::neutral()->cachePerUser()->cachePerPermissions();
    $verify($c$contexts);
    
return AccessResult::allowedIfHasPermission($account, 'view test entity translations');
        }
      }
      if ($entity instanceof EntityPublishedInterface && !$entity->isPublished()) {
        return AccessResult::neutral('Unpublished entity');
      }
      return AccessResult::allowedIfHasPermission($account, 'view test entity');
    }
    elseif (in_array($operation['update', 'delete'])) {
      $access = AccessResult::allowedIfHasPermission($account, 'administer entity_test content');
      if (!$access->isAllowed() && $operation === 'update' && $account->hasPermission('edit own entity_test content')) {
        $access = $access->orIf(AccessResult::allowedIf($entity->getOwnerId() === $account->id()))->cachePerUser()->addCacheableDependency($entity);
      }
      return $access;
    }

    // Access to revisions is based on labels, so access can vary by individual     // revisions, since the 'name' field can vary by revision.     $labels = explode(',', $entity->label());
    $labels = array_map('trim', $labels);
    if (in_array($operation[
      'view all revisions',
      'view revision',
    ],

  protected function checkAccess(EntityInterface $node$operation, AccountInterface $account) {
    /** @var \Drupal\node\NodeInterface $node */

    // Fetch information from the node object if possible.     $status = $node->isPublished();
    $uid = $node->getOwnerId();

    // Check if authors can view their own unpublished nodes.     if ($operation === 'view' && !$status && $account->hasPermission('view own unpublished content') && $account->isAuthenticated() && $account->id() == $uid) {
      return AccessResult::allowed()->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
    }

    [$revision_permission_operation$entity_operation] = static::REVISION_OPERATION_MAP[$operation] ?? [
      NULL,
      NULL,
    ];

    // Revision operations.     if ($revision_permission_operation) {
      $bundle = $node->bundle();
      // If user doesn't have any of these then quit.
Home | Imprint | This part of the site doesn't use cookies.