public function process(ServerRequestInterface $request, DelegateInterface $delegate) : ResponseInterface { /* @var \PSR7Session\Session\SessionInterface $session */ $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE); // Generate csrf token if (!$session->get('csrf')) { $session->set('csrf', md5(random_bytes(32))); } // Generate form and inject csrf token $form = new FormFactory($this->template->render('app::contact-form', ['token' => $session->get('csrf')]), $this->inputFilterFactory); // Validate form $validationResult = $form->validateRequest($request); if ($validationResult->isValid()) { // Get filter submitted values $data = $validationResult->getValues(); $this->logger->notice('Sending contact mail to {from} <{email}> with subject "{subject}": {body}', $data); // Create the message $message = new Message(); $message->setFrom($this->config['from'])->setReplyTo($data['email'], $data['name'])->setTo($this->config['to'])->setSubject('[xtreamwayz-contact] ' . $data['subject'])->setBody($data['body']); $this->mailTransport->send($message); // Display thank you page return new HtmlResponse($this->template->render('app::contact-thank-you'), 200); } // Display form and inject error messages and submitted values return new HtmlResponse($this->template->render('app::contact', ['form' => $form->asString($validationResult)]), 200); }
/** * @interitdoc */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $payload = null; $messageName = 'UNKNOWN'; try { $payload = $request->getParsedBody(); if (is_array($payload) && isset($payload['message_name'])) { $messageName = $payload['message_name']; } MessageDataAssertion::assert($payload); $message = $this->messageFactory->createMessageFromArray($payload['message_name'], $payload); switch ($message->messageType()) { case Message::TYPE_COMMAND: $this->commandBus->dispatch($message); return $response->withStatus(Middleware::STATUS_CODE_ACCEPTED); case Message::TYPE_EVENT: $this->eventBus->dispatch($message); return $response->withStatus(Middleware::STATUS_CODE_ACCEPTED); case Message::TYPE_QUERY: return $this->responseStrategy->fromPromise($this->queryBus->dispatch($message)); default: return $next($request, $response, new RuntimeException(sprintf('Invalid message type "%s" for message "%s".', $message->messageType(), $messageName), Middleware::STATUS_CODE_BAD_REQUEST)); } } catch (\Assert\InvalidArgumentException $e) { return $next($request, $response, new RuntimeException($e->getMessage(), Middleware::STATUS_CODE_BAD_REQUEST, $e)); } catch (\Exception $e) { return $next($request, $response, new RuntimeException(sprintf('An error occurred during dispatching of message "%s"', $messageName), Middleware::STATUS_CODE_INTERNAL_SERVER_ERROR, $e)); } }
public function it_errors_on_invalid_data_in_request(ServerRequestInterface $httpRequest) { $post = ['data' => ['type' => 'pages', 'attributes' => ['title' => 'Long title', 'slug' => 'long_title', 'short_title' => '', 'parent_uuid' => null, 'sort_order' => 42, 'status' => 'concept']]]; $httpRequest->getHeaderLine('Accept')->willReturn('application/json'); $httpRequest->getParsedBody()->willReturn($post); $this->shouldThrow(ValidationFailedException::class)->duringParseHttpRequest($httpRequest, []); }
/** * Authenticates that the user is allowed to make call to the route. * * @param ServerRequestInterface ServerRequestInterface $request PSR-7 standard for receiving client request * @param ResponseInterface ResponseInterface $response PSR-& standard for sending server response * @param function $next callback function for calling next method * * @return ResponseInterface HTTP response of client request */ public function authorize(ServerRequestInterface $request, $response, $next) { if (empty($request->getHeader('Authorization'))) { $response = $response->withStatus(400); $response->getBody()->write(json_encode(['message' => 'Token not found'])); return $response; } //Get token for accessing this route $token = $request->getHeader('Authorization')[0]; try { //Decode token to get object of data $decodedToken = Auth::decodeToken($token); //Extract the user id from decoded token $uid = $decodedToken->data->uid; $user = User::find($uid); //Check if user exist with the user id if ($user != null) { if ($user->isTokenValid($decodedToken)) { $response = $next($request, $response); } } else { $response = $response->withStatus(401); $response->getBody()->write(json_encode(['message' => 'User does not exist'])); } } catch (TokenExpirationException $ex) { $response = $response->withStatus(401); $response->getBody()->write(json_encode(['message' => $ex->getMessage()])); } catch (\Exception $ex) { $response = $response->withStatus(400); $response->getBody()->write(json_encode(['message' => $ex->getMessage()])); } return $response; }
/** * {@inheritdoc} */ public function canHandleRequest(ServerRequestInterface $request) { if (static::$uriPattern === null || (string) static::$uriPattern === '') { return false; } return (bool) preg_match(static::$uriPattern, $request->getUri()->getPath()); }
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; }
/** * 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; }
/** * 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; }
/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable|null $next * * @return HtmlResponse */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { /* @var \PSR7Session\Session\SessionInterface $session */ $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE); // Generate csrf token if (!$session->get('csrf')) { $session->set('csrf', md5(uniqid(rand(), true))); } // Generate form and inject csrf token $form = FormFactory::fromHtml($this->template->render('app::contact-form', ['token' => $session->get('csrf')])); // Get request data $data = $request->getParsedBody() ?: []; if ($request->getMethod() !== 'POST') { // Display form return new HtmlResponse($this->template->render('app::contact', ['form' => $form->asString()]), 200); } // Validate form $validationResult = $form->validate($data); if (!$validationResult->isValid()) { // Display form and inject error messages and submitted values return new HtmlResponse($this->template->render('app::contact', ['form' => $form->asString($validationResult)]), 200); } // Create the message $message = Swift_Message::newInstance()->setFrom($this->config['from'])->setReplyTo($data['email'], $data['name'])->setTo($this->config['to'])->setSubject('[xtreamwayz-contact] ' . $data['subject'])->setBody($data['body']); if ($this->config['transport']['debug'] !== true) { $this->mailer->send($message); } // Display thank you page return new HtmlResponse($this->template->render('app::contact-thank-you'), 200); }
/** * @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()); }
/** * {@inheritdoc} */ protected function data(ServerRequestInterface $request, Document $document) { $id = array_get($request->getQueryParams(), 'id'); $actor = $request->getAttribute('actor'); $data = array_get($request->getParsedBody(), 'data'); return $this->bus->dispatch(new EditLink($id, $actor, $data)); }
public function adminEditSidecarPOST(Request $request, Response $response, $args) { // unpack json body $json = $request->getParsedBody(); // var_dump($json); $service = new SearchService(); $return = 'return'; $unit = 'disk:default'; $terms = ['uuid:' . $json['uuid']]; $asset = $service->search(compact('return', 'unit', 'terms')); $asset = $asset[$terms[0]][$json['uuid']]; $path = 'default://' . $asset->parent()->parent()->name() . DS . $asset->parent()->name() . DS . $json['uuid'] . '.png'; $this->logger->info(__CLASS__ . '::' . __FUNCTION__ . ': BUILT path: ' . $path); $assignedProps = $asset->assignedProperties(); // this will reload the asset from json file // create this before we attempt to overwrite the props $assetService = new AssetService($asset, ['path' => $path, 'filename' => $json['uuid']]); $this->logger->info(__CLASS__ . '::' . __FUNCTION__ . ': asset service is setup and loaded'); unset($json['uuid']); // overwrite each edited (submitted) prop // readonly props are not submittable foreach ($json as $key => $value) { $assignedProps->{'properties'}->{$key} = $value; } $asset->assignedProperties($assignedProps); // $this->logger->info(__CLASS__.'::'.__FUNCTION__.': asset to json: '.$asset->toJson()); $resp = []; // commit changes to file if ($assetService->storeJsonData()) { $resp['response'] = 'updated'; } else { $resp['response'] = 'failed'; } return $response->getBody()->write(json_encode($resp)); }
/** * 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 __construct(ServerRequestInterface $request) { $this->body = $request->getParsedBody(); foreach ($request->getQueryParams() as $param => $value) { switch ($param) { case 'sort': $parts = explode(',', $value); foreach ($parts as $part) { preg_match_all('/^(\\-)?([\\w]+)$/', $part, $matches); if (empty($matches[0])) { throw new \Exception('Invalid sort format.', 1); } $name = $matches[2][0]; $order = $matches[1][0]; $this->sort[$name] = $order; } break; case 'pageSize': case 'pageNumber': $this->{$param} = $value; break; default: $this->userFilters[$param] = $value; } } }
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $out = null) { $page = intval($request->getAttribute('page')) ?: 0; $pictures = $this->apodApi->getPage($page, $this->resultsPerPage); $response->getBody()->write(json_encode($pictures)); return $response->withHeader('Cache-Control', ['public', 'max-age=3600'])->withHeader('Content-Type', 'application/json'); }
/** * Constructor * * @param string $action Type of action to validate * @param ServerRequestInterface $request Request Http * @param ContainerInterface $container Dependency Injection */ public function __construct($action, ServerRequestInterface $request, ContainerInterface $container) { $this->action = $action; $this->idUser = $request->getAttribute('id'); $this->data = $request->getParsedBody(); $this->entityManager = $container->get('EntityManager'); }
/** * @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; }
/** * {@inheritdoc} */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, \Closure $next) { if ($request->getHeaderLine('Content-Type') == 'application/json') { $request = $request->withParsedBody(json_decode($request->getBody()->__toString(), true)); } return $next($request); }
/** * {@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 __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); }
/** * Validation middleware invokable class. * * @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->errors = []; $params = $request->getParams(); $this->validate($params, $this->validators); return $next($request, $response); }
/** * {@inheritdoc} */ protected function data(ServerRequestInterface $request, Document $document) { $id = array_get($request->getQueryParams(), 'id'); $actor = $request->getAttribute('actor'); $file = array_get($request->getUploadedFiles(), 'avatar'); return $this->bus->dispatch(new UploadAvatar($id, $file, $actor)); }
/** * 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) { if (in_array($request->getMethod(), $this->methods)) { $request = $request->withAttribute(self::$isValidAttribute, true); } return $next($request, $response); }
/** * Sets the TYPO3 Backend context to a certain workspace, * called by the Backend toolbar menu * * @param ServerRequestInterface $request * @param ResponseInterface $response * @return ResponseInterface */ public function switchWorkspaceAction(ServerRequestInterface $request, ResponseInterface $response) { $parsedBody = $request->getParsedBody(); $queryParams = $request->getQueryParams(); $workspaceId = (int) (isset($parsedBody['workspaceId']) ? $parsedBody['workspaceId'] : $queryParams['workspaceId']); $pageId = (int) (isset($parsedBody['pageId']) ? $parsedBody['pageId'] : $queryParams['pageId']); $finalPageUid = 0; $originalPageId = $pageId; $this->getBackendUser()->setWorkspace($workspaceId); while ($pageId) { $page = BackendUtility::getRecordWSOL('pages', $pageId, '*', ' AND pages.t3ver_wsid IN (0, ' . $workspaceId . ')'); if ($page) { if ($this->getBackendUser()->doesUserHaveAccess($page, 1)) { break; } } else { $page = BackendUtility::getRecord('pages', $pageId); } $pageId = $page['pid']; } if (isset($page['uid'])) { $finalPageUid = (int) $page['uid']; } $ajaxResponse = ['title' => \TYPO3\CMS\Workspaces\Service\WorkspaceService::getWorkspaceTitle($workspaceId), 'workspaceId' => $workspaceId, 'pageId' => $finalPageUid && $originalPageId == $finalPageUid ? null : $finalPageUid]; $response->getBody()->write(json_encode($ajaxResponse)); return $response; }
/** * {@inheritdoc} */ public function __invoke(Request $request, Response $response, callable $out = null) { $session = $request->getAttribute('session'); $actor = $this->getActor($session); $request = $request->withAttribute('actor', $actor); return $out ? $out($request, $response) : $response; }
/** * 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); }
/** * {@inheritdoc} */ public function data(ServerRequestInterface $request, Document $document) { $this->assertAdmin($request->getAttribute('actor')); $file = array_get($request->getUploadedFiles(), 'favicon'); $tmpFile = tempnam($this->app->storagePath() . '/tmp', 'favicon'); $file->moveTo($tmpFile); $extension = pathinfo($file->getClientFilename(), PATHINFO_EXTENSION); if ($extension !== 'ico') { $manager = new ImageManager(); $encodedImage = $manager->make($tmpFile)->resize(64, 64, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); })->encode('png'); file_put_contents($tmpFile, $encodedImage); $extension = 'png'; } $mount = new MountManager(['source' => new Filesystem(new Local(pathinfo($tmpFile, PATHINFO_DIRNAME))), 'target' => new Filesystem(new Local($this->app->publicPath() . '/assets'))]); if (($path = $this->settings->get('favicon_path')) && $mount->has($file = "target://{$path}")) { $mount->delete($file); } $uploadName = 'favicon-' . Str::lower(Str::quickRandom(8)) . '.' . $extension; $mount->move('source://' . pathinfo($tmpFile, PATHINFO_BASENAME), "target://{$uploadName}"); $this->settings->set('favicon_path', $uploadName); return parent::data($request, $document); }
/** * @param PayloadInterface $payload */ public function __construct(PayloadInterface $payload, ServerRequestInterface $request, ShiftMapper $shiftMapper) { $this->payload = $payload; $this->shiftMapper = $shiftMapper; //userId has already been verified by the AuthAdapter by this point $this->userId = (int) $request->getHeader('id')[0]; }