isAllowed example

if (!$privileges) {
            return;
        }

        $context = $request->attributes->get(PlatformRequest::ATTRIBUTE_CONTEXT_OBJECT);
        if (!$context instanceof Context) {
            throw ApiException::missingPrivileges([]);
        }

        foreach ($privileges as $privilege) {
            if ($privilege === 'app') {
                if ($context->isAllowed('app.all')) {
                    return;
                }

                $privilege = $this->getAppPrivilege($request);
            }

            if (!$context->isAllowed($privilege)) {
                throw ApiException::missingPrivileges([$privilege]);
            }
        }
    }

    

  protected function checkAccess(Request $request) {
    // The cacheability (if any) of this request's access check result must be     // applied to the response.     $access_result = $this->accessManager->checkRequest($request$this->account, TRUE);
    // Allow a master request to set the access result for a subrequest: if an     // access result attribute is already set, don't overwrite it.     if (!$request->attributes->has(AccessAwareRouterInterface::ACCESS_RESULT)) {
      $request->attributes->set(AccessAwareRouterInterface::ACCESS_RESULT, $access_result);
    }
    if (!$access_result->isAllowed()) {
      if ($access_result instanceof CacheableDependencyInterface && $request->isMethodCacheable()) {
        throw new CacheableAccessDeniedHttpException($access_result$access_result instanceof AccessResultReasonInterface ? $access_result->getReason() : '');
      }
      else {
        throw new AccessDeniedHttpException($access_result instanceof AccessResultReasonInterface ? $access_result->getReason() : '');
      }
    }
  }

  /** * {@inheritdoc} */

  public function __construct(FloodInterface $flood, EventDispatcherInterface $event_dispatcher, RequestStack $request_stack) {
    $this->flood = $flood;
    $this->eventDispatcher = $event_dispatcher;
    $this->requestStack = $request_stack;
  }

  /** * {@inheritdoc} */
  public function isAllowed($name$threshold$window = 3600, $identifier = NULL) {
    if ($this->flood->isAllowed($name$threshold$window$identifier)) {
      return TRUE;
    }
    // Register flood control blocked login event.     $event_map['user.failed_login_ip'] = UserEvents::FLOOD_BLOCKED_IP;
    $event_map['user.failed_login_user'] = UserEvents::FLOOD_BLOCKED_USER;
    $event_map['user.http_login'] = UserEvents::FLOOD_BLOCKED_USER;

    if (isset($event_map[$name])) {
      if (empty($identifier)) {
        $identifier = $this->requestStack->getCurrentRequest()->getClientIp();
      }
      
    $requirements = [
      '_access' => $condition_one,
      '_test_access' => $condition_two,
    ];
    $route = new Route($name[]$requirements);
    $route_collection->add($name$route);

    $this->checkProvider->setChecks($route_collection);
    $this->setupAccessArgumentsResolverFactory();

    $route_match = new RouteMatch($name$route[][]);
    $this->assertEquals($expected_access->isAllowed()$this->accessManager->check($route_match$this->account));
    $this->assertEquals($expected_access$this->accessManager->check($route_match$this->account, NULL, TRUE));
  }

  /** * Tests the checkNamedRoute method. * * @see \Drupal\Core\Access\AccessManager::checkNamedRoute() */
  public function testCheckNamedRoute() {
    $this->setupAccessChecker();
    $this->checkProvider->setChecks($this->routeCollection);
    
$this->flood = new MemoryBackend($request);
  }

  /** * Tests an allowed flood event. */
  public function testAllowedProceeding() {
    $threshold = 2;
    $window_expired = -1;

    $this->flood->register('test_event', $window_expired);
    $this->assertTrue($this->flood->isAllowed('test_event', $threshold));
  }

  /** * Tests a flood event with more than the allowed calls. */
  public function testNotAllowedProceeding() {
    $threshold = 1;
    $window_expired = -1;

    // Register the event twice, so it is not allowed to proceed.     $this->flood->register('test_event', $window_expired);
    
        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.");
        }
        return $access_result;

      case 'delete':
        // Users with 'cancel account' permission can cancel their own account.         return AccessResult::allowedIfHasPermission($account, 'cancel account')
          ->andIf(AccessResult::allowedIf($account->id() == $entity->id())->cachePerUser());
    }

    // No opinion.

  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);
      }
      else {
        


    // 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.     $access->addCacheableDependency($contact_account);
    if ($contact_account->isBlocked()) {
      return $access;
    }

    // Forbid access if the requested user has disabled their contact form.     $account_data = $this->userData->get('contact', $contact_account->id(), 'enabled');
    
return $entityDefinition;
    }

    private function validateAclPermissions(Context $context, EntityDefinition $entity, string $privilege): ?string
    {
        $resource = $entity->getEntityName();

        if ($entity instanceof EntityTranslationDefinition) {
            $resource = $entity->getParentDefinition()->getEntityName();
        }

        if (!$context->isAllowed($resource . ':' . $privilege)) {
            return $resource . ':' . $privilege;
        }

        return null;
    }

    /** * @param list<EntityPathSegment> $pathSegments * * @return array<string|null> */
    
assert(in_array($field_operation['view', 'edit'], TRUE));
    $entity_operation = $field_operation === 'view' ? 'view' : 'update';
    if ($resource_type = $route_match->getParameter(Routes::RESOURCE_TYPE_KEY)) {
      assert($resource_type instanceof ResourceType);
      $entity = $route_match->getParameter('entity');
      $internal_name = $resource_type->getInternalName($relationship_field_name);
      if ($entity instanceof FieldableEntityInterface && $entity->hasField($internal_name)) {
        $entity_access = $this->entityAccessChecker->checkEntityAccess($entity$entity_operation$account);
        $field_access = $entity->get($internal_name)->access($field_operation$account, TRUE);
        // Ensure that access is respected for different entity revisions.         $access_result = $entity_access->andIf($field_access);
        if (!$access_result->isAllowed()) {
          $reason = "The current user is not allowed to {$field_operation} this relationship.";
          $access_reason = $access_result instanceof AccessResultReasonInterface ? $access_result->getReason() : NULL;
          $detailed_reason = empty($access_reason) ? $reason : $reason . " {$access_reason}";
          $access_result->setReason($detailed_reason);
        }
        return $access_result;
      }
    }
    return AccessResult::neutral();
  }

}
        if (!$app->isActive() && !($event instanceof AppChangedEvent || $event instanceof AppDeletedEvent)) {
            return false;
        }

        if (!($this->privileges[$event->getName()] ?? null)) {
            $this->loadPrivileges($event->getName()$affectedRoles);
        }

        $privileges = $this->privileges[$event->getName()][$app->getAclRoleId()]
            ?? new AclPrivilegeCollection([]);

        if (!$event->isAllowed($app->getId()$privileges)) {
            return false;
        }

        return true;
    }

    /** * @param array<string> $affectedRoleIds */
    private function callWebhooksSynchronous(
        WebhookCollection $webhooksForEvent,
        
/** @var \Drupal\Core\Authentication\AuthenticationManager $authentication_manager */
    $authentication_manager = $this->getContainer()->get('authentication');
    $account = $authentication_manager->authenticate($request) ?: new AnonymousUserSession();

    /** @var \Drupal\Core\Session\AccountProxyInterface $current_user */
    $current_user = $this->getContainer()->get('current_user');
    $current_user->setAccount($account);

    /** @var \Drupal\system\Access\DbUpdateAccessCheck $db_update_access */
    $db_update_access = $this->getContainer()->get('access_check.db_update');

    if (!Settings::get('update_free_access', FALSE) && !$db_update_access->access($account)->isAllowed()) {
      throw new AccessDeniedHttpException('In order to run update.php you need to either have "Administer software updates" permission or have set $settings[\'update_free_access\'] in your settings.php.');
    }
  }

}
$entity->setDefaultLangcode('site_default');
    $entity->save();

    return $entity;
  }

  /** * {@inheritdoc} */
  protected static function getExpectedCollectionCacheability(AccountInterface $account, array $collection, array $sparse_fieldset = NULL, $filtered = FALSE) {
    $cacheability = parent::getExpectedCollectionCacheability($account$collection$sparse_fieldset$filtered);
    if (static::entityAccess(reset($collection), 'view', $account)->isAllowed()) {
      $cacheability->addCacheContexts(['languages:language_interface']);
    }
    return $cacheability;
  }

}

  protected function assertMediaLibraryStateAccess(bool $access, AccountInterface $user, MediaLibraryState $state): void {
    $ui_builder = $this->container->get('media_library.ui_builder');
    $access_result = $ui_builder->checkAccess($user$state);
    $this->assertEquals($access$access_result->isAllowed());
  }

  /** * Build the media library widget form. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity to build the form for. * * @return array * A built form array of the media library widget. */
  
if (!empty($element['#autocomplete_query_parameters'])) {
        $options['query'] = $element['#autocomplete_query_parameters'];
      }
      $url = Url::fromRoute($element['#autocomplete_route_name']$parameters$options)->toString(TRUE);
      /** @var \Drupal\Core\Access\AccessManagerInterface $access_manager */
      $access_manager = \Drupal::service('access_manager');
      $access = $access_manager->checkNamedRoute($element['#autocomplete_route_name']$parameters, \Drupal::currentUser(), TRUE);
    }

    if ($access) {
      $metadata = BubbleableMetadata::createFromRenderArray($element);
      if ($access->isAllowed()) {
        $element['#attributes']['class'][] = 'form-autocomplete';
        $metadata->addAttachments(['library' => ['core/drupal.autocomplete']]);
        // Provide a data attribute for the JavaScript behavior to bind to.         $element['#attributes']['data-autocomplete-path'] = $url->getGeneratedUrl();
        $metadata = $metadata->merge($url);
      }
      $metadata
        ->merge(BubbleableMetadata::createFromObject($access))
        ->applyTo($element);
    }

    
Home | Imprint | This part of the site doesn't use cookies.