Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

中间件和session相关优化 #36

Merged
merged 11 commits into from
Aug 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/framework/src/Di/Annotation/Inject.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@
class Inject implements PropertyAnnotation
{
/**
* @param null|string $id 注入的类型
* @param string $id 注入的类型
*/
public function __construct(
protected ?string $id = null
protected string $id = ''
) {
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace Max\Exception\Handler;

use Max\Http\Message\Contract\HeaderInterface;
use Max\Http\Message\Contract\StatusCodeInterface;
use Max\Http\Message\Response;
use Max\Http\Message\Stream\StringStream;
use Max\Utils\Str;
Expand Down Expand Up @@ -43,12 +45,12 @@ public function handle(Throwable $throwable, ServerRequestInterface $request): ?
$whoops->{RunInterface::EXCEPTION_HANDLER}($throwable);
$content = ob_get_clean();

return new Response(500, ['Content-Type' => $contentType], new StringStream($content));
return new Response(StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR, [HeaderInterface::HEADER_CONTENT_TYPE => $contentType], new StringStream($content));
}

protected function negotiateHandler(ServerRequestInterface $request)
{
$accepts = $request->getHeaderLine('accept');
$accepts = $request->getHeaderLine(HeaderInterface::HEADER_ACCEPT);
foreach (self::$preference as $contentType => $handler) {
if (Str::contains($accepts, $contentType)) {
return [$this->setupHandler(new $handler(), $request), $contentType];
Expand Down
21 changes: 14 additions & 7 deletions src/http-message/src/Contract/HeaderInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,18 @@

interface HeaderInterface
{
public const HEADER_CONTENT_TYPE = 'Content-Type';
public const HEADER_SET_COOKIE = 'Set-Cookie';
public const HEADER_PRAGMA = 'Pragma';
public const HEADER_EXPIRES = 'Expires';
public const HEADER_CACHE_CONTROL = 'Cache-Control';
public const HEADER_CONTENT_TRANSFER_ENCODING = 'Content-Transfer-Encoding';
public const HEADER_CONTENT_DISPOSITION = 'Content-Disposition';
public const HEADER_CONTENT_TYPE = 'Content-Type';
public const HEADER_SET_COOKIE = 'Set-Cookie';
public const HEADER_PRAGMA = 'Pragma';
public const HEADER_ACCEPT = 'Accept';
public const HEADER_EXPIRES = 'Expires';
public const HEADER_CACHE_CONTROL = 'Cache-Control';
public const HEADER_CONTENT_TRANSFER_ENCODING = 'Content-Transfer-Encoding';
public const HEADER_CONTENT_DISPOSITION = 'Content-Disposition';
public const HEADER_ORIGIN = 'Origin';
public const HEADER_ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin';
public const HEADER_ACCESS_CONTROL_MAX_AGE = 'Access-Control-Max-Age';
public const HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS = 'Access-Control-Allow-Credentials';
public const HEADER_ACCESS_CONTROL_ALLOW_METHODS = 'Access-Control-Allow-Methods';
public const HEADER_ACCESS_CONTROL_ALLOW_HEADERS = 'Access-Control-Allow-Headers';
}
88 changes: 49 additions & 39 deletions src/http-message/src/Cookie.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@

class Cookie
{
public const SAME_SITE_LAX = 'lax';
public const SAME_SITE_NONE = 'none';
public const SAME_SITE_STRICT = 'strict';

public function __construct(
protected string $name,
protected string $value,
Expand All @@ -30,6 +34,51 @@ public function __construct(
}
}

/**
* 解析Cookie字符串,返回对象
*/
public static function parse(string $str): Cookie
{
$parts = [
'expires' => 0,
'path' => '/',
'domain' => '',
'secure' => false,
'httponly' => false,
'samesite' => '',
];
foreach (explode(';', $str) as $part) {
if (! str_contains($part, '=')) {
$key = $part;
$value = true;
} else {
[$key, $value] = explode('=', trim($part), 2);
$value = trim($value);
}
switch ($key = trim(strtolower($key))) {
case 'max-age':
$parts['expires'] = time() + (int) $value;
break;
default:
if (array_key_exists($key, $parts)) {
$parts[$key] = $value;
} else {
$parts['name'] = $key;
$parts['value'] = $value;
}
}
}
return new static(
$parts['name'], $parts['value'],
(int) $parts['expires'], $parts['path'],
$parts['domain'], (bool) $parts['secure'],
(bool) $parts['httponly'], $parts['samesite']
);
}

/**
* 生成对应的Cookie字符串
*/
public function __toString(): string
{
$str = $this->name . '=';
Expand Down Expand Up @@ -104,45 +153,6 @@ public function getMaxAge(): int
return $this->expires !== 0 ? $this->expires - time() : 0;
}

public static function parse(string $str): Cookie
{
$parts = [
'expires' => 0,
'path' => '/',
'domain' => '',
'secure' => false,
'httponly' => false,
'samesite' => '',
];
foreach (explode(';', $str) as $part) {
if (! str_contains($part, '=')) {
$key = $part;
$value = true;
} else {
[$key, $value] = explode('=', trim($part), 2);
$value = trim($value);
}
switch ($key = trim(strtolower($key))) {
case 'max-age':
$parts['expires'] = time() + (int) $value;
break;
default:
if (array_key_exists($key, $parts)) {
$parts[$key] = $value;
} else {
$parts['name'] = $key;
$parts['value'] = $value;
}
}
}
return new static(
$parts['name'], $parts['value'],
(int) $parts['expires'], $parts['path'],
$parts['domain'], (bool) $parts['secure'],
(bool) $parts['httponly'], $parts['samesite']
);
}

public function getName(): string
{
return $this->name;
Expand Down
18 changes: 18 additions & 0 deletions src/http-server/src/Exception/CSRFException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

/**
* This file is part of MaxPHP.
*
* @link https://github.com/marxphp
* @license https://github.com/marxphp/max/blob/master/LICENSE
*/

namespace Max\Http\Server\Exception;

use Max\Http\Message\Exception\HttpException;

class CSRFException extends HttpException
{
}
65 changes: 50 additions & 15 deletions src/http-server/src/Middleware/AllowCrossDomain.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,41 +11,76 @@

namespace Max\Http\Server\Middleware;

use Max\Http\Message\Contract\HeaderInterface;
use Max\Http\Message\Contract\RequestMethodInterface;
use Max\Http\Message\Contract\StatusCodeInterface;
use Max\Http\Message\Response;
use Max\Utils\Str;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

use function Max\Utils\collect;

class AllowCrossDomain implements MiddlewareInterface
{
/** @var array 允许域,全部可以使用`*` */
protected array $allowOrigin = ['*'];

/** @var array 附加的响应头 */
protected array $addedHeaders = [
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => 1800,
'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With',
HeaderInterface::HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS => 'true',
HeaderInterface::HEADER_ACCESS_CONTROL_MAX_AGE => 1800,
HeaderInterface::HEADER_ACCESS_CONTROL_ALLOW_METHODS => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
HeaderInterface::HEADER_ACCESS_CONTROL_ALLOW_HEADERS => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With',
];

public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$allowOrigin = in_array('*', $this->allowOrigin) ? '*' : $request->getHeaderLine('Origin');
if ($allowOrigin !== '') {
$headers = $this->addedHeaders;
$headers['Access-Control-Allow-Origin'] = $allowOrigin;
if (strcasecmp($request->getMethod(), 'OPTIONS') === 0) {
return new Response(204, $headers);
}
$response = $handler->handle($request);
foreach ($headers as $name => $header) {
$response = $response->withHeader($name, $header);
if ($this->shouldCrossOrigin($origin = $request->getHeaderLine(HeaderInterface::HEADER_ORIGIN))) {
$headers = $this->createCORSHeaders($origin);
if (strcasecmp($request->getMethod(), RequestMethodInterface::METHOD_OPTIONS) === 0) {
return new Response(StatusCodeInterface::STATUS_NO_CONTENT, $headers);
}
return $response;

return $this->addHeadersToResponse($handler->handle($request), $headers);
}

return $handler->handle($request);
}

/**
* 创建响应头部
*/
protected function createCORSHeaders(string $origin): array
{
$headers = $this->addedHeaders;
$headers[HeaderInterface::HEADER_ACCESS_CONTROL_ALLOW_ORIGIN] = $origin;
return $headers;
}

/**
* 将头部添加到响应
*/
protected function addHeadersToResponse(ResponseInterface $response, array $headers): ResponseInterface
{
foreach ($headers as $name => $header) {
$response = $response->withHeader($name, $header);
}
return $response;
}

/**
* 允许跨域
*/
protected function shouldCrossOrigin(string $origin)
{
if (empty($origin)) {
return false;
}
return collect($this->allowOrigin)->first(function($allowOrigin) use ($origin) {
return Str::is($allowOrigin, $origin);
});
}
}
6 changes: 4 additions & 2 deletions src/http-server/src/Middleware/ExceptionHandleMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace Max\Http\Server\Middleware;

use Max\Http\Message\Contract\HeaderInterface;
use Max\Http\Message\Contract\StatusCodeInterface;
use Max\Http\Message\Exception\HttpException;
use Max\Http\Message\Response;
use Psr\Http\Message\ResponseInterface;
Expand Down Expand Up @@ -49,7 +51,7 @@ protected function renderException(Throwable $throwable, ServerRequestInterface
{
$message = $throwable->getMessage();
$statusCode = $this->getStatusCode($throwable);
if (str_contains($request->getHeaderLine('Accept'), 'application/json')
if (str_contains($request->getHeaderLine(HeaderInterface::HEADER_ACCEPT), 'application/json')
|| strcasecmp('XMLHttpRequest', $request->getHeaderLine('X-REQUESTED-WITH')) === 0) {
return new Response($statusCode, [], json_encode([
'status' => false,
Expand All @@ -68,6 +70,6 @@ protected function renderException(Throwable $throwable, ServerRequestInterface

protected function getStatusCode(Throwable $throwable)
{
return $throwable instanceof HttpException ? $throwable->getCode() : 500;
return $throwable instanceof HttpException ? $throwable->getCode() : StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR;
}
}
34 changes: 19 additions & 15 deletions src/http-server/src/Middleware/SessionMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,28 +27,23 @@ class SessionMiddleware implements MiddlewareInterface
* Cookie 过期时间【+9小时,实际1小时后过期,和时区有关】.
*/
protected int $expires = 9 * 3600;

protected string $name = 'MAXPHP_SESSION_ID';

protected bool $httponly = true;

protected string $path = '/';

protected string $domain = '';

protected bool $secure = true;

/**
* @var mixed|SessionHandlerInterface
* 会话Cookie名
*/
protected string $name = 'MAXPHP_SESSION_ID';
protected bool $httponly = true;
protected string $path = '/';
protected string $domain = '';
protected bool $secure = true;
protected string $sameSite = Cookie::SAME_SITE_LAX;
protected SessionHandlerInterface $handler;

public function __construct(ConfigInterface $config)
{
$config = $config->get('session');
$handler = $config['handler'];
$options = $config['options'];
$this->handler = new $handler($options);
$config = $config['config'];
$this->handler = new $handler($config);
}

public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
Expand All @@ -59,7 +54,16 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
$response = $handler->handle($request);
$session->save();
$session->close();
$cookie = new Cookie($this->name, $session->getId(), time() + $this->expires, $this->path, $this->domain, $this->secure, $this->httponly);

return $this->addCookieToResponse($response, $this->name, $session->getId());
}

/**
* 将cookie添加到响应
*/
protected function addCookieToResponse(ResponseInterface $response, string $name, string $value): ResponseInterface
{
$cookie = new Cookie($name, $value, time() + $this->expires, $this->path, $this->domain, $this->secure, $this->httponly, $this->sameSite);

return $response->withAddedHeader(HeaderInterface::HEADER_SET_COOKIE, $cookie->__toString());
}
Expand Down
Loading