You are here

class SavedSearchAccessControlHandler in Search API Saved Searches 8

Provides access checking for saved searches.

Hierarchy

Expanded class hierarchy of SavedSearchAccessControlHandler

See also

\Drupal\search_api_saved_searches\Entity\SavedSearch

6 files declare their use of SavedSearchAccessControlHandler
CacheabilityTest.php in tests/src/Functional/CacheabilityTest.php
CurrentAuthenticatedUser.php in src/Plugin/views/argument_validator/CurrentAuthenticatedUser.php
Email.php in src/Plugin/search_api_saved_searches/notification/Email.php
EmailActivationTest.php in tests/src/Kernel/EmailActivationTest.php
IntegrationTest.php in tests/src/Functional/IntegrationTest.php

... See full list

File

src/Entity/SavedSearchAccessControlHandler.php, line 23

Namespace

Drupal\search_api_saved_searches\Entity
View source
class SavedSearchAccessControlHandler extends EntityAccessControlHandler implements EntityHandlerInterface {

  /**
   * Permission for administering saved searches.
   */
  const ADMIN_PERMISSION = 'administer search_api_saved_searches';

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface|null
   */
  protected $entityTypeManager;

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack|null
   */
  protected $requestStack;

  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    $handler = new static($entity_type);
    $handler
      ->setEntityTypeManager($container
      ->get('entity_type.manager'));
    $handler
      ->setRequestStack($container
      ->get('request_stack'));
    return $handler;
  }

  /**
   * Retrieves the entity type manager.
   *
   * @return \Drupal\Core\Entity\EntityTypeManagerInterface
   *   The entity type manager.
   */
  public function getEntityTypeManager() {
    return $this->entityTypeManager ?: \Drupal::service('entity_type.manager');
  }

  /**
   * Sets the entity type manager.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The new entity type manager.
   *
   * @return $this
   */
  public function setEntityTypeManager(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
    return $this;
  }

  /**
   * Retrieves the request stack.
   *
   * @return \Symfony\Component\HttpFoundation\RequestStack
   *   The request stack.
   */
  public function getRequestStack() {
    return $this->requestStack ?: \Drupal::service('request_stack');
  }

  /**
   * Sets the request stack.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   The new request stack.
   *
   * @return $this
   */
  public function setRequestStack(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {

    /** @var \Drupal\search_api_saved_searches\SavedSearchInterface $entity */
    $access = parent::checkAccess($entity, $operation, $account);
    if (!$access
      ->isAllowed()) {
      if (!$entity
        ->getOwner()
        ->isAnonymous()) {
        $is_owner = $account
          ->id() == $entity
          ->getOwnerId();
        $owner_access = AccessResult::allowedIf($is_owner)
          ->addCacheableDependency($account);
      }
      else {
        $token = $this
          ->getRequestStack()
          ->getCurrentRequest()->query
          ->get('token');
        $token_match = $token === $entity
          ->getAccessToken($operation);
        $owner_access = AccessResult::allowedIf($token_match)
          ->addCacheContexts([
          'url.query_args:token',
        ]);
      }
      $owner_access
        ->andIf($this
        ->checkBundleAccess($account, $entity
        ->bundle()));
      $access = $access
        ->orIf($owner_access);
    }
    return $access;
  }

  /**
   * {@inheritdoc}
   */
  protected function checkCreateAccess(AccountInterface $account, array $context, $bundle = NULL) {
    $access = parent::checkCreateAccess($account, $context, $bundle);
    if (!$access
      ->isAllowed()) {
      $access = $access
        ->orIf($this
        ->checkBundleAccess($account, $bundle));
    }
    return $access;
  }

  /**
   * {@inheritdoc}
   */
  protected function checkFieldAccess($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
    $field_name = $field_definition
      ->getName();

    // Only admins can edit administrative fields.
    $administrative_fields = [
      'uid',
      'status',
      'created',
      'last_executed',
      'next_execution',
    ];
    if ($operation === 'edit' && in_array($field_name, $administrative_fields, TRUE)) {
      return AccessResult::allowedIfHasPermission($account, self::ADMIN_PERMISSION);
    }

    // For serialized fields, neither viewing nor editing makes sense.
    $serialized_fields = [
      'query',
    ];
    if (in_array($field_name, $serialized_fields, TRUE)) {
      return AccessResult::forbidden();
    }

    // The index ID cannot be edited, but can be viewed by admins.
    if ($field_name === 'index_id') {
      if ($operation === 'edit') {
        return AccessResult::forbidden();
      }
      return AccessResult::allowedIfHasPermission($account, self::ADMIN_PERMISSION);
    }

    // Allow for access checks on fields defined by notification plugins.
    if ($field_definition instanceof BundleFieldDefinition) {
      $plugin_id = $field_definition
        ->getSetting('notification_plugin');
      $bundle = $field_definition
        ->getTargetBundle();
      if ($plugin_id && $bundle) {

        /** @var \Drupal\search_api_saved_searches\SavedSearchTypeInterface $type */
        $type = $this
          ->getEntityTypeManager()
          ->getStorage('search_api_saved_search_type')
          ->load($bundle);
        if ($type && $type
          ->isValidNotificationPlugin($plugin_id)) {
          return $type
            ->getNotificationPlugin($plugin_id)
            ->checkFieldAccess($operation, $field_definition, $account, $items);
        }
      }

      // In doubt (that is, when some part of the previous code didn't work
      // out), only allow admin access.
      return AccessResult::allowedIfHasPermission($account, self::ADMIN_PERMISSION);
    }
    return parent::checkFieldAccess($operation, $field_definition, $account, $items);
  }

  /**
   * Checks access for using saved searches of a specific bundle.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The user session for which to check access.
   * @param string $bundle
   *   The bundle for which to check usage access.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  protected function checkBundleAccess(AccountInterface $account, $bundle) {
    $permission = "use {$bundle} search_api_saved_searches";
    return AccessResult::allowedIfHasPermission($account, $permission);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityAccessControlHandler::$accessCache protected property Stores calculated access check results.
EntityAccessControlHandler::$entityType protected property Information about the entity type.
EntityAccessControlHandler::$entityTypeId protected property The entity type ID of the access control handler instance.
EntityAccessControlHandler::$viewLabelOperation protected property Allows to grant access to just the labels. 5
EntityAccessControlHandler::access public function Checks access to an operation on a given entity or entity translation. Overrides EntityAccessControlHandlerInterface::access 1
EntityAccessControlHandler::createAccess public function Checks access to create an entity. Overrides EntityAccessControlHandlerInterface::createAccess 1
EntityAccessControlHandler::fieldAccess public function Checks access to an operation on a given entity field. Overrides EntityAccessControlHandlerInterface::fieldAccess
EntityAccessControlHandler::getCache protected function Tries to retrieve a previously cached access value from the static cache.
EntityAccessControlHandler::prepareUser protected function Loads the current account object, if it does not exist yet.
EntityAccessControlHandler::processAccessHookResults protected function We grant access to the entity if both of these conditions are met:
EntityAccessControlHandler::resetCache public function Clears all cached access checks. Overrides EntityAccessControlHandlerInterface::resetCache
EntityAccessControlHandler::setCache protected function Statically caches whether the given user has access.
EntityAccessControlHandler::__construct public function Constructs an access control handler instance. 5
EntityHandlerBase::$moduleHandler protected property The module handler to invoke hooks on. 2
EntityHandlerBase::moduleHandler protected function Gets the module handler. 2
EntityHandlerBase::setModuleHandler public function Sets the module handler for this handler.
SavedSearchAccessControlHandler::$entityTypeManager protected property The entity type manager.
SavedSearchAccessControlHandler::$requestStack protected property The request stack.
SavedSearchAccessControlHandler::ADMIN_PERMISSION constant Permission for administering saved searches.
SavedSearchAccessControlHandler::checkAccess protected function Performs access checks. Overrides EntityAccessControlHandler::checkAccess
SavedSearchAccessControlHandler::checkBundleAccess protected function Checks access for using saved searches of a specific bundle.
SavedSearchAccessControlHandler::checkCreateAccess protected function Performs create access checks. Overrides EntityAccessControlHandler::checkCreateAccess
SavedSearchAccessControlHandler::checkFieldAccess protected function Default field access as determined by this access control handler. Overrides EntityAccessControlHandler::checkFieldAccess
SavedSearchAccessControlHandler::createInstance public static function Instantiates a new instance of this entity handler. Overrides EntityHandlerInterface::createInstance
SavedSearchAccessControlHandler::getEntityTypeManager public function Retrieves the entity type manager.
SavedSearchAccessControlHandler::getRequestStack public function Retrieves the request stack.
SavedSearchAccessControlHandler::setEntityTypeManager public function Sets the entity type manager.
SavedSearchAccessControlHandler::setRequestStack public function Sets the request stack.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.