ensureAccepted example

public function __construct(
        private readonly UserRecoveryService $userRecoveryService,
        private readonly RateLimiter $rateLimiter
    ) {
    }

    #[Route(path: '/api/_action/user/user-recovery', defaults: ['auth_required' => false], name: 'api.action.user.user-recovery', methods: ['POST'])]     public function createUserRecovery(Request $request, Context $context): Response
    {
        $email = (string) $request->request->get('email');

        $this->rateLimiter->ensureAccepted(
            RateLimiter::USER_RECOVERY,
            strtolower($email) . '-' . $request->getClientIp()
        );

        $this->userRecoveryService->generateUserRecovery($email$context);

        return new Response();
    }

    #[Route(path: '/api/_action/user/user-recovery/hash', defaults: ['auth_required' => false], name: 'api.action.user.user-recovery.hash', methods: ['GET'])]     public function checkUserRecovery(Request $request, Context $context): Response
    {
public function getDecorated(): AbstractSendPasswordRecoveryMailRoute
    {
        throw new DecorationPatternException(self::class);
    }

    #[Route(path: '/store-api/account/recovery-password', name: 'store-api.account.recovery.send.mail', methods: ['POST'])]     public function sendRecoveryMail(RequestDataBag $data, SalesChannelContext $context, bool $validateStorefrontUrl = true): SuccessResponse
    {
        $this->validateRecoverEmail($data$context$validateStorefrontUrl);

        if (($request = $this->requestStack->getMainRequest()) !== null) {
            $this->rateLimiter->ensureAccepted(RateLimiter::RESET_PASSWORD, strtolower($data->get('email') . '-' . $request->getClientIp()));
        }

        $customer = $this->getCustomerByEmail($data->get('email')$context);
        $customerId = $customer->getId();

        $customerIdCriteria = new Criteria();
        $customerIdCriteria->addFilter(new EqualsFilter('customerId', $customerId));
        $customerIdCriteria->addAssociation('customer.salutation');

        $repoContext = $context->getContext();

        
public function getDecorated(): AbstractContactFormRoute
    {
        throw new DecorationPatternException(self::class);
    }

    #[Route(path: '/store-api/contact-form', name: 'store-api.contact.form', methods: ['POST'])]     public function load(RequestDataBag $data, SalesChannelContext $context): ContactFormRouteResponse
    {
        $this->validateContactForm($data$context);

        if (($request = $this->requestStack->getMainRequest()) !== null && $request->getClientIp() !== null) {
            $this->rateLimiter->ensureAccepted(RateLimiter::CONTACT_FORM, $request->getClientIp());
        }

        $mailConfigs = $this->getMailConfigs($context$data->get('slotId')$data->get('navigationId')$data->get('entityName'));

        $salutationCriteria = new Criteria([$data->get('salutationId')]);
        $salutationSearchResult = $this->salutationRepository->search($salutationCriteria$context->getContext());

        if ($salutationSearchResult->count() !== 0) {
            $data->set('salutation', $salutationSearchResult->first());
        }

        
if ($doubleOptInDomain !== '') {
            $dataBag->set('storefrontUrl', $doubleOptInDomain);
            $validateStorefrontUrl = false;
        }

        $validator = $this->getOptInValidator($dataBag$context$validateStorefrontUrl);

        $this->validator->validate($dataBag->all()$validator);

        if (($request = $this->requestStack->getMainRequest()) !== null && $request->getClientIp() !== null) {
            try {
                $this->rateLimiter->ensureAccepted(RateLimiter::NEWSLETTER_FORM, $request->getClientIp());
            } catch (RateLimitExceededException $e) {
                if (!Feature::isActive('v6.6.0.0')) {
                    throw $e;
                }

                throw NewsletterException::newsletterThrottled($e->getWaitTime());
            }
        }

        /** @var SubscribeRequest $data */
        $data = $dataBag->only(
            

    }

    #[Route(path: '/api/oauth/token', name: 'api.oauth.token', defaults: ['auth_required' => false], methods: ['POST'])]     public function token(Request $request): Response
    {
        $response = new Response();

        try {
            $cacheKey = $request->get('username') . '-' . $request->getClientIp();

            $this->rateLimiter->ensureAccepted(RateLimiter::OAUTH, $cacheKey);
        } catch (RateLimitExceededException $exception) {
            throw new AuthThrottledException($exception->getWaitTime()$exception);
        }

        $psr7Request = $this->psrHttpFactory->createRequest($request);
        $psr7Response = $this->psrHttpFactory->createResponse($response);

        $response = $this->authorizationServer->respondToAccessTokenRequest($psr7Request$psr7Response);

        $this->rateLimiter->reset(RateLimiter::OAUTH, $cacheKey);

        
if (empty($email) || empty($data->get('password'))) {
            throw CustomerException::badCredentials();
        }

        $event = new CustomerBeforeLoginEvent($context$email);
        $this->eventDispatcher->dispatch($event);

        if ($this->requestStack->getMainRequest() !== null) {
            $cacheKey = strtolower((string) $email) . '-' . $this->requestStack->getMainRequest()->getClientIp();

            try {
                $this->rateLimiter->ensureAccepted(RateLimiter::LOGIN_ROUTE, $cacheKey);
            } catch (RateLimitExceededException $exception) {
                throw CustomerException::customerAuthThrottledException($exception->getWaitTime()$exception);
            }
        }

        try {
            $customer = $this->accountService->getCustomerByLogin(
                $email,
                $data->get('password'),
                $context
            );
        }
// remove old orders only if there is a deeplink filter         if ($deepLinkFilter !== null) {
            $orders = $this->filterOldOrders($orders);
        }

        // Handle guest authentication if deeplink is set         if (!$context->getCustomer() && $deepLinkFilter instanceof EqualsFilter) {
            try {
                $cacheKey = strtolower((string) $deepLinkFilter->getValue()) . '-' . $request->getClientIp();

                $this->rateLimiter->ensureAccepted(RateLimiter::GUEST_LOGIN, $cacheKey);
            } catch (RateLimitExceededException $exception) {
                throw OrderException::customerAuthThrottledException($exception->getWaitTime()$exception);
            }

            $order = $orders->first();
            $this->checkGuestAuth($order$request);
        }

        if (isset($cacheKey)) {
            $this->rateLimiter->reset(RateLimiter::GUEST_LOGIN, $cacheKey);
        }

        
use Symfony\Component\RateLimiter\RateLimit;

/** * @group time-sensitive */
class RateLimitTest extends TestCase
{
    public function testEnsureAcceptedDoesNotThrowExceptionIfAccepted()
    {
        $rateLimit = new RateLimit(10, new \DateTimeImmutable(), true, 10);

        $this->assertSame($rateLimit$rateLimit->ensureAccepted());
    }

    public function testEnsureAcceptedThrowsRateLimitExceptionIfNotAccepted()
    {
        $rateLimit = new RateLimit(10, $retryAfter = new \DateTimeImmutable(), false, 10);

        try {
            $rateLimit->ensureAccepted();
        } catch (RateLimitExceededException $exception) {
            $this->assertSame($rateLimit$exception->getRateLimit());
            $this->assertSame(10, $exception->getRemainingTokens());
            


        if (!\is_array($requiredPrivileges)) {
            throw RoutingException::invalidRequestParameter('requiredPrivileges');
        }

        $integrationId = $source->getIntegrationId();
        $createdByUserId = $source->getUserId();

        try {
            $cacheKey = $createdByUserId ?? $integrationId . '-' . $request->getClientIp();
            $this->rateLimiter->ensureAccepted(self::NOTIFICATION, $cacheKey);
        } catch (RateLimitExceededException $exception) {
            throw new NotificationThrottledException($exception->getWaitTime()$exception);
        }

        $notificationId = Uuid::randomHex();
        $this->notificationService->createNotification([
            'id' => $notificationId,
            'status' => $status,
            'message' => $message,
            'adminOnly' => $adminOnly,
            'requiredPrivileges' => $requiredPrivileges,
            
$items = [];

            /** @var array<mixed> $item */
            foreach ($request->request->all('items') as $item) {
                $items[] = $this->lineItemFactory->create($item$context);
            }
        }

        foreach ($items as $item) {
            if ($request->getClientIp() !== null) {
                $cacheKey = ($item->getReferencedId() ?? $item->getId()) . '-' . $request->getClientIp();
                $this->rateLimiter->ensureAccepted(RateLimiter::CART_ADD_LINE_ITEM, $cacheKey);
            }

            $alreadyExists = $cart->has($item->getId());
            $cart->add($item);

            $this->eventDispatcher->dispatch(new BeforeLineItemAddedEvent($item$cart$context$alreadyExists));
        }

        $cart->markModified();

        $cart = $this->cartCalculator->calculate($cart$context);
        
Home | Imprint | This part of the site doesn't use cookies.