getClientIp example

public function __construct(private readonly Request $request)
    {
    }

    /** * The ip method returns the real client ip address * * @return string|null request client ip address */
    public function ip(): ?string
    {
        return $this->request->getClientIp();
    }

    /** * The scheme method returns the request scheme * * @return string request scheme */
    public function scheme(): string
    {
        return $this->request->getScheme();
    }

    
$currentController$userAgent,
                $userId$sessionId,
            ]);
        }
    }

    /** * @return bool */
    public function shouldRefreshLog(Enlight_Controller_Request_Request $request)
    {
        if ($request->getClientIp() === null
            || !empty(Shopware()->Session()->get('Bot'))
        ) {
            return false;
        }
        if (!empty($this->Config()->get('blockIp'))
            && strpos($this->Config()->get('blockIp')$request->getClientIp()) !== false
        ) {
            return false;
        }

        return true;
    }
throw RoutingException::missingRequestParameter('message');
        }

        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,
            
/** * {@inheritdoc} */
  public static function getLabel() {
    return t('IP address');
  }

  /** * {@inheritdoc} */
  public function getContext() {
    return $this->requestStack->getCurrentRequest()->getClientIp();
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }

}

  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  /** * {@inheritdoc} */
  public function register($name$window = 3600, $identifier = NULL) {
    if (!isset($identifier)) {
      $identifier = $this->requestStack->getCurrentRequest()->getClientIp();
    }
    // We can't use REQUEST_TIME here, because that would not guarantee     // uniqueness.     $time = microtime(TRUE);
    $this->events[$name][$identifier][] = ['expire' => $time + $window, 'time' => $time];
  }

  /** * {@inheritdoc} */
  public function clear($name$identifier = NULL) {
    
public function matches(Request $request): bool
    {
        if (!isset($this->language)) {
            throw new \LogicException('Unable to match the request as the expression language is not available. Try running "composer require symfony/expression-language".');
        }

        return $this->language->evaluate($this->expression, [
            'request' => $request,
            'method' => $request->getMethod(),
            'path' => rawurldecode($request->getPathInfo()),
            'host' => $request->getHost(),
            'ip' => $request->getClientIp(),
            'attributes' => $request->attributes->all(),
        ]) && parent::matches($request);
    }
}
$request = Request::create('/');
        $request->server->set('REMOTE_ADDR', '10.0.0.1');
        $request->headers->set('X-Forwarded-For', '10.0.0.2');
        $request->headers->set('X-Forwarded-Host', 'Good');
        $request->headers->set('X-Forwarded-Port', '1234');
        $request->headers->set('X-Forwarded-Proto', 'https');
        $request->headers->set('X-Forwarded-Prefix', '/admin');

        $kernel = new TestSubRequestHandlerKernel(function D$request$type$catch) {
            $this->assertSame('127.0.0.1', $request->server->get('REMOTE_ADDR'));
            $this->assertSame('10.0.0.2', $request->getClientIp());
            $this->assertSame('Good', $request->headers->get('X-Forwarded-Host'));
            $this->assertSame('1234', $request->headers->get('X-Forwarded-Port'));
            $this->assertSame('https', $request->headers->get('X-Forwarded-Proto'));
            $this->assertSame('/admin', $request->headers->get('X-Forwarded-Prefix'));
        });

        SubRequestHandler::handle($kernel$request, HttpKernelInterface::MAIN_REQUEST, true);

        $this->assertSame($globalState$this->getGlobalState());
    }

    
throw CustomerException::customerNotFoundByHash($hash);
        }

        $customer = $customerRecovery->getCustomer();

        if (!$customer) {
            throw CustomerException::customerNotFoundByHash($hash);
        }

        // reset login and pw-reset limit when password was changed         if (($request = $this->requestStack->getMainRequest()) !== null) {
            $cacheKey = strtolower((string) $customer->getEmail()) . '-' . $request->getClientIp();

            $this->rateLimiter->reset(RateLimiter::LOGIN_ROUTE, $cacheKey);
            $this->rateLimiter->reset(RateLimiter::RESET_PASSWORD, $cacheKey);
        }

        $customerData = [
            'id' => $customer->getId(),
            'password' => $data->get('newPassword'),
            'legacyPassword' => null,
            'legacyEncoder' => null,
        ];

        
/** * @deprecated - Will be private with Shopware 5.8 * * @param Request $request * * @return void */
    protected function initServiceMode($request)
    {
        $config = $this->get(Shopware_Components_Config::class);
        if (!empty($config->get('setOffline'))
            && !str_contains($config->get('offlineIp')$request->getClientIp())
            && $request->getControllerName() !== 'error'
        ) {
            $request->setControllerName('error')->setActionName('service')->setDispatched(false);
        }
    }

    /** * @deprecated - Will be private with Shopware 5.8 * * @param Request $request * @param Enlight_Controller_Response_ResponseHttp $response * * @return void */

        $email = $data->get('email', $data->get('username'));

        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,
                
public function testInconsistentClientIpsOnMainRequests()
    {
        $this->expectException(BadRequestHttpException::class);
        $request = new Request();
        $request->setTrustedProxies(['1.1.1.1'], Request::HEADER_X_FORWARDED_FOR | Request::HEADER_FORWARDED);
        $request->server->set('REMOTE_ADDR', '1.1.1.1');
        $request->headers->set('FORWARDED', 'for=2.2.2.2');
        $request->headers->set('X_FORWARDED_FOR', '3.3.3.3');

        $dispatcher = new EventDispatcher();
        $dispatcher->addListener(KernelEvents::REQUEST, function D$event) {
            $event->getRequest()->getClientIp();
        });

        $kernel = $this->getHttpKernel($dispatcher);
        $kernel->handle($request$kernel::MAIN_REQUEST, false);

        Request::setTrustedProxies([], -1);
    }

    private function getHttpKernel(EventDispatcherInterface $eventDispatcher$controller = null, RequestStack $requestStack = null, array $arguments = [], bool $handleAllThrowables = false)
    {
        $controller ??= fn () => new Response('Hello');

        
public function matches(Request $request): bool
    {
        if (!isset($this->language)) {
            throw new \LogicException('Unable to match the request as the expression language is not available. Try running "composer require symfony/expression-language".');
        }

        return $this->language->evaluate($this->expression, [
            'request' => $request,
            'method' => $request->getMethod(),
            'path' => rawurldecode($request->getPathInfo()),
            'host' => $request->getHost(),
            'ip' => $request->getClientIp(),
            'attributes' => $request->attributes->all(),
        ]) && parent::matches($request);
    }
}

        $request = $this->requestStack
            ->getMainRequest();

        if (!$request) {
            return;
        }

        $this->customerRepository->update([
            [
                'id' => $event->getCustomer()->getId(),
                'remoteAddress' => $request->getClientIp(),
            ],
        ]$event->getContext());
    }
}

        if (false === $this->enabled) {
            return null;
        }

        $profile = new Profile(substr(hash('sha256', uniqid(mt_rand(), true)), 0, 6));
        $profile->setTime(time());
        $profile->setUrl($request->getUri());
        $profile->setMethod($request->getMethod());
        $profile->setStatusCode($response->getStatusCode());
        try {
            $profile->setIp($request->getClientIp());
        } catch (ConflictingHeadersException) {
            $profile->setIp('Unknown');
        }

        if ($prevToken = $response->headers->get('X-Debug-Token')) {
            $response->headers->set('X-Previous-Debug-Token', $prevToken);
        }

        $response->headers->set('X-Debug-Token', $profile->getToken());

        foreach ($this->collectors as $collector) {
            
$request->query->set('_method', ['delete', 'patch']);
        $this->assertSame('POST', $request->getMethod(), '->getMethod() returns the request method if invalid type is defined in query');
    }

    /** * @dataProvider getClientIpsProvider */
    public function testGetClientIp($expected$remoteAddr$httpForwardedFor$trustedProxies)
    {
        $request = $this->getRequestInstanceForClientIpTests($remoteAddr$httpForwardedFor$trustedProxies);

        $this->assertEquals($expected[0]$request->getClientIp());
    }

    /** * @dataProvider getClientIpsProvider */
    public function testGetClientIps($expected$remoteAddr$httpForwardedFor$trustedProxies)
    {
        $request = $this->getRequestInstanceForClientIpTests($remoteAddr$httpForwardedFor$trustedProxies);

        $this->assertEquals($expected$request->getClientIps());
    }

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