/**
  * Transform a PSR7 request into a CakePHP one.
  *
  * @param \Psr\Http\Message\ServerRequestInterface $request The PSR7 request.
  * @return \Cake\Network\Request The transformed request.
  */
 public static function toCake(PsrRequest $request)
 {
     $post = $request->getParsedBody();
     $server = $request->getServerParams();
     $files = static::getFiles($request);
     if (!empty($files)) {
         $post = Hash::merge($post, $files);
     }
     return new CakeRequest(['query' => $request->getQueryParams(), 'post' => $post, 'cookies' => $request->getCookieParams(), 'environment' => $server, 'params' => static::getParams($request), 'url' => $request->getUri()->getPath(), 'base' => $request->getAttribute('base', ''), 'webroot' => $request->getAttribute('webroot', '/')]);
 }
Пример #2
0
 /**
  * Server data (e.g. $_SERVER)
  * @return \PHPixie\HTTP\Data\Server
  */
 public function server()
 {
     if ($this->server === null) {
         $data = $this->serverRequest->getServerParams();
         $this->server = $this->builder->serverData($data);
     }
     return $this->server;
 }
 /**
  * {@inheritdoc}
  */
 public function getData()
 {
     $headers = [];
     foreach ($this->request->getHeaders() as $name => $values) {
         $headers[$name] = implode(', ', $values);
     }
     $data = ['SERVER' => $this->request->getServerParams(), 'QUERY' => $this->request->getQueryParams(), 'COOKIES' => $this->request->getCookieParams(), 'HEADERS' => $headers, 'ATTRIBUTES' => $this->request->getAttributes()];
     return $data;
 }
 /**
  * Convert a PSR-7 ServerRequest to a Zend\Http server-side request.
  *
  * @param ServerRequestInterface $psr7Request
  * @param bool $shallow Whether or not to convert without body/file
  *     parameters; defaults to false, meaning a fully populated request
  *     is returned.
  * @return Zend\Request
  */
 public static function toZend(ServerRequestInterface $psr7Request, $shallow = false)
 {
     if ($shallow) {
         return new Zend\Request($psr7Request->getMethod(), $psr7Request->getUri(), $psr7Request->getHeaders(), $psr7Request->getCookieParams(), $psr7Request->getQueryParams(), [], [], $psr7Request->getServerParams());
     }
     $zendRequest = new Zend\Request($psr7Request->getMethod(), $psr7Request->getUri(), $psr7Request->getHeaders(), $psr7Request->getCookieParams(), $psr7Request->getQueryParams(), $psr7Request->getParsedBody() ?: [], self::convertUploadedFiles($psr7Request->getUploadedFiles()), $psr7Request->getServerParams());
     $zendRequest->setContent($psr7Request->getBody());
     return $zendRequest;
 }
Пример #5
0
 /**
  * Constructor
  *
  * @param Request $request
  * @param Response $response
  */
 public function __construct(RequestInterface $request, ResponseInterface $response)
 {
     $this->request = $request;
     $this->response = $response;
     $this->server = $this->request->getServerParams();
     $request = $request->withAttribute('base_path', $this->getBasePath());
     $request = $request->withAttribute('base_uri', $this->getBaseUri());
     $request = $request->withAttribute('host_url', $this->getHostUrl());
     //$x = $request->getAttribute('base_path', 'default');
 }
Пример #6
0
 private function _extractDataPSR7(ServerRequestInterface $request = null, $name = '')
 {
     $method = $request->getMethod();
     $queryParams = $request->getQueryParams();
     if ('GET' === $method) {
         if ('' === $name) {
             return $queryParams;
         }
         // Don't submit GET requests if the form's name does not exist
         // in the request
         if (!isset($queryParams[$name])) {
             return;
         }
         return $queryParams[$name];
     }
     $serverParams = $request->getServerParams();
     $uploadedFiles = $request->getUploadedFiles();
     if ('' === $name) {
         return $this->mergeParamsAndUploadedFiles($serverParams, $uploadedFiles);
     }
     if (isset($serverParams[$name]) || isset($uploadedFiles[$name])) {
         $default = null;
         $params = isset($serverParams[$name]) ? $serverParams[$name] : null;
         $files = isset($uploadedFiles[$name]) ? $uploadedFiles[$name] : null;
         return $this->mergeParamsAndUploadedFiles($params, $files);
     }
     // Don't submit the form if it is not present in the request
     return;
 }
 /**
  * @param \Psr\Http\Message\ServerRequestInterface $request
  *
  * @throws \OAuth2\Exception\BadRequestExceptionInterface
  */
 private function checkRequestIsSecured(ServerRequestInterface $request)
 {
     $server_params = $request->getServerParams();
     if (empty($server_params['HTTPS']) || 'on' !== mb_strtolower($server_params['HTTPS'], '8bit')) {
         throw $this->getExceptionManager()->getBadRequestException(ExceptionManagerInterface::ERROR_INVALID_REQUEST, 'The request must be secured.');
     }
 }
 /**
  * Find out the client's IP address from the headers available to us
  *
  * @param  ServerRequestInterface $request PSR-7 Request
  * @return string
  */
 protected function determineClientIpAddress($request)
 {
     $ipAddress = null;
     $serverParams = $request->getServerParams();
     if (isset($serverParams['REMOTE_ADDR']) && $this->isValidIpAddress($serverParams['REMOTE_ADDR'])) {
         $ipAddress = $serverParams['REMOTE_ADDR'];
     }
     $checkProxyHeaders = $this->checkProxyHeaders;
     if ($checkProxyHeaders && !empty($this->trustedProxies)) {
         if (!in_array($ipAddress, $this->trustedProxies)) {
             $checkProxyHeaders = false;
         }
     }
     if ($checkProxyHeaders) {
         foreach ($this->headersToInspect as $header) {
             if ($request->hasHeader($header)) {
                 $ip = trim(current(explode(',', $request->getHeaderLine($header))));
                 if ($this->isValidIpAddress($ip)) {
                     $ipAddress = $ip;
                     break;
                 }
             }
         }
     }
     return $ipAddress;
 }
Пример #9
0
 /**
  * @param string $name
  * @param array  $options
  *
  * @return bool
  */
 public function isValid($name, array $options = [])
 {
     $options += ['referer' => null, 'token' => null];
     if (null === $options['token']) {
         $params = $this->request->getParsedBody();
         if (!isset($params[$name])) {
             $this->invalidate();
             return false;
         } else {
             $options['token'] = $params[$name];
         }
     }
     $error = false;
     $name .= $options['token'];
     $config = array_get([self::TOKEN_KEY, $name], $this->storage, []);
     $time = isset($config['expire']) ? $config['expire'] : 0;
     if (time() > $time) {
         $error = true;
     }
     if (!$error && null !== $options['referer']) {
         $params = $this->request->getServerParams();
         if (!isset($params['HTTP_REFERER']) || $params['HTTP_REFERER'] !== $options['referer']) {
             $error = true;
         }
     }
     $regenerate = array_key_exists('regenerate', $config) ? $config['regenerate'] : false;
     if ($error || !$regenerate) {
         array_remove([self::TOKEN_KEY, $name], $this->storage);
     } elseif ($regenerate) {
         $config['expire'] = time() + $config['time'];
         array_set([self::TOKEN_KEY, $name], $config, $this->storage);
     }
     $this->invalidate();
     return !$error;
 }
Пример #10
0
 /**
  * Handle authentication
  *
  * @param  \Psr\Http\Message\ServerRequestInterface $request  PSR7 request
  * @param  \Psr\Http\Message\ResponseInterface      $response PSR7 response
  * @param  callable                                 $next     Next middleware
  *
  * @return \Psr\Http\Message\ResponseInterface
  */
 public function __invoke(Request $request, Response $response, $next)
 {
     $path = $request->getUri()->getPath();
     if ($path && $path != 'login') {
         $serverParams = $request->getServerParams();
         $authHeader = isset($serverParams['HTTP_X_AUTHORIZATION']) ? $serverParams['HTTP_X_AUTHORIZATION'] : null;
         list($jwt) = sscanf($authHeader, 'Bearer %s');
         if (!$jwt) {
             return $response->withStatus(401)->write(json_encode(['message' => '401 Unauthorized']));
         }
         try {
             $settings = $this->app->getContainer()->get('settings');
             $secretKey = base64_decode($settings->get('jwt')['key']);
             $token = JWT::decode($jwt, $secretKey, [$settings->get('jwt')['algorithm']]);
             // Get the user info and add to the container
             $this->app->getContainer()['currentUser'] = function ($c) use($token) {
                 return $token->data;
                 // user attributes
             };
         } catch (\Exception $e) {
             return $response->withStatus(401)->write(json_encode(['message' => $e->getMessage()]));
         }
     }
     $response = $next($request, $response);
     return $response;
 }
Пример #11
0
 /**
  * @param ServerRequestInterface $request
  * @return BaseResponse|Response
  */
 public static function back(ServerRequestInterface $request)
 {
     $serverParams = $request->getServerParams();
     if (isset($serverParams['HTTP_REFERER'])) {
         return static::redirect($serverParams['HTTP_REFERER']);
     }
     return static::factory(200, "<script>window.history.back()</script>");
 }
Пример #12
0
 /**
  * {@inheritdoc}
  */
 public function createRequest(ServerRequestInterface $psrRequest)
 {
     $parsedBody = $psrRequest->getParsedBody();
     $parsedBody = is_array($parsedBody) ? $parsedBody : array();
     $request = new Request($psrRequest->getQueryParams(), $parsedBody, $psrRequest->getAttributes(), $psrRequest->getCookieParams(), $this->getFiles($psrRequest->getUploadedFiles()), $psrRequest->getServerParams(), $psrRequest->getBody()->__toString());
     $request->headers->replace($psrRequest->getHeaders());
     return $request;
 }
Пример #13
0
 /**
  * Returns the client IP address
  *
  * @param \Psr\Http\Message\ServerRequestInterface $request
  * @return string|null IPv4 or IPv6 address or null if invalid
  */
 protected function getIPAddress(\Psr\Http\Message\ServerRequestInterface $request)
 {
     $server = $request->getServerParams();
     $flags = FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6;
     if (isset($server['REMOTE_ADDR']) && ($ip = filter_var($server['REMOTE_ADDR'], FILTER_VALIDATE_IP, $flags)) !== false) {
         return $ip;
     }
 }
Пример #14
0
 /**
  * Converts a PSR-7 request into an OAuth2 request.
  *
  * @param ServerRequestInterface $psrRequest
  * @return Request
  */
 public static function convertRequestFromPsr7(ServerRequestInterface $psrRequest)
 {
     $headers = [];
     foreach ($psrRequest->getHeaders() as $header => $value) {
         $headers[$header] = implode(';', $value);
     }
     return new Request($psrRequest->getQueryParams(), is_array($psrRequest->getParsedBody()) ? $psrRequest->getParsedBody() : [], $psrRequest->getAttributes(), $psrRequest->getCookieParams(), self::getFiles($psrRequest->getUploadedFiles()), $psrRequest->getServerParams(), $psrRequest->getBody()->__toString(), $headers);
 }
Пример #15
0
 /**
  * @param ServerRequestInterface $request
  * @param ResponseInterface $response
  * @param callable $next
  * @return ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
 {
     $server = $request->getServerParams();
     $response = $next ? $next($request, $response) : $response;
     $ms = (microtime(true) - $server['REQUEST_TIME_FLOAT']) * 1000;
     $time = sprintf('%2.' . $this->config['digits'] . 'f%s', $ms, $this->config['suffix'] ? 'ms' : '');
     return $response->withHeader($this->config['header'], $time);
 }
Пример #16
0
 public function __invoke(ServerRequestInterface $requestInterface, ResponseInterface $responseInterface, callable $next)
 {
     $valid = $this->verify($requestInterface->getParam('g-recaptcha-response'), $requestInterface->getServerParams()['REMOTE_ADDR']);
     if ($valid) {
         return $next($requestInterface, $responseInterface);
     } else {
         throw new \Exception("Captcha Failed");
     }
 }
Пример #17
0
 /**
  * Execute the middleware.
  *
  * @param ServerRequestInterface $request
  * @param ResponseInterface      $response
  * @param callable               $next
  *
  * @return ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $server = $request->getServerParams();
     if (!isset($server['REQUEST_TIME_FLOAT'])) {
         $server['REQUEST_TIME_FLOAT'] = microtime(true);
     }
     $response = $next($request, $response);
     $time = (microtime(true) - $server['REQUEST_TIME_FLOAT']) * 1000;
     return $response->withHeader(self::HEADER, sprintf('%2.3fms', $time));
 }
 /**
  * @param ServerRequestInterface $request
  * @param ResponseInterface      $response
  * @param callable|null          $out
  * @return ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $out = null) : ResponseInterface
 {
     $serverParams = $request->getServerParams();
     $remoteAddr = $serverParams['REMOTE_ADDR'] ?? 'unknown IP address';
     // If request is not originating from localhost or from Docker local IP, we throw an RuntimeException
     if (!in_array($remoteAddr, $this->localhost) && !fnmatch('172.17.*', $remoteAddr)) {
         throw new RuntimeException(sprintf('Worker requests must come from localhost, request originated from %s given', $remoteAddr));
     }
     return $out($request, $response);
 }
Пример #19
0
 public function __construct(ServerRequestInterface $serverRequest)
 {
     $this->serverRequest = $serverRequest;
     // Parse the URL path
     $serverParams = $serverRequest->getServerParams();
     if (isset($serverParams["PATH_INFO"])) {
         $path = $serverRequest->getServerParams()["PATH_INFO"];
         $this->pathParts = explode('/', trim($path, '/'));
     }
     // Support old index.php?page=foo&id=3
     if (empty($this->pathParts) && $this->hasRequestValue("p")) {
         $pageName = $this->getRequestString("p");
         if ($this->hasRequestValue("id")) {
             $pageId = $this->getRequestInt("id");
             $this->pathParts = [$pageName, (string) $pageId];
         } else {
             $this->pathParts = [$pageName];
         }
     }
 }
Пример #20
0
 /**
  * Guesses the base URI of the application.
  *
  * @param  Psr\Http\Message\ServerRequestInterface $request
  * @return Psr\Http\Message\ServerRequestInterface
  */
 public static function guess(\Psr\Http\Message\ServerRequestInterface $request)
 {
     $server = $request->getServerParams();
     $basename = basename($server['SCRIPT_FILENAME']);
     $position = strpos($server['SCRIPT_NAME'], $basename) - 1;
     $rootUri = substr($server['SCRIPT_NAME'], 0, $position);
     $oldPath = $request->getUri()->getPath();
     $newPath = str_replace($rootUri, '', $oldPath);
     $uri = $request->getUri()->withPath($newPath);
     return $request->withUri($uri);
 }
Пример #21
0
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $uri = $request->getUri();
     $uriPath = $uri->getPath();
     $baseUrl = $this->baseUrlFinder->findBaseUrl($request->getServerParams(), $uriPath);
     $basePath = $this->detectBasePath($request->getServerParams(), $baseUrl);
     $request = $request->withAttribute(self::BASE_URL, $baseUrl);
     $request = $request->withAttribute(self::BASE_PATH, $basePath);
     if (!empty($baseUrl) && strpos($uriPath, $baseUrl) === 0) {
         $path = substr($uriPath, strlen($baseUrl));
         $path = '/' . ltrim($path, '/');
         $request = $request->withUri($uri->withPath($path));
     }
     if ($this->urlHelper) {
         $this->urlHelper->setBasePath($baseUrl);
     }
     if ($this->basePathHelper) {
         $this->basePathHelper->setBasePath($basePath);
     }
     return $next($request, $response);
 }
 /**
  * Set the "$attributeName" attribute to the client's IP address as determined from
  * the proxy header (X-Forwarded-For or from $_SERVER['REMOTE_ADDR']
  *
  * @param ServerRequestInterface $request PSR7 request
  * @param ResponseInterface $response     PSR7 response
  * @param callable $next                  Next middleware
  *
  * @return ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
 {
     if (!$next) {
         return $response;
     }
     if (!empty($this->trustedProxies)) {
         // get IP address from REMOTE_ADDR or from the Request attribute
         $ipAddress = null;
         $serverParams = $request->getServerParams();
         if (isset($serverParams['REMOTE_ADDR']) && $this->isValidIpAddress($serverParams['REMOTE_ADDR'])) {
             $ipAddress = $serverParams['REMOTE_ADDR'];
         }
         $ip = $request->getAttribute($this->ipAddressAttributeName);
         if ($this->isValidIpAddress($ip)) {
             $ipAddress = $ip;
         }
         if (!in_array($ipAddress, $this->trustedProxies)) {
             return $response = $next($request, $response);
         }
     }
     $uri = $request->getUri();
     // scheme
     if ($request->hasHeader('X-Forwarded-Proto')) {
         $scheme = $request->getHeaderLine('X-Forwarded-Proto');
         if (in_array($scheme, ['http', 'https'])) {
             $uri = $uri->withScheme($scheme);
         }
     }
     // host (& maybe port too)
     if ($request->hasHeader('X-Forwarded-Host')) {
         $host = trim(current(explode(',', $request->getHeaderLine('X-Forwarded-Host'))));
         $port = null;
         if (preg_match('/^(\\[[a-fA-F0-9:.]+\\])(:\\d+)?\\z/', $host, $matches)) {
             $host = $matches[1];
             if ($matches[2]) {
                 $port = (int) substr($matches[2], 1);
             }
         } else {
             $pos = strpos($host, ':');
             if ($pos !== false) {
                 $port = (int) substr($host, $pos + 1);
                 $host = strstr($host, ':', true);
             }
         }
         $uri = $uri->withHost($host);
         if ($port) {
             $uri = $uri->withPort($port);
         }
     }
     $request = $request->withUri($uri);
     return $response = $next($request, $response);
 }
Пример #23
0
 /**
  * @param \Psr\Http\Message\ServerRequestInterface $requestInterface
  * @param \Psr\Http\Message\ResponseInterface      $responseInterface
  * @param callable                                 $next
  * @return \Psr\Http\Message\ResponseInterface
  * @throws \Exception
  */
 public function __invoke(ServerRequestInterface $requestInterface, ResponseInterface $responseInterface, callable $next)
 {
     if (is_array($requestInterface->getAttribute($this->permissionKey))) {
         $uri = $requestInterface->getServerParams()['REQUEST_URI'];
         if (in_array($uri, $requestInterface->getAttribute($this->permissionKey))) {
             return $next($requestInterface, $responseInterface);
         } else {
             throw new \Exception("User does not have permission to view this resource");
         }
     } else {
         throw new \Exception("Permissions Not Loaded");
     }
 }
Пример #24
0
 /**
  * Match a request against the known routes.
  *
  * Implementations will aggregate required information from the provided
  * request instance, and pass them to the underlying router implementation;
  * when done, they will then marshal a `RouteResult` instance indicating
  * the results of the matching operation and return it to the caller.
  *
  * @param  Request $request
  * @return RouteResult
  */
 public function match(Request $request)
 {
     $this->_forbidRouteAdd = true;
     $params = $request->getServerParams();
     $path = $params['PATH_INFO'];
     // get the matched route
     $matchedRoute = $this->_matchPathToRoutePath($path);
     // check if route exists
     if ($matchedRoute instanceof Route) {
         return RouteResult::fromRouteMatch($matchedRoute->getName(), $matchedRoute->getMiddleware(), $params);
     }
     return RouteResult::fromRouteFailure();
 }
 /**
  * @inheritDoc
  */
 public function match(Request $request)
 {
     // Must inject routes prior to matching.
     $this->injectRoutes();
     $path = $request->getUri()->getPath();
     $method = $request->getMethod();
     $params = $request->getServerParams();
     $params['REQUEST_METHOD'] = $method;
     $route = $this->router->match($path, $params);
     if (false === $route) {
         return $this->marshalFailedRoute($request);
     }
     return $this->marshalMatchedRoute($route);
 }
 /**
  * @param \Psr\Http\Message\ServerRequestInterface $request
  *
  * @return null|\HttpDigest\DigestDataInterface
  */
 public function findAuthorizationHeader(ServerRequestInterface $request)
 {
     $server_params = $request->getServerParams();
     if (array_key_exists('PHP_AUTH_DIGEST', $server_params)) {
         $data = new DigestData($server_params['PHP_AUTH_DIGEST']);
         $this->validateData($data);
         return $data;
     }
     $header = $request->getHeader('Authorization');
     if (0 < count($header) && strtolower(substr($header[0], 0, 7)) === 'digest ') {
         $data = new DigestData(substr($header[0], 7, strlen($header[0]) - 7));
         $this->validateData($data);
         return $data;
     }
 }
Пример #27
0
 /**
  * {@inheritdoc}
  */
 protected function data(ServerRequestInterface $request, Document $document)
 {
     $actor = $request->getAttribute('actor');
     $ipAddress = array_get($request->getServerParams(), 'REMOTE_ADDR', '127.0.0.1');
     if (!$request->getAttribute('bypassFloodgate')) {
         $this->floodgate->assertNotFlooding($actor);
     }
     $discussion = $this->bus->dispatch(new StartDiscussion($actor, array_get($request->getParsedBody(), 'data', []), $ipAddress));
     // After creating the discussion, we assume that the user has seen all
     // of the posts in the discussion; thus, we will mark the discussion
     // as read if they are logged in.
     if ($actor->exists) {
         $this->bus->dispatch(new ReadDiscussion($discussion->id, $actor, 1));
     }
     return $discussion;
 }
 /**
  * @return array
  */
 private function parseIncomingParams()
 {
     $parameters = [];
     $server = $this->request->getServerParams();
     $body = $this->request->getBody();
     $content_type = false;
     if (isset($server['CONTENT_TYPE'])) {
         $content_type = $server['CONTENT_TYPE'];
     }
     switch ($content_type) {
         case "application/json":
             $body_params = json_decode($body, true);
             if ($body_params) {
                 foreach ($body_params as $param_name => $param_value) {
                     $parameters[$param_name] = $param_value;
                 }
             }
             break;
         case "application/x-www-form-urlencoded":
             parse_str($body, $postvars);
             foreach ($postvars as $field => $value) {
                 $parameters[$field] = $value;
             }
             break;
     }
     return $parameters;
 }
Пример #29
-1
 /**
  * @param ServerRequestInterface $request
  * @return string
  */
 protected function findOutRemoteAddr(ServerRequestInterface $request)
 {
     $forwardedFor = $request->getHeaderLine('X-Forwarded-For');
     if (empty($forwardedFor)) {
         $serverParams = $request->getServerParams();
         return isset($serverParams['REMOTE_ADDR']) ? $serverParams['REMOTE_ADDR'] : null;
     }
     $ips = explode(',', $forwardedFor);
     return $ips[0];
 }
Пример #30
-2
 /**
  * @return Cookie\CookiePool
  */
 public function getCookies()
 {
     if (!isset($this->cookies)) {
         $server = $this->request->getServerParams();
         $secure = isset($server['HTTPS']) && $server['HTTPS'] != 'off';
         $this->cookies = new Cookie\CookiePool($this->path, $this->domain, true, $secure);
         foreach ($this->request->getCookieParams() as $name => $value) {
             $this->cookies->add(new Cookie\RequestCookie($name, $value));
         }
     }
     return $this->cookies;
 }