getClientIp() public méthode

This method can read the client IP address from the "X-Forwarded-For" header when trusted proxies were set via "setTrustedProxies()". The "X-Forwarded-For" header value is a comma+space separated list of IP addresses, the left-most being the original client, and each successive proxy that passed the request adding the IP address where it received the request from. If your reverse proxy uses a different header name than "X-Forwarded-For", ("Client-Ip" for instance), configure it via "setTrustedHeaderName()" with the "client-ip" key.
See also: getClientIps()
See also: http://en.wikipedia.org/wiki/X-Forwarded-For
public getClientIp ( ) : string
Résultat string The client IP address
 public function matches(Request $request)
 {
     if (!$this->language) {
         throw new \LogicException('Unable to match the request as the expression language is not available.');
     }
     return $this->language->evaluate($this->expression, array('request' => $request, 'method' => $request->getMethod(), 'path' => rawurldecode($request->getPathInfo()), 'host' => $request->getHost(), 'ip' => $request->getClientIp(), 'attributes' => $request->attributes->all())) && parent::matches($request);
 }
Exemple #2
0
 /**
  * Executes the action with the given context.
  *
  * @param string $ip
  *   (optional) The IP address that should be banned.
  */
 public function doExecute($ip = NULL)
 {
     if (!isset($ip)) {
         $ip = $this->request->getClientIp();
     }
     $this->banManager->banIp($ip);
 }
Exemple #3
0
 /**
  * Sistema de almacenamiento de entradas a la pagina para reflejar el numero
  * de visitas.
  */
 public function getVisitasForViewAction(Request $req)
 {
     //Grabamos la visita en la BD
     $sess = $this->container->get('session');
     $now = array('ip' => $req->getClientIp(), 'visitas' => 0);
     if ($sess->has('visitas')) {
         $now = json_decode($sess->get('visitas'), TRUE);
         if ($req->getClientIp() == $now['ip']) {
             goto retorno;
         }
     }
     $em = $this->getDoctrine()->getManager();
     $visitas = $em->getRepository('AppBundle:Visitas')->findAll();
     if (count($visitas) == 0) {
         $visitas = new \AppBundle\Entity\Visitas();
         $visitas->setVisitas(1);
         goto lleno;
     }
     if (count($visitas) > 0) {
         $visitas = $visitas[0];
         $visitas->setVisitas($visitas->getVisitas() + 1);
     }
     lleno:
     $visitas->setIp($req->getClientIp());
     $visitas->setUpdated(new \DateTime('now'));
     $now['visitas'] = $visitas->getVisitas();
     $sess->set('visitas', json_encode($now));
     $em->persist($visitas);
     $em->flush();
     retorno:
     return $this->render('::/front/includes/visitas.html.twig', array('visitas' => $now['visitas']));
 }
Exemple #4
0
 /**
  * @param LoggerInterface $logger
  * @param Request         $request
  * @param array           $options
  */
 public function __construct(LoggerInterface $logger, Request $request, array $options = array())
 {
     $this->logger = $logger;
     $this->options = $this->configureOptions($options);
     $this->request = $request;
     $this->logger->debug('Create call with params ' . json_encode($this->options));
     $this->logger->debug('Request server values: ' . json_encode($this->request->server));
     $this->host = $this->request->getClientIp();
     $queryBag = $this->request->query;
     $this->securityCode = $queryBag->has('securityCodeFieldName') ? $queryBag->get('securityCodeFieldName') : '';
     $body = $this->request->getContent();
     if (!$body) {
         $this->logger->error('Event content is null');
         $this->valid = false;
         return;
     }
     $this->logger->debug('Event content: ' . $body);
     try {
         $json = json_decode($body, true);
     } catch (\Exception $e) {
         $this->logger->error('Exception on decode json text');
         $this->valid = false;
     }
     if (!isset($json['ref'])) {
         $this->valid = false;
         return;
     }
     $count = count($json['commits']) - 1;
     $this->author = $json['commits'][$count]['author']['email'];
     $this->authorName = $json['commits'][$count]['author']['name'];
     $this->message = $json['commits'][$count]['message'];
     $this->timestamp = $json['commits'][$count]['timestamp'];
     $this->repository = $json['repository'][$this->options['repositoryFieldName']];
     $this->branch = substr($json['ref'], strrpos($json['ref'], '/') + 1);
 }
Exemple #5
0
 /**
  * Returns the client IP address, try to find
  *
  * @param Request $request
  * @return string
  */
 protected function getClientIpAddress(Request $request)
 {
     $clientIP = $request->getClientIp(true);
     if (empty($clientIP)) {
         $clientIP = $request->getClientIp(false);
     }
     return $clientIP;
 }
Exemple #6
0
 /**
  * @param string $email
  * @param string $size
  * @param string $default
  *
  * @return string
  */
 public function getImage($email, $size = '250', $default = null)
 {
     $localDefault = $this->devMode || in_array($this->request->getClientIp(), array_merge($this->devHosts, ['127.0.0.1', 'fe80::1', '::1'])) ? 'https://www.mautic.org/media/images/default_avatar.png' : $this->avatarHelper->getDefaultAvatar(true);
     $url = 'https://www.gravatar.com/avatar/' . md5(strtolower(trim($email))) . '?s=' . $size;
     if ($default === null) {
         $default = $localDefault;
     }
     $default = strpos($default, '.') !== false && strpos($default, 'http') !== 0 ? UrlHelper::rel2abs($default) : $default;
     $url .= '&d=' . urlencode($default);
     return $url;
 }
 /**
  * @param SessionAccess $event
  */
 public function onSessionAccessEvent(SessionAccess $event)
 {
     $user = $event->getUser();
     $course = $event->getCourse();
     $session = $event->getSession();
     $ip = $this->request->getClientIp();
     $access = new TrackECourseAccess();
     $access->setCId($course->getId())->setUserId($user->getId())->setSessionId($session->getId())->setUserIp($ip);
     $this->em->persist($access);
     $this->em->flush();
 }
 public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
 {
     $login = new \Club\UserBundle\Entity\LoginAttempt();
     $login->setUsername($request->get('_username'));
     $login->setSession($request->getSession()->getId());
     $login->setIpAddress($request->getClientIp());
     $login->setHostname(gethostbyaddr($request->getClientIp()));
     $login->setLoginFailed(1);
     $this->em->persist($login);
     $this->em->flush();
     return new RedirectResponse('login');
 }
 public function onAuthenticationSuccess(Request $request, TokenInterface $token)
 {
     $login = new \Club\UserBundle\Entity\LoginAttempt();
     $login->setUsername($request->get('_username'));
     $login->setSession($request->getSession()->getId());
     $login->setIpAddress($request->getClientIp());
     $login->setHostname(gethostbyaddr($request->getClientIp()));
     $login->setLoginFailed(0);
     $this->em->persist($login);
     $this->em->flush();
     return new RedirectResponse('user');
 }
Exemple #10
0
 /**
  * {@inheritodc}
  */
 public function vote(TokenInterface $token, $object, array $attributes)
 {
     foreach ($attributes as $attribute) {
         if (!$this->supportsAttribute($attribute)) {
             continue;
         }
         if (in_array($this->request->getClientIp(), $this->whitelisted)) {
             return VoterInterface::ACCESS_GRANTED;
         }
         return VoterInterface::ACCESS_DENIED;
     }
     return VoterInterface::ACCESS_ABSTAIN;
 }
Exemple #11
0
 /**
  * Set the username from the security context by listening on core.request
  *
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (null === $this->request) {
         return;
     }
     // If you use a cache like Varnish, you may want to set a proxy to Request::getClientIp() method
     // $this->request->setTrustedProxies(array('127.0.0.1'));
     // $ip = $_SERVER['REMOTE_ADDR'];
     $ip = $this->request->getClientIp();
     if (null !== $ip) {
         $this->ipTraceableListener->setIpValue($ip);
     }
 }
Exemple #12
0
 public function testBuffer()
 {
     $logger = $this->getLogger(['buffer' => true, 'level' => \Psr\Log\LogLevel::ERROR]);
     $message = 'TEst MeSSage';
     $level = \Psr\Log\LogLevel::EMERGENCY;
     $message2 = 'TEst2 MeSSage2';
     $level2 = \Psr\Log\LogLevel::CRITICAL;
     $fullMsg = join(PHP_EOL, [join("\t", [date('c'), $this->request->getClientIp(), $level, $message]), join("\t", [date('c'), $this->request->getClientIp(), $level2, $message2])]);
     $this->storage->expects($this->once())->method('store')->with($fullMsg);
     $logger->emergency($message);
     $logger->critical($message2);
     $logger->flushBuffer();
 }
 /**
  * Checks if the passed value is valid.
  *
  * @param mixed $value The value that should be validated
  * @param Constraint $constraint The constraint for the validation
  *
  * @api
  */
 public function validate($value, Constraint $constraint)
 {
     $reCaptchaResponse = $this->request->request->get('g-recaptcha-response');
     if (empty($reCaptchaResponse)) {
         $this->context->addViolation($constraint->message);
         return;
     }
     $response = $this->buzz->submit('https://www.google.com/recaptcha/api/siteverify', ['secret' => $this->secret, 'response' => $reCaptchaResponse, 'remoteip' => $this->request->getClientIp()]);
     $reCaptchaValidationResponse = json_decode($response->getContent());
     if (true !== $reCaptchaValidationResponse->success) {
         $this->context->addViolation($constraint->message);
     }
 }
 /**
  * @Route("/opcache-clear/{version}/", name="_enuygun_com_opcache_clear")
  * @param Request $request
  * @param $version
  * @return array
  */
 public function opcacheClearAction(Request $request, $version)
 {
     $ipFilter = $this->container->getParameter('enuygun_com_opcache_clear.ip_filter');
     if (!empty($ipFilter) && !in_array($request->getClientIp(), $ipFilter)) {
         return new JsonResponse(array('success' => false, 'message' => $request->getClientIp() . ' is not allowed'), 400, array('x-enuygun-opcache-clear' => json_encode(array('success' => false, 'message' => $request->getClientIp() . ' is not allowed', 'version' => $version))));
     }
     if (!function_exists('opcache_reset')) {
         throw new \RuntimeException('Opcache extension is not enabled.');
     }
     $success = opcache_reset();
     $message = 'Opcache cleared: ' . ($success ? 'success' : 'failed');
     return new JsonResponse(array('success' => $success, 'message' => $message), 200, array('x-enuygun-opcache-clear' => json_encode(array('success' => $success, 'message' => $message, 'version' => $version))));
 }
 /**
  * {@inheritdoc}
  */
 public function validate($value, Constraint $constraint)
 {
     if (!$constraint instanceof ReCaptchaConstraint) {
         throw new InvalidArgumentException('Use ReCaptchaConstraint for ReCaptchaValidator.');
     }
     if ($this->request->get('g-recaptcha-response', false)) {
         $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $this->privateKey . "&response=" . $this->request->get('g-recaptcha-response', false) . "&remoteip=" . $this->request->getClientIp()));
         if (!$response->success) {
             $this->context->addViolationAt('recaptcha', $constraint->message);
         }
     } else {
         $this->context->addViolationAt('recaptcha', $constraint->message);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function validate($value, Constraint $constraint)
 {
     if (!$constraint instanceof ReCaptchaConstraint) {
         throw new InvalidArgumentException('Use ReCaptchaConstraint for ReCaptchaValidator.');
     }
     if ($this->request->get('g-recaptcha-response', false)) {
         $reCaptcha = new ReCaptcha($this->privateKey, $this->request->getClientIp(), $this->request->get('g-recaptcha-response', false));
         $response = $reCaptcha->buildRequest($this->driver)->send();
         if (!$response->isSuccess()) {
             $this->context->addViolation($constraint->message);
         }
     } else {
         $this->context->addViolation($constraint->message);
     }
 }
 /**
  * {@inheritDoc}
  */
 public function execute($request)
 {
     /** @var $request GetHttpRequest */
     RequestNotSupportedException::assertSupports($this, $request);
     if (false == $this->httpRequest) {
         return;
     }
     $request->query = $this->httpRequest->query->all();
     $request->request = $this->httpRequest->request->all();
     $request->headers = $this->httpRequest->headers->all();
     $request->method = $this->httpRequest->getMethod();
     $request->uri = $this->httpRequest->getUri();
     $request->clientIp = $this->httpRequest->getClientIp();
     $request->userAgent = $this->httpRequest->headers->get('User-Agent');
 }
 public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
 {
     $data = ['request-id' => $request->headers->get('X-Request-Id'), 'datetime' => date('Y-m-d H:i:s'), 'method' => $request->getMethod(), 'scheme' => $request->getScheme(), 'host' => $request->getHttpHost(), 'uri' => $request->getRequestUri(), 'route' => $request->get('_route')];
     /*
     if (isset($this['current_user'])) {
         $data['username'] = $this['current_user']->getName();
     }
     */
     $data['address'] = $request->getClientIp();
     if ($request->getSession()) {
         $data['session-id'] = $request->getSession()->getId();
     }
     if ($request->headers->has('User-Agent')) {
         $data['agent'] = $request->headers->get('User-Agent');
     }
     if ($request->headers->has('referer')) {
         $data['referer'] = $request->headers->get('referer');
     }
     $this->log($data);
     $response = $this->app->handle($request, $type, $catch);
     /*
     // response details
     $data['status'] = $response->getStatusCode();
     if ($response->headers->has('Content-Type')) {
         $data['content-type'] = $response->headers->get('content-type');
     }
     */
     return $response;
 }
Exemple #19
0
 /**
  * @return PublishEventInterface
  */
 public function createPublishEvent()
 {
     $class = $this->getClass();
     $obj = new $class();
     $obj->setMachineIp($this->request->getClientIp());
     return $obj;
 }
 public function onRequest(Request $request)
 {
     $session = $request->getSession();
     list($id, $role) = $session->get('user', array(null, 'ROLE_ANONYMOUS'));
     if (null === $id && $request->cookies->has(Remember::REMEMBER_ME)) {
         if ($this->remember->check($request->cookies->get(Remember::REMEMBER_ME))) {
             list($id, $role) = $this->remember->getIt();
             $session->set('user', array($id, $role));
         }
     }
     $this->provider->setRole($role);
     if (!$this->provider->isAllowed($request->getPathInfo())) {
         throw new Exception\AccessDeniedException("Access denied to " . $request->getPathInfo());
     }
     if (null !== $id) {
         // Ban check
         $clientIp = $request->getClientIp();
         $ban = Ban::findActive($id, $clientIp);
         if (!empty($ban)) {
             throw new BannedException($ban[0], Response::HTTP_FORBIDDEN);
         }
         // User loading.
         $user = User::find($id);
         if (null !== $user) {
             $user->ip = $clientIp;
             $user->save();
             $this->provider->setUser($user);
             $this->provider->setAuthenticated(true);
         }
     }
 }
 public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
 {
     if ($request->request->has('_username')) {
         $username = $request->request->get('_username');
     } else {
         $username = '';
     }
     //if ($exception->getMessage() === 'Captcha is invalid') {
     //} else {
     $failedLoginIp = $request->getClientIp();
     $user = $this->fosUM->findUserByUsername($username);
     if ($user) {
         $failedLogin = $user->getFailedLogin();
         $failedLogin++;
         $user->setFailedLogin($failedLogin);
         $user->setFailedLoginIp($failedLoginIp);
         if ($failedLogin === 3) {
             //email do użytkownika i admina
             $message = \Swift_Message::newInstance()->setSubject('Nieautoryzowane próby dostępu do konta')->setFrom('*****@*****.**')->setTo(array('*****@*****.**', $user->getEmail()))->setBody($username . ' próbował zalogować się zbyt wiele razy z adresu IP: ' . $failedLoginIp . ' ' . $exception->getMessage());
             $this->mailer->send($message);
         }
         if ($failedLogin === 5) {
             $user->setLocked(1);
         }
         $this->fosUM->updateUser($user);
     }
     //}
     $url = 'fos_user_security_login';
     $response = new RedirectResponse($this->router->generate($url));
     return $response;
 }
 /**
  * Verify reCaptcha response.
  *
  * @param string $recaptchaValue
  *
  * @throws RecaptchaException
  */
 public function verify($recaptchaValue)
 {
     // We don't override the value provided by the form
     // If empty, we use the default input drawed by google JS we need to get
     // the value with hardcoded variable
     if ((null === $recaptchaValue || empty($recaptchaValue)) && $this->request->request->has(self::GOOGLE_DEFAULT_INPUT)) {
         $recaptchaValue = $this->request->request->get(self::GOOGLE_DEFAULT_INPUT);
     }
     if ($this->enabled) {
         /* @var \ReCaptcha\Response $response */
         $response = $this->reCaptcha->verify($recaptchaValue, $this->request->getClientIp());
         if (!$response->isSuccess()) {
             throw new RecaptchaException($response);
         }
     }
 }
 public function reset(Application $app, Request $request, $reset_key)
 {
     $errors = $app['validator']->validateValue($reset_key, array(new Assert\NotBlank(), new Assert\Regex(array('pattern' => '/^[a-zA-Z0-9]+$/'))));
     if ('GET' === $request->getMethod() && count($errors) === 0) {
         try {
             $Customer = $app['eccube.repository.customer']->getActiveCustomerByResetKey($reset_key);
         } catch (\Exception $e) {
             throw new HttpException\NotFoundHttpException('有効期限が切れているか、無効なURLです。');
         }
         // パスワードの発行・更新
         $pass = $app['eccube.repository.customer']->getResetPassword();
         $Customer->setPassword($pass);
         // 発行したパスワードの暗号化
         $encPass = $app['eccube.repository.customer']->encryptPassword($app, $Customer);
         $Customer->setPassword($encPass);
         $Customer->setResetKey(null);
         // パスワードを更新
         $app['orm.em']->persist($Customer);
         $app['orm.em']->flush();
         // メール送信
         $app['eccube.service.mail']->sendPasswordResetCompleteMail($Customer, $pass);
         // ログ出力
         $app['monolog']->addInfo('reset password complete:' . "{$Customer->getId()} {$Customer->getEmail()} {$request->getClientIp()}");
     } else {
         throw new HttpException\AccessDeniedHttpException('不正なアクセスです。');
     }
     return $app->render('Forgot/reset.twig');
 }
Exemple #24
0
 public function auth(Request $request)
 {
     $token = $request->headers->get('X-Auth-Token');
     if (empty($token)) {
         // 兼容老的协议,即将去除
         $token = $request->headers->get('Auth-Token', '');
     }
     $method = strtolower($request->headers->get('X-Auth-Method'));
     if ($method == 'keysign') {
         $decoded = $this->decodeKeysign($token);
         $this->setCurrentUser(array('id' => 0, 'nickname' => '游客', 'currentIp' => $request->getClientIp(), 'roles' => array()));
     } else {
         $whilelist = isset($this->whilelist[$request->getMethod()]) ? $this->whilelist[$request->getMethod()] : array();
         $path = rtrim($request->getPathInfo(), '/');
         $inWhiteList = 0;
         foreach ($whilelist as $pattern) {
             if (preg_match($pattern, $path)) {
                 $inWhiteList = 1;
                 break;
             }
         }
         if (!$inWhiteList && empty($token)) {
             throw new \RuntimeException('API Token不存在!');
         }
         $token = $this->getUserService()->getToken('mobile_login', $token);
         if (!$inWhiteList && empty($token['userId'])) {
             throw new \RuntimeException('API Token不不正确!');
         }
         $user = $this->getUserService()->getUser($token['userId']);
         if (!$inWhiteList && empty($user)) {
             throw new \RuntimeException('登录用户不存在!');
         }
         $this->setCurrentUser($user);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE)
 {
     if ($request->getClientIp() == '127.0.0.10') {
         return new Response(t('Bye!'), 403);
     }
     return $this->httpKernel->handle($request, $type, $catch);
 }
 public function onException(BlockadeException $exception, Request $request)
 {
     $driver = $exception->getDriver();
     $msg = $driver ? get_class($driver) . ' threw ' : '';
     $msg .= sprintf('%s with message "%s" from ip %s on page %s', get_class($exception), $exception->getMessage(), $request->getClientIp(), $request->getUri());
     $this->logger->log($this->level, $msg);
 }
Exemple #27
0
 protected function getOrigin(Request $request)
 {
     if (!($address = $request->getClientIp())) {
         $address = '127.0.0.1';
     }
     return array('origin' => $address);
 }
 /**
  * @param string $uri
  * @param Request $request
  * @return Request
  */
 protected function createSubRequest($uri, Request $request)
 {
     $cookies = $request->cookies->all();
     $server = $request->server->all();
     // Override the arguments to emulate a sub-request.
     // Sub-request object will point to localhost as client ip and real client ip
     // will be included into trusted header for client ip
     try {
         if ($trustedHeaderName = Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP)) {
             $currentXForwardedFor = $request->headers->get($trustedHeaderName, '');
             $server['HTTP_' . $trustedHeaderName] = ($currentXForwardedFor ? $currentXForwardedFor . ', ' : '') . $request->getClientIp();
         }
     } catch (\InvalidArgumentException $e) {
         // Do nothing
     }
     $server['REMOTE_ADDR'] = '127.0.0.1';
     $subRequest = TheliaRequest::create($uri, 'get', array(), $cookies, array(), $server);
     if ($request->headers->has('Surrogate-Capability')) {
         $subRequest->headers->set('Surrogate-Capability', $request->headers->get('Surrogate-Capability'));
     }
     if ($session = $request->getSession()) {
         $subRequest->setSession($session);
     }
     return $subRequest;
 }
Exemple #29
0
 public function createToken(Request $request, $exp, $user)
 {
     $rand_val = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 6);
     $payload = ['iss' => $request->getClientIp(), 'sub' => '', 'aud' => 'http://sheaker.com', 'exp' => $exp, 'nbf' => time(), 'iat' => time(), 'jti' => hash('sha256', time() . $rand_val), 'user' => $user];
     $token = JWT::encode($payload, $this->secretKey);
     return $token;
 }
Exemple #30
0
 /**
  * Checks if current purge request is allowed.
  * This method can be overridden to extend the allowance test.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *
  * @return bool
  */
 protected function isInternalRequestAllowed(Request $request)
 {
     if (!$this->isInternalIPAllowed($request->getClientIp())) {
         return false;
     }
     return true;
 }