public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { if ($request->getUri()->getScheme() != 'https' && $request->getUri()->getHost() != 'localhost') { throw new SecurityException('HTTPS not used'); } return $next($request, $response); }
/** * Invocation * * Register routes container and request attributes * * @param ServerRequestInterface $request Request * @param ResponseInterface $response Response * @param TornadoHttp $next Next Middleware - TornadoHttp container * @return ResponseInterface * @throws HttpMethodNotAllowedException * @throws HttpNotFoundException */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, TornadoHttp $next) { /** @var \FastRoute\Dispatcher\GroupCountBased $dispatcher */ $dispatcher = FastRoute\simpleDispatcher(function (RouteCollector $routeCollector) { foreach ($this->routes as $key => $route) { $routeCollector->addRoute($route['methods'], $route['path'], $key); } }); $method = $request->getMethod(); $uri = rawurldecode(parse_url($request->getUri(), \PHP_URL_PATH)); $route = $dispatcher->dispatch($method, $uri); $handler = null; $vars = null; switch ($route[0]) { case Dispatcher::NOT_FOUND: throw new HttpNotFoundException('Inexistent route for the url ' . $request->getUri()); case Dispatcher::METHOD_NOT_ALLOWED: throw new HttpMethodNotAllowedException('Method not allowed'); case Dispatcher::FOUND: $handler = $route[1]; $vars = $route[2]; break; } $request = $request->withAttribute(Router::REGISTER_KEY, $handler); foreach ($vars as $name => $value) { $request = $request->withAttribute($name, $value); } return $next($request, $response); }
/** * @param Request $request * @param Response $response * @return Response */ function dispatch(Request $request, Response $response) { $path = preg_replace('{/{2,}}', '/', $request->getUri()->getPath()); $path = $request->getUri()->getQuery(); // TODO:TEST:DEBUG $path = trim($path, '/'); $path = urldecode($path); // TODO: debug temporaire foreach ($this->collection as $route) { // Pattern if (!preg_match('{^' . $route->getPattern() . '$}i', $path, $attributes)) { continue; } // Options foreach ($route->getOptions() as $key => $value) { switch ($key) { case 'method': if (!in_array($request->getMethod(), explode('|', $value))) { continue 3; } } } // Attributes foreach (array_filter($attributes, 'is_string', ARRAY_FILTER_USE_KEY) as $ak => $av) { $request = $request->withAttribute($ak, $av); } //return call_user_func($this->callable, $request, ...array_filter($attributes, 'is_int', ARRAY_FILTER_USE_KEY)); // TODO: delete key 0 return $this->runner($request, $response, ...$route->getCallables()); } // Error 404 return $response; }
protected function getRoute($indexKey, ServerRequestInterface $request) { $validRoutes = []; foreach ($this->routesIndex[$indexKey] as $route) { $scheme = $route->getScheme(); if (!empty($scheme) && $request->getUri()->getScheme() !== $scheme) { continue; } $host = $route->getHost(); if (!empty($host) && $request->getUri()->getHost() !== $host) { continue; } foreach ($route->getGroup()->getConditions() as $condition) { if (!$condition->verify($request)) { continue 2; } } foreach ($route->getConditions() as $condition) { if (!$condition->verify($request)) { continue 2; } } $validRoutes[] = $route; } if (empty($validRoutes)) { throw new RouteConditionFailedException(); } else { if (count($validRoutes) > 1) { throw new ManyRoutesFoundException(); } } return reset($validRoutes); }
/** * {@inheritdoc} */ public function get(array $fileInfo, array $data = []) : string { $engine = $this->getLoader(); if ($this->request !== null) { // Set uri extensions $engine->loadExtension(new URI($this->request->getUri()->getPath())); } // Set asset extensions $engine->loadExtension(new Asset($this->config['engine']['plates']['asset'] ?? null)); // Get all extensions if (!empty($this->availableExtensions)) { foreach ($this->availableExtensions as $extension) { $engine->loadExtension(is_object($extension) ? $extension : new $extension()); } } if (!$engine->exists($fileInfo['name'])) { throw new Exception('Template "' . $fileInfo['name'] . '" dont exist!'); } // Creat a new template $template = new Template($engine, $fileInfo['name']); // We'll evaluate the contents of the view inside a try/catch block so we can // flush out any stray output that might get out before an error occurs or // an exception is thrown. This prevents any partial views from leaking. ob_start(); try { return $template->render($data); } catch (Throwable $exception) { $this->handleViewException($exception); } }
public function addLanguage(ServerRequestInterface $request, $language) { $path = $request->getUri()->getPath(); if ($language !== $this->environment->getDefaultLanguage()) { $path = '/' . $language . ($path === '/' ? '' : $path); } return $request->withUri($request->getUri()->withPath($path)); }
/** * Invocation * * @param ServerRequestInterface $request Request * @param ResponseInterface $response Response * @param callable $next Next Middleware * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { if ($this->basePath !== '/') { $uri = $request->getUri(); $path = '/' . preg_replace('/^' . str_replace('/', '\\/', $this->basePath) . '/', '', $request->getUri()->getPath()); $request = $request->withUri($uri->withPath($path)); } return $next($request, $response); }
/** * 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; }
/** * Invoke middleware * * @param ServerRequestInterface $request request * @param ResponseInterface $response response * @param callable $next callable * * @return object ResponseInterface */ public function __invoke(Request $request, Response $response, callable $next = null) { $err = null; if ($request->isSecure() == false) { $path = $request->getUri()->getPath(); $host = $request->getUri()->getHost(); return $response->redirect('https://' . $host . $path); } return $next($request, $response, $err); }
/** * Schedule new cookie. Cookie will be send while dispatching request. * * Domain, path, and secure values can be left in null state, in this case cookie manager will * populate them automatically. * * @link http://php.net/manual/en/function.setcookie.php * @param string $name The name of the cookie. * @param string $value The value of the cookie. This value is stored on the clients * computer; do not store sensitive information. * @param int $lifetime Cookie lifetime. This value specified in seconds and declares period * of time in which cookie will expire relatively to current time() * value. * @param string $path The path on the server in which the cookie will be available on. * If set to '/', the cookie will be available within the entire * domain. * If set to '/foo/', the cookie will only be available within the * /foo/ * directory and all sub-directories such as /foo/bar/ of domain. The * default value is the current directory that the cookie is being set * in. * @param string $domain The domain that the cookie is available. To make the cookie * available * on all subdomains of example.com then you'd set it to * '.example.com'. * The . is not required but makes it compatible with more browsers. * Setting it to www.example.com will make the cookie only available in * the www subdomain. Refer to tail matching in the spec for details. * @param bool $secure Indicates that the cookie should only be transmitted over a secure * HTTPS connection from the client. When set to true, the cookie will * only be set if a secure connection exists. On the server-side, it's * on the programmer to send this kind of cookie only on secure * connection (e.g. with respect to $_SERVER["HTTPS"]). * @param bool $httpOnly When true the cookie will be made accessible only through the HTTP * protocol. This means that the cookie won't be accessible by * scripting * languages, such as JavaScript. This setting can effectively help to * reduce identity theft through XSS attacks (although it is not * supported by all browsers). * @return $this */ public function set($name, $value = null, $lifetime = null, $path = null, $domain = null, $secure = null, $httpOnly = true) { if (is_null($domain)) { $domain = $this->httpConfig->cookiesDomain($this->request->getUri()); } if (is_null($secure)) { $secure = $this->request->getMethod() == 'https'; } return $this->schedule(new Cookie($name, $value, $lifetime, $path, $domain, $secure, $httpOnly)); }
/** * @inheritDoc */ public function getRoutes() : array { $routes = []; foreach ($this->routes->getRoutes() as $route) { if ((!$route->getHost() || $route->getHost() === $this->request->getUri()->getHost()) && (!$route->getScheme() || $route->getScheme() === $this->request->getUri()->getScheme())) { $routes[] = $route; } } return $routes; }
/** * 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); }
/** * @return bool */ public function resolves() { if (preg_match($this->compileRegex(), $this->request->getUri()->getPath(), $parameters) > 0) { $params = []; foreach ($parameters as $key => $value) { if (!is_int($key)) { $params[$key] = $value; } } return $params; } return false; }
/** * @throws \WoohooLabs\Harmony\Exception\MethodNotAllowed * @throws \WoohooLabs\Harmony\Exception\RouteNotFound */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) : ResponseInterface { $route = $this->fastRoute->dispatch($request->getMethod(), $request->getUri()->getPath()); if ($route[0] === Dispatcher::NOT_FOUND) { throw new RouteNotFound($request->getUri()->getPath()); } if ($route[0] === Dispatcher::METHOD_NOT_ALLOWED) { throw new MethodNotAllowed($request->getMethod()); } foreach ($route[2] as $name => $value) { $request = $request->withAttribute($name, $value); } $request = $request->withAttribute($this->actionAttributeName, $route[1]); return $next($request, $response); }
public function match(ServerRequestInterface $request) { if (!$this->startsWith($request->getUri()->getPath(), $this->routePath)) { return false; } $templateFile = trim(substr($request->getUri()->getPath(), strlen($this->routePath)), '/'); if (!$templateFile) { $templateFile = 'index'; } $template = $this->templateDir . $templateFile . $this->templateExtension; if (!is_file($template)) { throw new NoMatchingRouteException('No matching route for request "' . $request->getUri()->getPath() . '"'); } return new RouteData($this->name, array_merge(['template' => $templateFile, '_view' => ['text/html' => $template]], $this->values), $this->handler); }
/** * Handles any backend request * * @param ServerRequestInterface $request * @return NULL|ResponseInterface */ public function handleRequest(ServerRequestInterface $request) { // enable dispatching via Request/Response logic only for typo3/index.php // This fallback will be removed in TYPO3 CMS 8, as only index.php will be allowed $path = substr($request->getUri()->getPath(), strlen(GeneralUtility::getIndpEnv('TYPO3_SITE_PATH'))); $routingEnabled = $path === TYPO3_mainDir . 'index.php' || $path === TYPO3_mainDir; $proceedIfNoUserIsLoggedIn = false; if ($routingEnabled) { $pathToRoute = (string) $request->getQueryParams()['route']; // Allow the login page to be displayed if routing is not used and on index.php if (empty($pathToRoute)) { $pathToRoute = '/login'; } $request = $request->withAttribute('routePath', $pathToRoute); // Evaluate the constant for skipping the BE user check for the bootstrap // should be handled differently in the future by checking the Bootstrap directly if ($pathToRoute === '/login') { $proceedIfNoUserIsLoggedIn = true; } } $this->boot($proceedIfNoUserIsLoggedIn); // Check if the router has the available route and dispatch. if ($routingEnabled) { return $this->dispatch($request); } // No route found, so the system proceeds in called entrypoint as fallback. return null; }
/** * Execute the middleware. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $language = null; //Use path if ($this->usePath) { $uri = $request->getUri(); $path = ltrim($this->getPath($uri->getPath()), '/'); $dirs = explode('/', $path, 2); $first = array_shift($dirs); if (!empty($first) && in_array($first, $this->languages, true)) { $language = $first; //remove the language in the path $request = $request->withUri($uri->withPath('/' . array_shift($dirs))); } } //Use http headers if ($language === null) { $language = $this->negotiateHeader($request->getHeaderLine('Accept-Language'), new Negotiator(), $this->languages); if (empty($language)) { $language = isset($this->languages[0]) ? $this->languages[0] : null; } //Redirect to a path with the language if ($this->redirectStatus && $this->usePath) { $path = Utils\Helpers::joinPath($this->basePath, $language, $this->getPath($uri->getPath())); return self::getRedirectResponse($this->redirectStatus, $uri->withPath($path), $response); } } $request = Middleware::setAttribute($request, self::KEY, $language); if ($language !== null) { $response = $response->withHeader('Content-Language', $language); } return $next($request, $response); }
/** * */ public function nav($root) { if (!isset($this->navigation[$root]) || !is_array($this->navigation[$root])) { return []; } $navigation = $this->navigation[$root]; $aclFilter = function ($page) { if (!$this->acl) { return true; } $path = parse_url($page['href'], PHP_URL_PATH); if (isset($page['external'])) { return true; } $resource = 'route' . $path; return $this->acl->isAllowed($this->currentRole, $resource, 'get'); }; $prepare = function ($page) use(&$prepare, &$aclFilter) { if (isset($page['route'])) { $routeData = isset($page['route_data']) ? $page['route_data'] : []; $query = isset($page['query']) ? $page['query'] : []; $page['href'] = $this->router->pathFor($page['route'], $routeData, $query); } $path = parse_url($page['href'], PHP_URL_PATH); $page['active'] = $path !== '/' && 0 === strpos($this->request->getUri()->getPath(), $path); if (isset($page['pages']) && is_array($page['pages'])) { $page['pages'] = array_filter(array_map($prepare, $page['pages']), $aclFilter); } return $page; }; return array_filter(array_map($prepare, $navigation), $aclFilter); }
/** * {@inheritdoc} */ public function canHandleRequest(ServerRequestInterface $request) { if (static::$uriPattern === null || (string) static::$uriPattern === '') { return false; } return (bool) preg_match(static::$uriPattern, $request->getUri()->getPath()); }
/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $routeInfo = $this->dispatcher->dispatch($request->getMethod(), $request->getUri()->getPath()); switch ($routeInfo[0]) { case Dispatcher::NOT_FOUND: $response = $response->withStatus(404); break; case Dispatcher::METHOD_NOT_ALLOWED: $response = $response->withStatus(405); break; case Dispatcher::FOUND: $callable = $routeInfo[1]; $args = $routeInfo[2]; if (isset($this->container)) { $response = $this->container->call($callable, ['request' => $request, 'response' => $response, 'arguments' => $args]); } else { if (is_callable($callable)) { call_user_func($callable, $request, $response, $args); } else { $callable = new $callable(); call_user_func($callable, $request, $response, $args); } } break; default: return $response->withStatus(500); } $response = $next($request, $response); return $response; }
/** * Slim middleware entry point * * @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, $response, $next) { $this->request = $request; $this->response = $response; $this->dispatch($request->getMethod(), $request->getUri()); return $next($this->request, $this->response); }
/** * Apply the asset middleware. * * @param \Psr\Http\Message\ServerRequestInterface $request The request. * @param \Psr\Http\Message\ResponseInterface $response The response. * @param callable $next The callable to invoke the next middleware layer. * @return \Psr\Http\Message\ResponseInterface A response. */ public function __invoke($request, $response, $next) { $path = $request->getUri()->getPath(); if (strpos($path, $this->urlPrefix) !== 0) { // Not an asset request. return $next($request, $response); } $factory = new Factory($this->config); $assets = $factory->assetCollection(); $targetName = substr($path, strlen($this->urlPrefix)); if (!$assets->contains($targetName)) { // Unknown build. return $next($request, $response); } try { $build = $assets->get($targetName); $compiler = $factory->cachedCompiler($this->outputDir); $contents = $compiler->generate($build); } catch (Exception $e) { // Could not build the asset. $response->getBody()->write($e->getMessage()); return $response->withStatus(400)->withHeader('Content-Type', 'text/plain'); } return $this->respond($response, $contents, $build->ext()); }
/** * @param ServerRequestInterface $request * * @return RoutingResponse */ public function route(ServerRequestInterface $request) : RoutingResponse { if ($request->getUri() == '/') { return new RoutingResponse(200, ControllerMock::class, 'stringAction'); } else { if ($request->getUri() == '/notfound') { return new RoutingResponse(200, ControllerMock::class, 'throwNotFoundAction'); } else { if ($request->getUri() == '/exception') { return new RoutingResponse(200, ControllerMock::class, 'exceptionAction'); } else { return $this->getNotFoundRoute(); } } } }
/** * @param Request $request * @param Response $response * @param callable $next * @return \Psr\Http\Message\MessageInterface|HtmlResponse * @throws Exception */ public function __invoke(Request $request, Response $response, callable $next) { //$form = new LoginForm('Login', []); //$form->get('submit')->setValue('Login'); if ($request->getMethod() == 'POST') { $auth = new AuthenticationService(); $query = $request->getParsedBody(); $authAdapter = new AuthAdapter($query['login'], $query['password'], $this->authConfig); $result = $auth->authenticate($authAdapter); if (!$result->isValid()) { //$response->getBody()->write("Not valid authentication\n"); //return $response->withStatus(403)->withHeader("Content-type", 'text/html'); throw new Exception("Not valid authentication\n", 403); } else { if ($request->getUri()->getPath() === '/auth') { $render = $this->template->render('app::homepage'); $query = $request->getParsedBody(); $query['view']['render'] = $render; $query['view']['code'] = 200; $request = $request->withParsedBody($query); } return $next($request, $response); } } else { $render = $this->template->render('app::login', ['error' => null]); $query = $request->getParsedBody(); $query['view']['render'] = $render; $query['view']['code'] = 200; $request = $request->withParsedBody($query); return $next($request, $response); } }
/** * @param Request $request * @return Executable */ public function routeRequest(Request $request) { $path = $request->getUri()->getPath(); $routeInfo = $this->dispatcher->dispatch($request->getMethod(), $path); $dispatcherResult = $routeInfo[0]; if ($dispatcherResult === \FastRoute\Dispatcher::FOUND) { $handler = $routeInfo[1]; $vars = $routeInfo[2]; $injectionParams = InjectionParams::fromParams($vars); $injectionParams->share(new \Tier\JigBridge\RouteInfo($vars)); $executable = new Executable($handler, $injectionParams, null); $executable->setTierNumber(TierHTTPApp::TIER_GENERATE_BODY); return $executable; } else { if ($dispatcherResult === \FastRoute\Dispatcher::METHOD_NOT_ALLOWED) { //TODO - need to embed allowedMethods....theoretically. $executable = new Executable([$this, 'serve405ErrorPage']); $executable->setTierNumber(TierHTTPApp::TIER_GENERATE_BODY); return $executable; } } $executable = new Executable([$this, 'serve404ErrorPage']); $executable->setTierNumber(TierHTTPApp::TIER_GENERATE_BODY); return $executable; }
/** * {@inheritdoc} */ public function route(ServerRequestInterface $request) : RoutingResponse { $httpMethod = $request->getMethod(); $uri = $request->getUri()->getPath(); $routeInfo = $this->dispatcher->dispatch($httpMethod, $uri); return $this->processDispatcherResult($routeInfo); }
public function match(ServerRequestInterface $request) { //Convert URL params into regex patterns, construct a regex for this route, init params $patternAsRegex = preg_replace_callback('#:([\\w]+)\\+?#', array($this, 'matchesCallback'), str_replace(')', ')?', (string) $this->path)); if (substr($this->path, -1) === '/') { $patternAsRegex .= '?'; } $regex = '#^' . $patternAsRegex . '$#'; //Cache URL params' names and values if this route matches the current HTTP request if (!preg_match($regex, $request->getUri()->getPath(), $paramValues)) { return false; } $params = []; if ($this->paramNames) { foreach ($this->paramNames as $name) { if (isset($paramValues[$name])) { if (isset($this->paramNamesPath[$name])) { $params[$name] = explode('/', urldecode($paramValues[$name])); } else { $params[$name] = urldecode($paramValues[$name]); } } } } return $params; }
/** * @param Request $request * @return \Psr\Http\Message\ResponseInterface|RedirectResponse */ public function handle(Request $request) { $redirectUri = (string) $request->getAttribute('originalUri', $request->getUri())->withQuery(''); $server = new Twitter(['identifier' => $this->settings->get('flarum-auth-twitter.api_key'), 'secret' => $this->settings->get('flarum-auth-twitter.api_secret'), 'callback_uri' => $redirectUri]); $session = $request->getAttribute('session'); $queryParams = $request->getQueryParams(); $oAuthToken = array_get($queryParams, 'oauth_token'); $oAuthVerifier = array_get($queryParams, 'oauth_verifier'); if (!$oAuthToken || !$oAuthVerifier) { $temporaryCredentials = $server->getTemporaryCredentials(); $session->set('temporary_credentials', serialize($temporaryCredentials)); $session->save(); // Second part of OAuth 1.0 authentication is to redirect the // resource owner to the login screen on the server. $server->authorize($temporaryCredentials); exit; } // Retrieve the temporary credentials we saved before $temporaryCredentials = unserialize($session->get('temporary_credentials')); // We will now retrieve token credentials from the server $tokenCredentials = $server->getTokenCredentials($temporaryCredentials, $oAuthToken, $oAuthVerifier); $user = $server->getUserDetails($tokenCredentials); $identification = ['twitter_id' => $user->uid]; $suggestions = ['username' => $user->nickname, 'avatarUrl' => str_replace('_normal', '', $user->imageUrl)]; return $this->authResponse->make($request, $identification, $suggestions); }
/** * Generates a cache key based on a unique request. * * @todo determine parts required for unique request * @param ServerRequestInterface $request * @return string */ private function generateKey(ServerRequestInterface $request) { $params = $request->getQueryParams(); ksort($params); $parts = [$request->getMethod(), $request->getUri()->getPath(), serialize($params)]; return sha1(implode(':', $parts)); }
public function match(ServerRequestInterface $request) { if ($request->getUri()->getPath() !== $this->path) { return false; } return new RouteData($this->name, $this->values, $this->handler); }