protected function getNotFoundResponse(RequestInterface $request, ResponseInterface $response, \Exception $exception) { $output = json_encode(['error_message' => $exception->getMessage()], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); $body = new Body(fopen('php://temp', 'r+')); $body->write($output); return $response->withStatus(404)->withHeader('Content-type', 'application/json')->withBody($body); }
/** * 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; }
/** * Mount redirect headers into response * * @param UriInterface|string $uri * @param int $status * @return ResponseInterface * @throws \InvalidArgumentException */ public function redirect($uri, $status = 302) { if (!is_string($uri) && !$uri instanceof UriInterface) { throw new \InvalidArgumentException("Redirect allowed only for string or UriInterface uris."); } return $this->response->withStatus($status)->withHeader("Location", (string) $uri); }
public function validateToken(ServerRequestInterface $request, ResponseInterface $response) { $authHeader = $request->getHeader('HTTP_AUTHORIZATION'); if (empty($authHeader)) { $authHeader = apache_request_headers(); if (empty($authHeader['Authorization'])) { throw (new OAuth2Exception('Authorization header is missing'))->displayMessage(OAuth2Exception::FORBIDDEN)->response($response->withStatus(403)); } $authHeader = $authHeader['Authorization']; } else { $authHeader = $authHeader[0]; } list($token) = sscanf($authHeader, 'Bearer %s'); if (!$token) { throw (new OAuth2Exception('Token is missing in the request'))->displayMessage(OAuth2Exception::FORBIDDEN)->response($response->withStatus(403)); } try { $token = (new Parser())->parse($token); } catch (\Exception $e) { throw (new OAuth2Exception('Token was tampered'))->displayMessage(OAuth2Exception::FORBIDDEN)->response($response->withStatus(403)); } if ($token->getClaim('exp') <= time()) { throw (new OAuth2Exception('Token expired'))->displayMessage(OAuth2Exception::FORBIDDEN)->response($response->withStatus(403)); } $this->info['id'] = $token->getClaim('sub'); foreach (explode(',', $token->getClaim('cc')) as $customClaim) { $this->info[$customClaim] = $token->getClaim($customClaim); } if (!$token->verify(new Sha256(), $this->config['public-key'])) { throw (new OAuth2Exception('Token was tampered'))->displayMessage(OAuth2Exception::FORBIDDEN)->response($response->withStatus(403)); } return $response; }
/** * @param ServerRequestInterface $request PSR7 Request. * @param ResponseInterface $response PSR7 Response. * @return ResponseInterface */ public function run(RequestInterface $request, ResponseInterface $response) { $widgetType = $request->getParam('widget_type'); $widgetOptions = $request->getParam('widget_options'); if (!$widgetType) { $this->setSuccess(false); return $response->withStatus(400); } try { $widget = $this->widgetFactory->create($widgetType); $widget->setView($this->widgetView); if (is_array($widgetOptions)) { $widget->setData($widgetOptions); } $widgetHtml = $widget->renderTemplate($widgetType); $widgetId = $widget->widgetId(); $this->setWidgetHtml($widgetHtml); $this->setWidgetId($widgetId); $this->setSuccess(true); return $response; } catch (Exception $e) { $this->addFeedback('error', sprintf('An error occured reloading the widget: "%s"', $e->getMessage())); $this->addFeedback('error', $e->getMessage()); $this->setSuccess(false); return $response->withStatus(500); } }
/** * Note that the lost-password action should never change status code and always return 200. * * @param RequestInterface $request A PSR-7 compatible Request instance. * @param ResponseInterface $response A PSR-7 compatible Response instance. * @return ResponseInterface * @todo This should be done via an Authenticator object. */ public function run(RequestInterface $request, ResponseInterface $response) { $username = $request->getParam('username'); if (!$username) { $this->addFeedback('error', 'Missing username.'); $this->setSuccess(false); return $response->withStatus(404); } $recaptchaValue = $request->getParam('g-recaptcha-response'); if (!$recaptchaValue) { $this->addFeedback('error', 'Missing captcha.'); $this->setSuccess(false); return $response->withStatus(404); } if (!$this->validateCaptcha($recaptchaValue)) { $this->addFeedback('error', 'Invalid captcha.'); $this->setSuccess(false); return $response->withStatus(404); } $user = $this->loadUser($username); if (!$user) { // Fail silently. $this->logger->error('Lost password request: can not find user in database.'); return $response; } $token = $this->generateLostPasswordToken($user); $this->sendLostPasswordEmail($user, $token); return $response; }
/** * Add headers represented by an array of header lines. * * @param string[] $headers Response headers as array of header lines. * * @return $this * * @throws \UnexpectedValueException For invalid header values. * @throws \InvalidArgumentException For invalid status code arguments. */ public function setHeadersFromArray(array $headers) { $statusLine = trim(array_shift($headers)); $parts = explode(' ', $statusLine, 3); if (count($parts) < 2 || substr(strtolower($parts[0]), 0, 5) !== 'http/') { throw new \UnexpectedValueException(sprintf('"%s" is not a valid HTTP status line', $statusLine)); } $reasonPhrase = count($parts) > 2 ? $parts[2] : ''; $this->response = $this->response->withStatus((int) $parts[1], $reasonPhrase)->withProtocolVersion(substr($parts[0], 5)); foreach ($headers as $headerLine) { $headerLine = trim($headerLine); if ('' === $headerLine) { continue; } $parts = explode(':', $headerLine, 2); if (count($parts) !== 2) { throw new \UnexpectedValueException(sprintf('"%s" is not a valid HTTP header line', $headerLine)); } $name = trim(urldecode($parts[0])); $value = trim(urldecode($parts[1])); if ($this->response->hasHeader($name)) { $this->response = $this->response->withAddedHeader($name, $value); } else { $this->response = $this->response->withHeader($name, $value); } } return $this; }
/** * @param RequestInterface $request A PSR-7 compatible Request instance. * @param ResponseInterface $response A PSR-7 compatible Response instance. * @return ResponseInterface */ public function run(RequestInterface $request, ResponseInterface $response) { try { $objType = $request->getParam('obj_type'); $objId = $request->getParam('obj_id'); if (!$objType) { $this->setSuccess(false); return $response->withStatus(404); } if (!$objId) { $this->setSuccess(false); return $response->withStatus(404); } $this->logger->debug(sprintf('Admin Deleting object "%s" ID %s', $objType, $objId)); $obj = $this->modelFactory()->create($objType); $obj->load($objId); if (!$obj->id()) { $this->setSuccess(false); return $response->withStatus(404); } $res = $obj->delete(); if ($res) { $this->setSuccess(true); return $response; } } catch (Exception $e) { $this->setSuccess(false); return $response->withStatus(500); } }
/** * Execute the middleware. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { if (empty($this->router)) { throw new RuntimeException('No RouterContainer instance has been provided'); } $matcher = $this->router->getMatcher(); $route = $matcher->match($request); if (!$route) { $failedRoute = $matcher->getFailedRoute(); switch ($failedRoute->failedRule) { case 'Aura\\Router\\Rule\\Allows': return $response->withStatus(405); // 405 METHOD NOT ALLOWED // 405 METHOD NOT ALLOWED case 'Aura\\Router\\Rule\\Accepts': return $response->withStatus(406); // 406 NOT ACCEPTABLE // 406 NOT ACCEPTABLE default: return $response->withStatus(404); // 404 NOT FOUND } } $request = Middleware::setAttribute($request, self::KEY, $route); foreach ($route->attributes as $name => $value) { $request = $request->withAttribute($name, $value); } $response = $this->executeCallable($route->handler, $request, $response); return $next($request, $response); }
public function __invoke(Request $req, Response $res, $args = []) { $vaultName = $args['vaultName']; if (!Vault::create($vaultName)) { return $res->withStatus(500); } return $res->withStatus(201); }
public function __invoke(Request $request, Response $response, callable $out = null) { if (!$request->hasHeader('authorization')) { return $response->withStatus(401); } if (!$this->isValid($request)) { return $response->withStatus(403); } return $out($request, $response); }
/** * {@inheritdoc} */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response) { try { $page = new Page($this->basePath, $this->defaultPage); return $response->withStatus(301)->withHeader('Location', '/' . $page->getName()); } catch (\Exception $e) { $this->logger->debug(sprintf('Page creation failed, due to "%s"', $e->getMessage())); } return $response->withStatus(404); }
/** * Execute the middleware. * * @param RequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next) { if ($request->getMethod() !== 'GET') { return $response->withStatus(405); } $file = $this->getFilename($request); if (!is_file($file)) { return $response->withStatus(404); } return $next($request, $response->withBody(Middleware::createStream($file))); }
public function __invoke(Request $req, Response $res, $args = []) { $vaultName = $args['vaultName']; $multipartID = $args['multipartID']; if (!($vault = Vault::get($vaultName))) { return $res->withStatus(404); } if (!($m = $vault->getMultipart($multipartID))) { return $res->withStatus(404); } return $res->withJson($m->serializeArray(true), 200, JSON_PRETTY_PRINT); }
public function __invoke(Request $req, Response $res, $args = []) { $vaultName = $args['vaultName']; $multipartID = $args['multipartID']; if (!($vault = Vault::get($vaultName))) { return $res->withStatus(404); } if ($m = $vault->getMultipart($multipartID)) { $m->delete(); } return $res->withStatus(204); }
/** * {@inheritdoc} */ public function process(RequestInterface $request, DelegateInterface $delegate) { try { $response = $delegate->next($request); } catch (\Exception $e) { if ($this->logger instanceof LoggerInterface) { $this->logger->error($e); } return $this->response->withStatus(500); } return $response; }
public function __invoke(Request $req, Response $res, $args = []) { $vaultName = $args['vaultName']; $archiveID = $args['archiveID']; if (!($v = Vault::get($vaultName))) { return $res->withStatus(404); } if ($archive = $v->getArchive($archiveID)) { $archive->delete(); } $v->invalidateInventory(); return $res->withStatus(204); }
public function __invoke(Request $req, Response $res, $args = []) { $vaultName = $args['vaultName']; $jobID = $args['jobID']; if (!($v = Vault::get($vaultName))) { return $res->withStatus(404); } if (!($job = $v->getJob($jobID))) { return $res->withStatus(404); } $job->forceCompletion(); return $res->withStatus(200); }
/** * @return ResponseInterface */ protected function handle() { $handlers = $this->isDevelopment ? $this->devHandlers : $this->productionHandlers; $class = get_class($this->e); if (array_key_exists($class, $handlers)) { $handler = $handlers[$class]; return call_user_func($handler); } if ($this->isDevelopment) { return $this->handleDevError(); } return $this->response->withStatus(500); }
public function __invoke(Request $req, Response $res, $args = []) { $vaultName = $args['vaultName']; if (!($v = Vault::get($vaultName))) { return $res->withStatus(404); } $postData = file_get_contents('php://input'); $params = json_decode($postData, true); $job = $v->createJob($params); if (!empty($GLOBALS['config']['throwPolicyEnforcedException']) && $job->getAction() == 'ArchiveRetrieval') { return $res->policyEnforcedException(); } return $res->withStatus(202)->withHeader('x-amz-job-id', $job->getId()); }
/** * Execute the middleware. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $route = $this->router->dispatch($request->getMethod(), $request->getUri()->getPath()); if ($route[0] === Dispatcher::NOT_FOUND) { return $response->withStatus(404); } if ($route[0] === Dispatcher::METHOD_NOT_ALLOWED) { return $response->withStatus(405); } foreach ($route[2] as $name => $value) { $request = $request->withAttribute($name, $value); } $response = $this->executeCallable($route[1], $request, $response); return $next($request, $response); }
public function __invoke(Request $req, Response $res, $args = []) { $vaultName = $args['vaultName']; if (!($vault = Vault::get($vaultName))) { return $res->withStatus(404); } if (!($partSize = $req->getHeaderLine('x-amz-part-size'))) { return $res->withStatus(400)->write('Part size missing.'); } if (!($desc = $req->getHeaderLine('x-amz-archive-description'))) { $desc = ''; } $m = $vault->createMultipart($partSize, $desc); return $res->withStatus(201)->withHeader('x-amz-multipart-upload-id', $m->getId()); }
public function __invoke(Request $request, Response $response, callable $out = null) { //Sin header no pasas if (!$request->hasHeader('authorization')) { $response->getBody()->write('WTF! Unauthorized'); return $response->withStatus(401); } //Autenticacion valida? if (!$this->isValid($request)) { $response->getBody()->write('Invalid token!'); return $response->withStatus('403'); } //seguimos con la suguiente capa return $out($request, $response); }
public function testWithStatusFail() { try { $this->response->withStatus(9999); $this->fail(); } catch (InvalidArgumentException $e) { $this->assertEquals('Invalid status code "9999".', $e->getMessage()); } try { $this->response->withStatus([]); $this->fail(); } catch (InvalidArgumentException $e) { $this->assertEquals('Invalid status code. It must be a 3-digit integer.', $e->getMessage()); } }
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next) { //$response->getBody()->write('BEFORE'); $user = AuthService::getUser(); if (!$user->isLogin) { $newResponse = $response->withStatus(302)->withHeader('Location', '/auth/login'); return $newResponse; } if (!$user->isAdmin()) { $newResponse = $response->withStatus(302)->withHeader('Location', '/user'); return $newResponse; } $response = $next($request, $response); return $response; }
/** * Execute the middleware. * * @param RequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next) { $key = $this->getCacheKey($request); $item = $this->cache->getItem($key); //If it's cached if ($item->isHit()) { $headers = $item->get(); $cachedResponse = $response->withStatus(304); foreach ($headers as $name => $header) { $cachedResponse = $cachedResponse->withHeader($name, $header); } if ($this->cacheUtil->isNotModified($request, $cachedResponse)) { return $cachedResponse; } $this->cache->deleteItem($key); } $response = $next($request, $response); //Add cache-control header if ($this->cacheControl && !$response->hasHeader('Cache-Control')) { $response = $this->cacheUtil->withCacheControl($response, $this->cacheControl); } //Add Last-Modified header if (!$response->hasHeader('Last-Modified')) { $response = $this->cacheUtil->withLastModified($response, time()); } //Save in the cache if ($this->cacheUtil->isCacheable($response)) { $item->set($response->getHeaders()); $item->expiresAfter($this->cacheUtil->getLifetime($response)); $this->cache->save($item); } return $response; }
public function __invoke(Request $request, Response $response, callable $next) { $xml = file_get_contents('php://input'); $xml = preg_replace('/[\\n\\r]/', '', $xml); $xml = preg_replace('/>\\s+/', '>', $xml); $rootBodyClass = 'DTS\\eBaySDK\\Trading\\Types\\AbstractResponseType'; $parserBody = new XmlParser($rootBodyClass); $body = mb_strstr($xml, "<soapenv:Body>", false); $body = trim($body, "<soapenv:Body>"); $body = mb_strstr($body, "</soapenv:Body>", true); $body = '<' . $body; /** @var AbstractResponseType $notification */ $notification = $parserBody->parse($body); $notification->NotificationSignature = mb_strstr($xml, '<ebl:NotificationSignature xmlns:ebl="urn:ebay:apis:eBLBaseComponents">', false); $notification->NotificationSignature = trim($notification->NotificationSignature, '<ebl:NotificationSignature xmlns:ebl="urn:ebay:apis:eBLBaseComponents">'); $notification->NotificationSignature = mb_strstr($notification->NotificationSignature, "</ebl:NotificationSignature>", true); $timestamp = mb_strstr($body, "<Timestamp>", false); $timestamp = trim($timestamp, "<Timestamp>"); $timestamp = mb_strstr($timestamp, "</Timestamp>", true); if ($this->calculationSignature($timestamp) !== $notification->NotificationSignature) { throw new \Exception("Not Equalse signature", 403); } $item = ['add_date' => $notification->Timestamp->format("Y-m-d h:i:s"), 'soapaction' => $notification->NotificationEventName, 'data' => $body]; $this->store->create($item); return $response->withStatus(200); }
/** * Invoca la respuesta * * @param ServerRequestInterface $request Instancia de ServerRequestInterface * @param ResponseInterface $response Instancia de ResponseInterface * @param \Throwable $error Instancia de Throwable * * @return mixed */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, \Throwable $error) { $output = $this->render($error); $body = new Body(fopen('php://temp', 'r+')); $body->write($output); return $response->withStatus(500)->withHeader('Content-type', 'application/json')->withBody($body); }
/** * Process an incoming request and/or response. * * Accepts a server-side request and a response instance, and does * something with them. * * If the response is not complete and/or further processing would not * interfere with the work done in the middleware, or if the middleware * wants to delegate to another process, it can use the `$out` callable * if present. * * If the middleware does not return a value, execution of the current * request is considered complete, and the response instance provided will * be considered the response to return. * * Alternately, the middleware may return a response instance. * * Often, middleware will `return $out();`, with the assumption that a * later middleware will return a response. * * @param Request $request * @param Response $response * @param null|callable $out * @return null|Response */ public function __invoke(Request $request, Response $response, callable $out = null) { $shortCode = $request->getAttribute('shortCode'); try { $url = $this->urlShortener->shortCodeToUrl($shortCode); if (!isset($url)) { return $out($request, $response->withStatus(404), 'Not found'); } $imagePath = $this->previewGenerator->generatePreview($url); return $this->generateImageResponse($imagePath); } catch (InvalidShortCodeException $e) { return $out($request, $response->withStatus(404), 'Not found'); } catch (PreviewGenerationException $e) { return $out($request, $response->withStatus(500), 'Preview generation error'); } }
/** * Invoke error handler * * @param ServerRequestInterface $request The most recent Request object * @param ResponseInterface $response The most recent Response object * @param string[] $methods Allowed HTTP methods * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $methods) { if ($request->getMethod() === 'OPTIONS') { $status = 200; $contentType = 'text/plain'; $output = $this->renderPlainNotAllowedMessage($methods); } else { $status = 405; $contentType = $this->determineContentType($request); switch ($contentType) { case 'application/json': $output = $this->renderJsonNotAllowedMessage($methods); break; case 'text/xml': case 'application/xml': $output = $this->renderXmlNotAllowedMessage($methods); break; case 'text/html': $output = $this->renderHtmlNotAllowedMessage($methods); break; } } $body = new Body(fopen('php://temp', 'r+')); $body->write($output); $allow = implode(', ', $methods); return $response->withStatus($status)->withHeader('Content-type', $contentType)->withHeader('Allow', $allow)->withBody($body); }