/** * Set up the application and shut it down afterwards * * @param callable $execute * @return void */ public function run(callable $execute = null) { $this->request = \TYPO3\CMS\Core\Http\ServerRequestFactory::fromGlobals(); // see below when this option is set and Bootstrap::defineTypo3RequestTypes() for more details if (TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_AJAX) { $this->request = $this->request->withAttribute('isAjaxRequest', true); } elseif (isset($this->request->getQueryParams()['M'])) { $this->request = $this->request->withAttribute('isModuleRequest', true); } $this->bootstrap->handleRequest($this->request); if ($execute !== null) { call_user_func($execute); } $this->bootstrap->shutdown(); }
/** * @param Request $request * @return Request */ protected function logIn(Request $request) { $header = $request->getHeaderLine('authorization'); $parts = explode(';', $header); $actor = new Guest(); if (isset($parts[0]) && starts_with($parts[0], $this->prefix)) { $token = substr($parts[0], strlen($this->prefix)); if (($accessToken = AccessToken::find($token)) && $accessToken->isValid()) { $actor = $accessToken->user; $actor->updateLastSeen()->save(); } elseif (isset($parts[1]) && ($apiKey = ApiKey::valid($token))) { $userParts = explode('=', trim($parts[1])); if (isset($userParts[0]) && $userParts[0] === 'userId') { $actor = User::find($userParts[1]); } } } if ($actor->exists) { $locale = $actor->getPreference('locale'); } else { $locale = array_get($request->getCookieParams(), 'locale'); } if ($locale && $this->locales->hasLocale($locale)) { $this->locales->setLocale($locale); } return $request->withAttribute('actor', $actor ?: new Guest()); }
/** * Our job as a pipe rat router is to set the "ResourceKey" route param to the * data that we are given for the matched route. * * @param Request $request * @param Response $response * @param callable|null $out * * @return mixed * @throws RouteException */ public function __invoke(Request $request, Response $response, callable $out = null) { $aPathMatched = false; $paths = $request->getAttribute(Paths::ATTRIBUTE_NAME); /** * */ foreach ($paths as $availablePath => $availableVerbs) { $regex = '/^' . str_replace(['{', '}', '/'], ['(?<', '>[^/]+)', '\\/'], $availablePath) . '$/'; if (preg_match($regex, $request->getUri()->getPath(), $captures)) { $aPathMatched = true; foreach ($availableVerbs as $availableVerb => $routeData) { if (strcasecmp($availableVerb, $request->getMethod()) === 0) { return $out($request->withAttribute(ResourceKey::ATTRIBUTE_NAME, $routeData)->withAttribute(RouteParams::ATTRIBUTE_NAME, new RouteParams($this->parseNamedCaptures($captures))), $response); } } break; } } if ($aPathMatched) { //A path matched but a verb did not so return "Method not allowed" return $response->withStatus(405); } //No paths matched so do nothing and allow other middleware to handle this request. return $out($request, $response); }
/** * {@inheritdoc} */ public function validateAuthorization(ServerRequestInterface $request) { if ($request->hasHeader('authorization') === false) { throw OAuthServerException::accessDenied('Missing "Authorization" header'); } $header = $request->getHeader('authorization'); $jwt = trim(preg_replace('/^(?:\\s+)?Bearer\\s/', '', $header[0])); try { // Attempt to parse and validate the JWT $token = (new Parser())->parse($jwt); if ($token->verify(new Sha256(), $this->publicKey->getKeyPath()) === false) { throw OAuthServerException::accessDenied('Access token could not be verified'); } // Ensure access token hasn't expired $data = new ValidationData(); $data->setCurrentTime(time()); if ($token->validate($data) === false) { throw OAuthServerException::accessDenied('Access token is invalid'); } // Check if token has been revoked if ($this->accessTokenRepository->isAccessTokenRevoked($token->getClaim('jti'))) { throw OAuthServerException::accessDenied('Access token has been revoked'); } // Return the request with additional attributes return $request->withAttribute('oauth_access_token_id', $token->getClaim('jti'))->withAttribute('oauth_client_id', $token->getClaim('aud'))->withAttribute('oauth_user_id', $token->getClaim('sub'))->withAttribute('oauth_scopes', $token->getClaim('scopes')); } catch (\InvalidArgumentException $exception) { // JWT couldn't be parsed so return the request as is throw OAuthServerException::accessDenied($exception->getMessage()); } catch (\RuntimeException $exception) { //JWR couldn't be parsed so return the request as is throw OAuthServerException::accessDenied('Error while decoding to JSON'); } }
/** * Executes the modules configured via Extbase * * @param string $moduleName * @return Response A PSR-7 response object * @throws \RuntimeException */ protected function dispatchModule($moduleName) { $moduleConfiguration = $this->getModuleConfiguration($moduleName); // Check permissions and exit if the user has no permission for entry $this->backendUserAuthentication->modAccess($moduleConfiguration, true); $id = isset($this->request->getQueryParams()['id']) ? $this->request->getQueryParams()['id'] : $this->request->getParsedBody()['id']; if ($id && MathUtility::canBeInterpretedAsInteger($id)) { // Check page access $permClause = $this->backendUserAuthentication->getPagePermsClause(true); $access = is_array(BackendUtility::readPageAccess((int) $id, $permClause)); if (!$access) { throw new \RuntimeException('You don\'t have access to this page', 1289917924); } } /** @var Response $response */ $response = GeneralUtility::makeInstance(Response::class); // Use Core Dispatching if (isset($moduleConfiguration['routeTarget'])) { $dispatcher = GeneralUtility::makeInstance(Dispatcher::class); $this->request = $this->request->withAttribute('target', $moduleConfiguration['routeTarget']); $response = $dispatcher->dispatch($this->request, $response); } else { // extbase module $configuration = array('extensionName' => $moduleConfiguration['extensionName'], 'pluginName' => $moduleName); if (isset($moduleConfiguration['vendorName'])) { $configuration['vendorName'] = $moduleConfiguration['vendorName']; } // Run Extbase $bootstrap = GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Core\Bootstrap::class); $content = $bootstrap->run('', $configuration); $response->getBody()->write($content); } return $response; }
/** * Execute the middleware. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $user = null; if (isset($_SESSION) && isset($_SESSION['twitterUser'])) { $user = $_SESSION['twitterUser']; } return $next($request->withAttribute(self::USER, $user), $response); }
/** * {@inheritDoc} */ public function parse(ServerRequestInterface $request) { $rawBody = (string) $request->getBody(); $parsedBody = json_decode($rawBody, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new MalformedRequestBodyException('Error when parsing JSON request body: ' . json_last_error_msg()); } return $request->withAttribute('rawBody', $rawBody)->withParsedBody($parsedBody); }
/** * withPaths * * set Reliv\PipeRat\RequestAttribute\Paths attribute = array ['/{path}' => ['{verb}' => 'resourceKey']] * * @param Request $request * * @return Request */ public function withPaths(Request $request) { if (!empty($this->paths)) { $request->withAttribute(Paths::getName(), $this->paths); return $request; } $resourceConfig = $this->getResourceConfig(); /** * @var string $resourceName * @var Options $resourceOptions */ foreach ($resourceConfig as $resourceName => $resourceOptions) { $resourcePath = $resourceOptions->get('path', '/' . $resourceName); $methodsAllowed = $resourceOptions->get('methodsAllowed', []); $methods = $resourceOptions->get('methods', []); $methodPriority = $resourceOptions->get('methodPriority', []); $this->buildMethods($resourceName, $resourcePath, $methodsAllowed, $methods, $methodPriority); } return $request->withAttribute(Paths::getName(), $this->paths); }
/** * Execute the middleware * * @param ServerRequestInterface $request * @param ResponseInterface $response * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $negotiator = new Negotiator(); $language = $negotiator->getBest($request->getHeaderLine('Accept-Language'), $this->languages); if ($language) { $language = strtolower(substr($language->getValue(), 0, 2)); } else { $language = isset($this->languages[0]) ? $this->languages[0] : null; } return $next($request->withAttribute('LANGUAGE', $language), $response); }
public function it_should_throw_exception_when_class_is_not_implement_interface(ServerRequestInterface $request, UriInterface $uri, ResponseInterface $response, GroupCountBased $dispatcher, ContainerInterface $container) { $request->getMethod()->willReturn('GET'); $request->getUri()->willReturn($uri); $uri->getPath()->willReturn('/'); $dispatcher->dispatch('GET', '/')->willReturn([Dispatcher::FOUND, 'Test', []]); $request->withAttribute('param', [])->shouldBeCalled(); $container->offsetGet('Test')->willReturn(new \ArrayObject()); $this->shouldThrow(InternalErrorHttpException::class)->during('__invoke', [$request, $response, function ($request, $response) { return $response; }]); }
/** * {@inheritdoc} */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, \Closure $next = null) { //Opening cookie scope $outerCookies = $this->container->replace(self::class, $this); $this->request = $this->decodeCookies($request); $response = $next($this->request->withAttribute('cookieDomain', $this->cookieDomain())); //New cookies $response = $this->mountCookies($response); //Restoring scope $this->container->restore($outerCookies); return $response; }
/** * Constructor setting up legacy constant and register available Request Handlers * * @param \Composer\Autoload\ClassLoader $classLoader an instance of the class loader */ public function __construct($classLoader) { $this->defineLegacyConstants(); $this->bootstrap = Bootstrap::getInstance()->initializeClassLoader($classLoader)->baseSetup($this->entryPointPath); // can be done here after the base setup is done $this->defineAdditionalEntryPointRelatedConstants(); // Redirect to install tool if base configuration is not found if (!$this->bootstrap->checkIfEssentialConfigurationExists()) { $this->bootstrap->redirectToInstallTool($this->entryPointPath); } foreach ($this->availableRequestHandlers as $requestHandler) { $this->bootstrap->registerRequestHandlerImplementation($requestHandler); } $this->request = \TYPO3\CMS\Core\Http\ServerRequestFactory::fromGlobals(); // see below when this option is set if ($GLOBALS['TYPO3_AJAX']) { $this->request = $this->request->withAttribute('isAjaxRequest', true); } elseif (isset($this->request->getQueryParams()['M'])) { $this->request = $this->request->withAttribute('isModuleRequest', true); } $this->bootstrap->configure(); }
/** * Invoke middleware. * * @param ServerRequestInterface $request request object * @param ResponseInterface $response response object * @param callable $next next middleware * * @return ResponseInterface response object */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $isValid = $request->getAttribute(self::$isValidAttribute, false); $violations = $request->getAttribute(self::$violationsAttribute, []); foreach ($request->getHeader($this->headerName) as $token) { $tokenViolations = call_user_func($this->tokenValidator, $token); if (count($tokenViolations) === 0) { $isValid = true; continue; } $violations = array_merge($violations, $tokenViolations); } return $next($request->withAttribute(self::$isValidAttribute, $isValid)->withAttribute(self::$violationsAttribute, $violations), $response); }
/** * Execute the middleware. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { /* @var $view \Slim\Views\Twig */ $view = $this->ci->get('view'); /* @var $autoLogin \nanotwi\AutoLogin */ $autoLogin = $this->ci->get('autoLogin'); /* @var $autoLogin \nanotwi\NanoTwitter */ $nanoTwitter = $this->ci->get('nanoTwitter'); $routeInfo = $request->getAttribute('routeInfo')[2]; //https://github.com/slimphp/Slim/issues/1505#issuecomment-142193606 $token = $routeInfo['token']; $oAuthToken = $autoLogin->parseAutologinToken($token); $view['token'] = $token; return $next($request->withAttribute('autologinToken', $token)->withAttribute('oAuth', $oAuthToken), $response); }
/** * @test */ public function callsNextMiddlewareIfResponderReturnedAResponse() { $called = false; $next = function (ServerRequestInterface $request, ResponseInterface $response, callable $next = null) use(&$called) : ResponseInterface { $called = true; return $response; }; $responder = $this->createMock(Responder::class, ['__invoke']); $responder->expects($this->once())->method('__invoke')->will($this->returnValue(new Response())); $payload = $this->createMock(Payload::class); $this->request = $this->request->withAttribute(self::$responderAttribute, $responder); $this->request = $this->request->withAttribute(self::$payloadAttribute, $payload); $this->middleware->__invoke($this->request, $this->response, $next); $this->assertTrue($called); }
/** * @test */ public function beforeEmitterMiddlewareWillBePipedBeforeEmitter() { $expectedOrder = [BasicRoutingMiddleware::class, ActionResolverMiddleware::class, ActionExecutorMiddleware::class, ResponderResolverMiddleware::class, ResponderExecutorMiddleware::class, TestMiddleware::class]; $order = []; $app = $this->getMockedAdrenaline(); $app->expects($this->any())->method('pipe')->will($this->returnCallback(function ($middleware) use(&$order) { $order[] = get_class($middleware); })); $route = RouteBuilder::route()->get('/')->to('home')->build(); $routingResult = RoutingResult::forSuccess($route); $app->beforeEmitter(new TestMiddleware()); $this->request = $this->request->withAttribute(RoutingResult::class, $routingResult); $app->__invoke($this->request, $this->response); $this->assertEquals($order, $expectedOrder); }
/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $route = $this->dispatchRoutes()->dispatch($request->getMethod(), $request->getUri()->getPath()); switch ($route[0]) { case Dispatcher::NOT_FOUND: // ... 404 Not Found break; case Dispatcher::METHOD_NOT_ALLOWED: $allowedMethods = $route[1]; // ... 405 Method Not Allowed break; case Dispatcher::FOUND: return $next($request->withAttribute('action.handler', $route[1]), $response); break; } }
/** * Invoking the middleware * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * @return ResponseInterface $response * @throws InternalServerError * @throws NotAcceptable */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { // Make sure we have serializers if (!isset($this->container['acceptTypes'])) { throw new InternalServerError('No serializers seems to be registered'); } // Get priorities $supported = $this->container['acceptTypes']; // Prepare charset $charset = $this->prepareCharsetHeaderString(); // Make sure we have what we need to do the negotiation if ($request->hasHeader('Accept')) { // Get header $accept = $request->getHeaderLine('Accept'); // Negotiate $best = $this->getBestFormat($accept, $supported); // If an Accept header field is present, and if the server cannot send a response // which is acceptable according to the combined Accept field value, then the server // SHOULD return a 406 (not acceptable) response. if ($best === null) { // We must set the mime type before throwing the exception so that the correct serializer // is triggered to serialize the error message. Both on the request and response. $this->container['latestRequest'] = $request->withAttribute('Accept', $supported[0]); $this->container['latestResponse'] = $response->withHeader('Content-Type', $supported[0] . $charset); throw new NotAcceptable('Can not send a response which is acceptable according to the Accept header. ' . 'Supported mime types are: ' . implode(', ', $supported)); } } else { // If no Accept header field is present, then it is assumed that the client accepts all media types. $best = $this->acceptsAnything(1, $supported); } // Save result $request = $request->withAttribute('Accept', $best['value']); // Set response content type header $response = $response->withHeader('Content-Type', $best['value'] . $charset); // Set extra params if (isset($best['parameters'])) { // Set parameters array as attribute $request = $request->withAttribute('Accept-Parameters', $best['parameters']); } // Call next middleware return $next($request, $response, $next); }
/** * @inheritdoc * @throws ResponderResolveException */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) : ResponseInterface { $domainPayload = $request->getAttribute($this->domainPayloadAttribute); // if the return value is a response instance, directly return it if ($domainPayload instanceof ResponseInterface) { $this->logger->debug('Received response. Skipping resolvers.'); $response = $domainPayload; if ($next) { $response = $next($request->withAttribute($this->responderAttribute, $response), $response); } return $response; } try { $responder = $this->resolve($request); } catch (ResolveException $e) { throw new ResponderResolveException('None of given resolvers could resolve a responder', $e->getCode(), $e); } if ($next) { $response = $next($request->withAttribute($this->responderAttribute, $responder), $response); } return $response; }
/** * {@inheritDoc} */ public function match(ServerRequestInterface $request) { $requestUri = $request->getUri(); // strip query string if provided $requestPath = $requestUri->getPath(); $queryStringPos = strpos($requestPath, '?'); if (false !== $queryStringPos) { $requestPath = substr($requestPath, 0, $queryStringPos); } if (!isset($this->routes[$request->getMethod()]) || null === $requestPath) { $this->logger->error(sprintf('No routes found for request method "%s". Returning default target "%s"', $request->getMethod(), $this->defaultTarget)); return $request->withAttribute($this->targetRequestAttribute, $this->defaultTarget); } $this->logger->debug(sprintf('Analysing request path "%s"', $requestPath)); foreach ($this->routes[$request->getMethod()] as $routeDefinition) { $route = $routeDefinition['route']; $identifier = $this->getRouteIdentifier($route); $this->logger->debug(sprintf('Trying to match requested path to route "%s"', $identifier)); $urlVars = []; if (preg_match_all($routeDefinition['pathMatcher'], $requestPath, $urlVars)) { // remove all elements which should not be set in the request, // e.g. the matching url string as well as all numeric items $params = $this->mapParams($urlVars); // match params against configured matchers and only continue if valid if ($this->matchParams($route, $params)) { $params = array_merge($request->getQueryParams(), $params); // setting route params as query params $request = $request->withQueryParams($params); $identifier = $this->getRouteIdentifier($route); $this->logger->debug(sprintf('Route "%s" matches. Applying its target...', $identifier)); return $request->withAttribute($this->targetRequestAttribute, $route->getTarget()); } } } $this->logger->debug('No matching route found. Applying default target.'); return $request->withAttribute($this->getTargetRequestAttribute(), $this->defaultTarget); }
/** * {@inheritdoc} */ public function validateAuthorization(ServerRequestInterface $request) { if ($request->hasHeader('authorization') === false) { throw OAuthServerException::accessDenied('Missing "Authorization" header'); } $header = $request->getHeader('authorization'); $accessTokenId = trim($header[0]); try { $accessTokenEntity = $this->accessTokenRepository->findAccessToken($accessTokenId); // Check if token has been revoked if (is_null($accessTokenEntity)) { throw OAuthServerException::accessDenied('Access token has been revoked'); } // Ensure access token hasn't expired if ($accessTokenEntity->getExpiryDateTime()->lt(Carbon::now())) { throw OAuthServerException::accessDenied('Access token is invalid'); } // Return the request with additional attributes return $request->withAttribute('oauth_access_token_id', $accessTokenEntity->getIdentifier())->withAttribute('oauth_client_id', $accessTokenEntity->getClient()->getIdentifier())->withAttribute('oauth_user_id', $accessTokenEntity->getUserIdentifier())->withAttribute('oauth_scopes', $accessTokenEntity->getScopes()); } catch (\InvalidArgumentException $exception) { // JWT couldn't be parsed so return the request as is throw OAuthServerException::accessDenied($exception->getMessage()); } }
/** * {@inheritdoc} */ public function withAttribute($name, $value) { return new static($this->wrapped->withAttribute($name, $value)); }
/** * Get the param from the URL * * @param Request $request * @param Response $response * @param callable|null $out * * @return mixed * @throws InvalidWhereException */ public function __invoke(Request $request, Response $response, callable $out = null) { return $out($request->withAttribute('orderByFilterParam', $this->getValue($request)), $response); }
/** * @param ServerRequestInterface $request * @return mixed */ public function dispatch(ServerRequestInterface $request) { $dispatcher = $this->createDispatcher(); $routeInfo = $this->runDispatcher($dispatcher, $request->getMethod(), $request->getUri()->getPath()); foreach ($routeInfo[2] as $key => $value) { $request->withAttribute($key, $value); } return $this->routes[$routeInfo[1]]['handler']->execute($request); }
/** * {@inheritDoc} */ public function withAttribute($name, $value) { return new self($this->app, $this->psrRequest->withAttribute($name, $value)); }
/** * Proxy to ServerRequestInterface::withAttribute() * * {@inheritdoc} */ public function withAttribute($attribute, $value) { $new = $this->psrRequest->withAttribute($attribute, $value); return new self($new, $this->originalRequest); }
/** * * Location: http://www.example.com/users/4/ * http://www.restapitutorial.com/lessons/httpmethods.html * * @param ServerRequestInterface $request * @param ResponseInterface $response * @return ResponseInterface * @throws \zaboy\rest\RestException * @internal param callable|null $next */ public function methodPostWithoutId(ServerRequestInterface $request, ResponseInterface $response) { $promise = new Client($this->store); $responseBody = $promise->toArray(); $this->request = $request->withAttribute('Response-Body', $responseBody); $response = $response->withStatus(201); $insertedPrimaryKeyValue = $promise->getId(); $location = $request->getUri()->getPath(); $response = $response->withHeader('Location', rtrim($location, '/') . '/' . $insertedPrimaryKeyValue); return $response; }
/** * Builds a Response for PayloadStatus::ERROR. */ protected function error($payload) { $this->response = $this->response->withStatus(500); $this->request = $this->request->withAttribute('page', 'error.php'); $this->htmlBody($payload); }
/** * Store an attribute in the request. * * @param ServerRequestInterface $request * @param string $name * @param mixed $value * * @return ServerRequestInterface */ public static function setAttribute(ServerRequestInterface $request, $name, $value) { $attributes = $request->getAttribute(self::KEY, []); $attributes[$name] = $value; return $request->withAttribute(self::KEY, $attributes); }
/** * {@inheritDoc} */ public function parse(ServerRequestInterface $request) { $rawBody = $request->getBody()->getContents(); return $request->withAttribute('rawBody', $rawBody)->withParsedBody(json_decode($rawBody, true)); }