/**
  * 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;
 }
 /**
  * {@inheritdoc}
  */
 public function getData()
 {
     $headers = [];
     foreach ($this->request->getHeaders() as $name => $values) {
         $headers[$name] = implode(', ', $values);
     }
     $data = ['SERVER' => $this->request->getServerParams(), 'QUERY' => $this->request->getQueryParams(), 'COOKIES' => $this->request->getCookieParams(), 'HEADERS' => $headers, 'ATTRIBUTES' => $this->request->getAttributes()];
     return $data;
 }
 /**
  * {@inheritdoc}
  */
 public function read($sessionId)
 {
     $cookies = $this->request->getCookieParams();
     if (!is_null($decoded = json_decode($cookies, true)) && is_array($decoded)) {
         if (isset($decoded[$sessionId])) {
             $data = $decoded[$sessionId];
             if (isset($data['expires']) && Chronos::now()->getTimestamp() <= $data['expires']) {
                 return $data['data'];
             }
         }
     }
     return '';
 }
 public function __invoke(Request $request)
 {
     /** Check for token on header */
     if (isset($this->options['header'])) {
         if ($request->hasHeader($this->options['header'])) {
             $header = $request->getHeader($this->options['header'])[0];
             if (preg_match($this->options['regex'], $header, $matches)) {
                 return $matches[1];
             }
         }
     }
     /** If nothing on header, try query parameters */
     if (isset($this->options['parameter'])) {
         if (!empty($request->getQueryParams()[$this->options['parameter']])) {
             return $request->getQueryParams()[$this->options['parameter']];
         }
     }
     /** If nothing on parameters, try cookies */
     if (isset($this->options['cookie'])) {
         $cookie_params = $request->getCookieParams();
         if (!empty($cookie_params[$this->options["cookie"]])) {
             return $cookie_params[$this->options["cookie"]];
         }
     }
     /** If nothing until now, check argument as last try */
     if (isset($this->options['argument'])) {
         if ($route = $request->getAttribute('route')) {
             $argument = $route->getArgument($this->options['argument']);
             if (!empty($argument)) {
                 return $argument;
             }
         }
     }
     throw new TokenNotFoundException('Token not found');
 }
示例#5
0
 /**
  * {@inheritdoc}
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, \Closure $next)
 {
     if (isset($request->getCookieParams()[self::COOKIE])) {
         $token = $request->getCookieParams()[self::COOKIE];
     } else {
         //Making new token
         $token = substr(base64_encode(openssl_random_pseudo_bytes(self::TOKEN_LENGTH)), 0, self::TOKEN_LENGTH);
         //We can alter response cookies
         $response = $response->withAddedHeader('Set-Cookie', Cookie::create(self::COOKIE, $token, self::LIFETIME, $request->getAttribute('basePath'), $request->getAttribute('cookieDomain'))->packHeader());
     }
     if ($this->isRequired($request) && !$this->compare($token, $this->fetchToken($request))) {
         //Invalid CSRF token
         return $response->withStatus(412, 'Bad CSRF Token');
     }
     return $next($request->withAttribute(static::ATTRIBUTE, $token), $response);
 }
示例#6
0
 /**
  * {@inheritdoc}
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, \Closure $next)
 {
     $cookies = $request->getCookieParams();
     $outerID = null;
     if (isset($cookies[self::COOKIE])) {
         if ($this->store()->isStarted()) {
             $outerID = $this->store()->getID();
         }
         //Mounting ID retrieved from cookies
         $this->store()->setID($cookies[self::COOKIE]);
     }
     $response = $next();
     if (empty($this->store) && $this->container->hasInstance(SessionStore::class)) {
         //Store were started by itself
         $this->store = $this->container->get(SessionStore::class);
     }
     if (!empty($this->store) && ($this->store->isStarted() || $this->store->isDestroyed())) {
         $response = $this->setCookie($request, $response, $this->store, $cookies);
     }
     //Restoring original session, not super efficient operation
     if (!empty($outerID)) {
         $this->store->setID($outerID);
     }
     return $response;
 }
 /**
  * Handles a frontend request based on the _GP "eID" variable.
  *
  * @param ServerRequestInterface $request
  * @return NULL|\Psr\Http\Message\ResponseInterface
  */
 public function handleRequest(ServerRequestInterface $request)
 {
     // Timetracking started
     $configuredCookieName = trim($GLOBALS['TYPO3_CONF_VARS']['BE']['cookieName']);
     if (empty($configuredCookieName)) {
         $configuredCookieName = 'be_typo_user';
     }
     if ($request->getCookieParams()[$configuredCookieName]) {
         $GLOBALS['TT'] = new TimeTracker();
     } else {
         $GLOBALS['TT'] = new NullTimeTracker();
     }
     $GLOBALS['TT']->start();
     // Hook to preprocess the current request
     if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['preprocessRequest'])) {
         foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['preprocessRequest'] as $hookFunction) {
             $hookParameters = array();
             GeneralUtility::callUserFunction($hookFunction, $hookParameters, $hookParameters);
         }
         unset($hookFunction);
         unset($hookParameters);
     }
     // Remove any output produced until now
     $this->bootstrap->endOutputBufferingAndCleanPreviousOutput();
     return $this->dispatch($request);
 }
示例#8
0
 /**
  * Checks if the user has access to the site. This is the case if the site
  * is public or if the user has entered the access key.
  * @param ServerRequestInterface $serverRequest The request.
  * @return boolean True if the user has access, false otherwise.
  */
 private function checkSiteAccess(ServerRequestInterface $serverRequest)
 {
     $correctKey = $this->website->getConfig()->get(Config::OPTION_ACCESS_CODE);
     if (empty($correctKey)) {
         // The website doesn't use an access key
         return true;
     }
     // Check for key in cookie
     $cookies = $serverRequest->getCookieParams();
     if (isset($cookies["key"]) && $cookies["key"] === $correctKey) {
         return true;
     }
     // Newly entered key
     $postData = $serverRequest->getParsedBody();
     if (isset($postData["key"])) {
         $text = $this->website->getText();
         if ($postData["key"] === $correctKey) {
             $text->addMessage($text->t("access_key.access_granted"));
             return true;
         } else {
             $text->addMessage($text->t("access_key.entered_wrong_key"));
             return false;
         }
     }
     return false;
 }
 /**
  * Execute the middleware.
  *
  * @param ServerRequestInterface $request
  * @param ResponseInterface      $response
  * @param callable               $next
  *
  * @return ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     if (session_status() === PHP_SESSION_DISABLED) {
         throw new RuntimeException('PHP sessions are disabled');
     }
     if (session_status() === PHP_SESSION_ACTIVE) {
         throw new RuntimeException('Failed to start the session: already started by PHP.');
     }
     //Session name
     $name = $this->name ?: session_name();
     session_name($name);
     //Session id
     $id = $this->id;
     if (empty($id)) {
         $cookies = $request->getCookieParams();
         if (!empty($cookies[$name])) {
             $id = $cookies[$name];
         }
     }
     if (!empty($id)) {
         session_id($id);
     }
     session_start();
     $request = self::startStorage($request, isset($_SESSION[self::STORAGE_KEY]) ? $_SESSION[self::STORAGE_KEY] : []);
     $response = $next($request, $response);
     if (session_status() === PHP_SESSION_ACTIVE && session_name() === $name) {
         $_SESSION[self::STORAGE_KEY] = self::stopStorage($request);
         session_write_close();
     }
     return $response;
 }
 /**
  * Timetracking started depending if a Backend User is logged in
  *
  * @return void
  */
 protected function initializeTimeTracker()
 {
     $configuredCookieName = trim($GLOBALS['TYPO3_CONF_VARS']['BE']['cookieName']) ?: 'be_typo_user';
     /** @var TimeTracker timeTracker */
     $this->timeTracker = GeneralUtility::makeInstance(TimeTracker::class, $this->request->getCookieParams()[$configuredCookieName] ? true : false);
     $this->timeTracker->start();
 }
 /**
  * @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());
 }
示例#12
0
 /**
  * Get the access token referred to by the request cookie.
  *
  * @param Request $request
  * @return AccessToken|null
  */
 protected function getToken(Request $request)
 {
     $token = array_get($request->getCookieParams(), 'flarum_remember');
     if ($token) {
         return AccessToken::find($token);
     }
 }
示例#13
0
 /**
  * {@inheritdoc}
  */
 public function __invoke(Request $request, Response $response, callable $out = null)
 {
     if (($token = array_get($request->getCookieParams(), 'flarum_remember')) && ($accessToken = AccessToken::valid($token))) {
         $this->app->instance('flarum.actor', $user = $accessToken->user);
         $user->updateLastSeen()->save();
     }
     return $out ? $out($request, $response) : $response;
 }
 /**
  * {@inheritdoc}
  */
 public function createRequest(ServerRequestInterface $psrRequest)
 {
     $parsedBody = $psrRequest->getParsedBody();
     $parsedBody = is_array($parsedBody) ? $parsedBody : array();
     $request = new Request($psrRequest->getQueryParams(), $parsedBody, $psrRequest->getAttributes(), $psrRequest->getCookieParams(), $this->getFiles($psrRequest->getUploadedFiles()), $psrRequest->getServerParams(), $psrRequest->getBody()->__toString());
     $request->headers->replace($psrRequest->getHeaders());
     return $request;
 }
示例#15
0
文件: Util.php 项目: tonis-io/oauth2
 /**
  * Converts a PSR-7 request into an OAuth2 request.
  *
  * @param ServerRequestInterface $psrRequest
  * @return Request
  */
 public static function convertRequestFromPsr7(ServerRequestInterface $psrRequest)
 {
     $headers = [];
     foreach ($psrRequest->getHeaders() as $header => $value) {
         $headers[$header] = implode(';', $value);
     }
     return new Request($psrRequest->getQueryParams(), is_array($psrRequest->getParsedBody()) ? $psrRequest->getParsedBody() : [], $psrRequest->getAttributes(), $psrRequest->getCookieParams(), self::getFiles($psrRequest->getUploadedFiles()), $psrRequest->getServerParams(), $psrRequest->getBody()->__toString(), $headers);
 }
示例#16
0
 /**
  * Execute the middleware.
  *
  * @param ServerRequestInterface $request
  * @param ResponseInterface      $response
  * @param callable               $next
  *
  * @return ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $session = $this->factory->newInstance($request->getCookieParams());
     if ($this->name !== null) {
         $session->setName($this->name);
     }
     $request = Middleware::setAttribute($request, self::KEY, $session);
     return $next($request, $response);
 }
示例#17
0
 /**
  * {@inheritdoc}
  */
 public function __invoke(Request $request, Response $response, callable $out = null)
 {
     if (($token = array_get($request->getCookieParams(), 'flarum_remember')) && ($accessToken = AccessToken::valid($token)) && $accessToken->user->isAdmin()) {
         $this->app->instance('flarum.actor', $accessToken->user);
     } else {
         die('Access Denied');
     }
     return $out ? $out($request, $response) : $response;
 }
示例#18
0
 /**
  * Create instance from a server request.
  *
  * @param ServerRequestInterface $request
  *
  * @return RequestCookies
  */
 public static function createFromRequest(ServerRequestInterface $request) : RequestCookies
 {
     $cookies = [];
     $cookieParams = $request->getCookieParams();
     foreach ($cookieParams as $name => $value) {
         $cookies[] = new Cookie($name, $value);
     }
     return new static($cookies);
 }
示例#19
0
 /**
  * {@inheritdoc}
  */
 public function __invoke(Request $request, Response $response, callable $next)
 {
     if (isset($request->getCookieParams()[$this->httpConfig->csrfCookie()])) {
         $token = $request->getCookieParams()[$this->httpConfig->csrfCookie()];
     } else {
         //Making new token
         $token = $this->generateToken();
         //Token cookie!
         $cookie = $this->tokenCookie($request->getUri(), $token);
         //We can alter response cookies
         $response = $response->withAddedHeader('Set-Cookie', $cookie->createHeader());
     }
     if ($this->isRequired($request) && !$this->compare($token, $this->fetchToken($request))) {
         //Invalid CSRF token
         return $response->withStatus(412, 'Bad CSRF Token');
     }
     return $next($request->withAttribute(static::ATTRIBUTE, $token), $response);
 }
示例#20
0
 /**
  * Execute the middleware
  *
  * @param ServerRequestInterface $request
  * @param ResponseInterface      $response
  *
  * @return ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $factory = $this->factory ?: new SessionFactory();
     $session = $factory->newInstance($request->getCookieParams());
     if ($this->name !== null) {
         $session->setName($this->name);
     }
     $request = $request->withAttribute('SESSION', $session);
     return $next($request, $response);
 }
示例#21
0
 protected function resolveSources(ServerRequestInterface $request)
 {
     $original_data = ['get' => $request->getQueryParams(), 'post' => $request->getParsedBody(), 'file' => $request->getUploadedFiles(), 'cookie' => $request->getCookieParams(), 'uri' => $this->resolveUriSource($request)];
     foreach ($this->param_sources as $item => $source) {
         if (isset($original_data[$source][$item])) {
             $params[$item] = $original_data[$source][$item];
         }
     }
     return $params;
 }
示例#22
0
 private function decryptRequestCookies(ServerRequestInterface $request)
 {
     $cookies = $request->getCookieParams();
     foreach ($cookies as $key => $cookie) {
         if (!in_array($key, $this->except)) {
             $cookies[$key] = $this->encrypter->decrypt($cookie);
         }
     }
     $request = $request->withCookieParams($cookies);
     return $request;
 }
示例#23
0
 /**
  * Timetracking started depending if a Backend User is logged in
  *
  * @return void
  */
 protected function initializeTimeTracker()
 {
     $configuredCookieName = trim($GLOBALS['TYPO3_CONF_VARS']['BE']['cookieName']) ?: 'be_typo_user';
     $this->timeTracker = new TimeTracker($this->request->getCookieParams()[$configuredCookieName] ? true : false);
     // We have to define this as reference here, because there is code around
     // which exchanges the TT object in the global variable. The reference ensures
     // that the $timeTracker member always works on the same object as the global variable.
     // This is a dirty workaround and bypasses the protected access modifier of the $timeTracker member.
     $GLOBALS['TT'] =& $this->timeTracker;
     $this->timeTracker->start();
 }
示例#24
0
 /**
  * @param ServerRequestInterface $request
  * @return Storage
  */
 public function readFromRequest(ServerRequestInterface $request)
 {
     $cookies = $request->getCookieParams();
     if (isset($cookies[$this->name])) {
         $this->id = $cookies[$this->name];
     } else {
         $this->id = $this->generateId();
         $this->reset = true;
     }
     return new Storage($this->handler->read($this->id));
 }
示例#25
0
 /**
  * {@inheritdoc}
  */
 public function __invoke(Request $request, Response $response, callable $out = null)
 {
     $id = array_get($request->getCookieParams(), 'flarum_remember');
     if ($id) {
         $token = AccessToken::find($id);
         if ($token) {
             $token->touch();
             $session = $request->getAttribute('session');
             $session->set('user_id', $token->user_id);
         }
     }
     return $out ? $out($request, $response) : $response;
 }
示例#26
0
文件: SetLocale.php 项目: flarum/core
 /**
  * {@inheritdoc}
  */
 public function __invoke(Request $request, Response $response, callable $out = null)
 {
     $actor = $request->getAttribute('actor');
     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 $out ? $out($request, $response) : $response;
 }
示例#27
0
 /**
  * Execute the middleware.
  *
  * @param ServerRequestInterface $request
  * @param ResponseInterface      $response
  * @param callable               $next
  *
  * @return ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $session = $this->factory->newInstance($request->getCookieParams());
     if ($this->name !== null) {
         $session->setName($this->name);
     }
     $fragment = $session->getSegment(self::STORAGE_KEY);
     $request = self::setAttribute($request, self::KEY, $session);
     $request = self::startStorage($request, $fragment->get(self::STORAGE_KEY) ?: []);
     $response = $next($request, $response);
     $fragment->set(self::STORAGE_KEY, self::stopStorage($request));
     return $response;
 }
示例#28
0
 /**
  * Construct action request.
  *
  * @param \Psr\Http\Message\ServerRequestInterface $request Request to wrap.
  */
 public function __construct(\Psr\Http\Message\ServerRequestInterface $request)
 {
     parent::__construct($request->getBody());
     foreach ($request->getHeaders() as $name => $value) {
         $this->setHeader($name, $value);
     }
     $this->protocolVersion = $request->getProtocolVersion();
     $this->method = $request->getMethod();
     $this->requestTarget = $request->getRequestTarget();
     $this->uri = $request->getUri();
     $this->attributes = $request->getAttributes();
     $this->cookies = $request->getCookieParams();
     $this->data = $request->getParsedBody();
     $this->query = $request->getQueryParams();
     $this->server = $request->getServerParams();
     $this->files = $request->getUploadedFiles();
     if (isset($this->server['SCRIPT_NAME'])) {
         $this->attributes['basePath'] = dirname($this->server['SCRIPT_NAME']);
         $this->attributes['scriptName'] = basename($this->server['SCRIPT_NAME']);
     } else {
         $this->attributes['basePath'] = '/';
         $this->attributes['scriptName'] = 'index.php';
     }
     if (!isset($this->attributes['path'])) {
         $this->attributes['path'] = self::findPath($this);
     }
     if (!isset($this->attributes['rewrite'])) {
         $this->attributes['rewrite'] = false;
     }
     if (!isset($this->attributes['accepts'])) {
         $this->attributes['accepts'] = [];
         if (isset($this->server['HTTP_ACCEPT'])) {
             $contentTypes = explode(',', $this->server['HTTP_ACCEPT']);
             foreach ($contentTypes as $contentType) {
                 $contentType = explode(';', $contentType);
                 $this->attributes['accepts'][] = trim(strtolower($contentType[0]));
             }
         }
     }
     if (!isset($this->attributes['encodings'])) {
         $this->attributes['encodings'] = [];
         if (isset($this->server['HTTP_ACCEPT_ENCODING'])) {
             $acceptEncodings = explode(',', $this->server['HTTP_ACCEPT_ENCODING']);
             foreach ($acceptEncodings as $encoding) {
                 $this->attributes['encodings'][] = trim(strtolower($encoding));
             }
         }
     }
 }
示例#29
0
 /**
  * {@inheritdoc}
  */
 public function __invoke(Request $request, Response $response, callable $out = null)
 {
     do {
         // Check if a guest.
         $actor = $request->getAttribute('actor');
         if (!$actor->isGuest()) {
             break;
         }
         // Check for the global cookie setting.
         $authSettings = SingleSO::settingsAuth($this->settings, false);
         if (!$authSettings) {
             break;
         }
         // Check if the cookie is configured.
         $globalCookie = $authSettings['global_cookie'];
         if (!$globalCookie) {
             break;
         }
         // Check if that cookie is set.
         $cookies = $request->getCookieParams();
         if (!isset($cookies[$globalCookie])) {
             break;
         }
         // Get current request path.
         // And URL hash is unfortunately unavailable.
         // Such data will be discarded on auto-login.
         $requestUri = $request->getUri();
         $requestPath = $requestUri->getPath();
         // Ignore if the controller path, avoid infinite redirect.
         if (strpos($requestPath, SingleSO::CONTROLLER_PATH) === 0) {
             break;
         }
         // Get any query parameters.
         $query = $requestUri->getQuery();
         // Create the redirect path, preserve ? even if no query.
         $params = $request->getQueryParams();
         $redirect = $requestPath . ($query ? '?' . $query : (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '?') !== false ? '?' : ''));
         // Create the login path.
         $loginPath = rtrim($this->app->url(), '/') . SingleSO::CONTROLLER_PATH . '/login';
         // Create the redirect target, include return redirect parameters.
         $target = SingleSO::addParams($loginPath, ['redirect' => $redirect]);
         // Take over the response, redirect to login URL.
         return new RedirectResponse($target);
     } while (false);
     return $out ? $out($request, $response) : $response;
 }
示例#30
-2
文件: SapiServer.php 项目: jivoo/http
 /**
  * @return Cookie\CookiePool
  */
 public function getCookies()
 {
     if (!isset($this->cookies)) {
         $server = $this->request->getServerParams();
         $secure = isset($server['HTTPS']) && $server['HTTPS'] != 'off';
         $this->cookies = new Cookie\CookiePool($this->path, $this->domain, true, $secure);
         foreach ($this->request->getCookieParams() as $name => $value) {
             $this->cookies->add(new Cookie\RequestCookie($name, $value));
         }
     }
     return $this->cookies;
 }