access example

$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.");
        }
      }
      /** @var \Drupal\Core\Entity\EntityInterface $dependency */
      $access = $access->andIf($dependency->access($operation$account, TRUE));
    }
    return $access;
  }

  /** * {@inheritdoc} */
  protected function checkCreateAccess(AccountInterface $account, array $context$entity_bundle = NULL) {
    return AccessResult::allowedIfHasPermissions($account[
      'create ' . $entity_bundle . ' block content',
      'access block library',
    ])
$this->installEntitySchema('content_moderation_state');
    $this->installEntitySchema('user');
    $this->accessControlHandler = $this->container->get('entity_type.manager')->getAccessControlHandler('content_moderation_state');
  }

  /** * @covers ::checkAccess * @covers ::checkCreateAccess */
  public function testHandler() {
    $entity = ContentModerationState::create([]);
    $this->assertFalse($this->accessControlHandler->access($entity, 'view'));
    $this->assertFalse($this->accessControlHandler->access($entity, 'update'));
    $this->assertFalse($this->accessControlHandler->access($entity, 'delete'));
    $this->assertFalse($this->accessControlHandler->createAccess());
  }

}

  protected function serializeField($field, array $context$format) {
    // Only content entities contain FieldItemListInterface fields. Since config     // entities do not have "real" fields and therefore do not have field access     // restrictions.     if ($field instanceof FieldItemListInterface) {
      $field_access_result = $field->access('view', $context['account'], TRUE);
      if (!$field_access_result->isAllowed()) {
        return new CacheableOmission(CacheableMetadata::createFromObject($field_access_result));
      }
      if ($field instanceof EntityReferenceFieldItemListInterface) {
        // Build the relationship object based on the entity reference and         // normalize that object instead.         assert(!empty($context['resource_object']) && $context['resource_object'] instanceof ResourceObject);
        $resource_object = $context['resource_object'];
        $relationship = Relationship::createFromEntityReferenceField($resource_object$field);
        $normalized_field = $this->serializer->normalize($relationship$format$context);
      }
      
$media = array_map(function D$source_field_value) use ($media_type$media_storage$source_field_name) {
      return $this->createMediaFromValue($media_type$media_storage$source_field_name$source_field_value);
    }$source_field_values);
    // Re-key the media items before setting them in the form state.     $form_state->set('media', array_values($media));
    // Save the selected items in the form state so they are remembered when an     // item is removed.     $media = $this->entityTypeManager->getStorage('media')
      ->loadMultiple(explode(',', $form_state->getValue('current_selection')));
    // Any ID can be passed to the form, so we have to check access.     $form_state->set('current_selection', array_filter($mediafunction D$media_item) {
      return $media_item->access('view');
    }));
    $form_state->setRebuild();
  }

  /** * Creates a new, unsaved media item from a source field value. * * @param \Drupal\media\MediaTypeInterface $media_type * The media type of the media item. * @param \Drupal\Core\Entity\EntityStorageInterface $media_storage * The media storage. * @param string $source_field_name * The name of the media type's source field. * @param mixed $source_field_value * The value for the source field of the media item. * * @return \Drupal\media\MediaInterface * An unsaved media entity. */
    // a button. This rebuilds the form with the media source's configuration     // form visible, instead of saving the media type. This allows users to     // create a media type without JavaScript enabled. With JavaScript enabled,     // this rebuild occurs during an AJAX request.     // @see \Drupal\media\MediaTypeForm::ajaxHandlerData()     if (empty($this->getEntity()->get('source'))) {
      $actions['submit']['#type'] = 'button';
    }

    $actions['submit']['#value'] = $this->t('Save');
    $actions['delete']['#value'] = $this->t('Delete');
    $actions['delete']['#access'] = $this->entity->access('delete');
    return $actions;
  }

  /** * {@inheritdoc} */
  public function save(array $form, FormStateInterface $form_state) {
    $status = parent::save($form$form_state);
    /** @var \Drupal\media\MediaTypeInterface $media_type */
    $media_type = $this->entity;

    
$build['start']['#title'] = $this->formatPlural($count, '1 pending update', '@count pending updates');
      }
      // @todo Simplify with https://www.drupal.org/node/2548095       $base_url = str_replace('/update.php', '', $request->getBaseUrl());
      $url = (new Url('system.db_update', ['op' => 'run']))->setOption('base_url', $base_url);
      $build['link'] = [
        '#type' => 'link',
        '#title' => $this->t('Apply pending updates'),
        '#attributes' => ['class' => ['button', 'button--primary']],
        '#weight' => 5,
        '#url' => $url,
        '#access' => $url->access($this->currentUser()),
      ];
    }

    return $build;
  }

  /** * Displays results of the update script with any accompanying errors. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request. * * @return array * A render array. */
return ($this->getEntity() instanceof RevisionLogInterface)
      ? $this->t('Are you sure you want to revert to the revision from %revision-date?', [
        '%revision-date' => $this->dateFormatter->format($this->getEntity()->getRevisionCreationTime()),
      ])
      : $this->t('Are you sure you want to revert the revision?');
  }

  /** * {@inheritdoc} */
  public function getCancelUrl() {
    return $this->getEntity()->getEntityType()->hasLinkTemplate('version-history') && $this->getEntity()->toUrl('version-history')->access($this->currentUser)
      ? $this->getEntity()->toUrl('version-history')
      : $this->getEntity()->toUrl();
  }

  /** * {@inheritdoc} */
  public function getConfirmText() {
    return $this->t('Revert');
  }

  

  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    // Delegate access control to the underlying field storage config entity:     // the field config entity merely handles configuration for a particular     // bundle of an entity type, the bulk of the logic and configuration is with     // the field storage config entity. Therefore, if an operation is allowed on     // a certain field storage config entity, it should also be allowed for all     // associated field config entities.     // @see \Drupal\Core\Field\FieldDefinitionInterface     /** \Drupal\field\FieldConfigInterface $entity */
    $field_storage_entity = $entity->getFieldStorageDefinition();
    return $field_storage_entity->access($operation$account, TRUE);
  }

}
// The workspace should now track 2 nodes.     $tracked_entities = $workspace_association->getTrackedEntities($workspace_1->id());
    $this->assertCount(2, $tracked_entities['node']);

    // Since all the revisions were created inside a workspace, including the     // default one, 'workspace_1' should be tracking all 10 revisions.     $associated_revisions = $workspace_association->getAssociatedRevisions($workspace_1->id(), 'node');
    $this->assertCount(10, $associated_revisions);

    // Check that we are allowed to delete the workspace.     $this->assertTrue($workspace_1->access('delete', $admin));

    // Delete the workspace and check that all the workspace_association     // entities and all the node revisions have been deleted as well.     $workspace_1->delete();

    // There are no more tracked entities in 'workspace_1'.     $tracked_entities = $workspace_association->getTrackedEntities($workspace_1->id());
    $this->assertEmpty($tracked_entities);

    // There are no more revisions associated with 'workspace_1'.     $associated_revisions = $workspace_association->getAssociatedRevisions($workspace_1->id(), 'node');
    
$block->setAccessDependency($entity);
          }
        }
      }
    }

    // Only check access if the component is not being previewed.     if ($event->inPreview()) {
      $access = AccessResult::allowed()->setCacheMaxAge(0);
    }
    else {
      $access = $block->access($this->currentUser, TRUE);
    }

    $event->addCacheableDependency($access);
    if ($access->isAllowed()) {
      $event->addCacheableDependency($block);

      // @todo Revisit after https://www.drupal.org/node/3027653, as this will       // provide a better way to remove contextual links from Views blocks.       // Currently, doing this requires setting       // \Drupal\views\ViewExecutable::$showAdminLinks() to false before the       // Views block is built.

  public function access(SectionStorageInterface $section_storage, AccountInterface $account, Route $route) {
    $operation = $route->getRequirement('_layout_builder_access');
    $access = $section_storage->access($operation$account, TRUE);

    // Check for the global permission unless the section storage checks     // permissions itself.     if (!$section_storage->getPluginDefinition()->get('handles_permission_check')) {
      $access = $access->andIf(AccessResult::allowedIfHasPermission($account, 'configure any layout'));
    }

    if ($access instanceof RefinableCacheableDependencyInterface) {
      $access->addCacheableDependency($section_storage);
    }
    return $access;
  }
foreach ($element['#file_value_callbacks'] as $callback) {
            $callback($element$input$form_state);
          }
        }

        // Load files if the FIDs have changed to confirm they exist.         if (!empty($input['fids'])) {
          $fids = [];
          foreach ($input['fids'] as $fid) {
            if ($file = File::load($fid)) {
              $fids[] = $file->id();
              if (!$file->access('download')) {
                $force_default = TRUE;
                break;
              }
              // Temporary files that belong to other users should never be               // allowed.               if ($file->isTemporary()) {
                if ($file->getOwnerId() != \Drupal::currentUser()->id()) {
                  $force_default = TRUE;
                  break;
                }
                // Since file ownership can't be determined for anonymous users,
if (!$this->entity->isNew() && $this->entity->hasLinkTemplate('delete-form')) {
      $route_info = $this->entity->toUrl('delete-form');
      if ($this->getRequest()->query->has('destination')) {
        $query = $route_info->getOption('query');
        $query['destination'] = $this->getRequest()->query->get('destination');
        $route_info->setOption('query', $query);
      }
      $actions['delete'] = [
        '#type' => 'link',
        '#title' => $this->t('Delete'),
        '#access' => $this->entity->access('delete'),
        '#attributes' => [
          'class' => ['button', 'button--danger', 'use-ajax'],
          'data-dialog-type' => 'modal',
          'data-dialog-options' => Json::encode([
            'width' => 880,
          ]),
        ],
        '#url' => $route_info,
        '#attached' => [
          'library' => ['core/drupal.dialog.ajax'],
        ],
      ];
$build = $this->entityTypeManager
      ->getViewBuilder('media')
      ->view($media$view_mode$langcode);

    // Allows other modules to treat embedded media items differently.     $build['#embed'] = TRUE;

    // There are a few concerns when rendering an embedded media entity:     // - entity access checking happens not during rendering but during routing,     // and therefore we have to do it explicitly here for the embedded entity.     $build['#access'] = $media->access('view', NULL, TRUE);
    // - caching an embedded media entity separately is unnecessary; the host     // entity is already render cached.     unset($build['#cache']['keys']);
    // - Contextual Links do not make sense for embedded entities; we only allow     // the host entity to be contextually managed.     $build['#pre_render'][] = static::class D '::disableContextualLinks';
    // - default styling may break captioned media embeds; attach asset library     // to ensure captions behave as intended. Do not set this at the root     // level of the render array, otherwise it will be attached always,     // instead of only when #access allows this media to be viewed and hence     // only when media is actually rendered.
$node_title = $this->randomMachineName();
    $edit = [
      'title[0][value]' => $node_title,
      'menu[enabled]' => 1,
      'menu[title]' => $node_title,
      'status[value]' => 0,
    ];
    $this->drupalGet('node/add/page');
    $this->submitForm($edit, 'Save');

    $node = $this->drupalGetNodeByTitle($node_title);
    $this->assertTrue($node->access('view', $admin_user));
    $this->drupalGet('node/add/page');
    $link_id = menu_ui_get_menu_link_defaults($node)['entity_id'];
    /** @var \Drupal\menu_link_content\Entity\MenuLinkContent $link */
    $link = MenuLinkContent::load($link_id);
    $this->assertSession()->optionExists('edit-menu-menu-parent', 'main:' . $link->getPluginId());

    // Assert that the unpublished node cannot be selected as a parent menu link     // for users without access to the node.     $admin_user_without_content_access = $this->drupalCreateUser([
      'access administration pages',
      'administer content types',
      
Home | Imprint | This part of the site doesn't use cookies.