Commit bc275f33 authored by 谢宇轩's avatar 谢宇轩

feat: 重构授权中间件的模块

parent d6599b7d
<?php
// generated code, do not edit.
declare(strict_types=1);
namespace Jiwei\Test\SDK\Endpoint;
use Closure;
use Jiwei\EasyHttpSdk\Application;
use Jiwei\EasyHttpSdk\Exception\SdkException;
use Jiwei\EasyHttpSdk\Exception\ApplicationException;
use Jiwei\EasyHttpSdk\Exception\TimeOutExcetpion;
use Jiwei\EasyHttpSdk\Helper\ArgsRecorder;
use Jiwei\EasyHttpSdk\Helper\CallBackHelper;
use Jiwei\EasyHttpSdk\Http\SdkRequest;
class Test
{
use ArgsRecorder;
use CallBackHelper;
/** @var Application */
protected $application;
/**
* @param Application $application
*/
public function __construct(
Application $application
)
{
$this->application = $application;
}
/**
* 创建表单
*
* @param array|null $body
*
* @param Closure|null $catch
* @param Closure|null $then
* @return array
*
* @throws ApplicationException
* @throws SdkException
* @throws TimeOutExcetpion
*/
public function create(?array $body = [], ?Closure $catch = null, ?Closure $then = null): mixed
{
$url = "/api/form";
$request = new SdkRequest("POST", $url, "Test", "create", [], json_encode($body));
$request = $request->withArgs($this->ArgsRecoder(__METHOD__, func_get_args()))->withRequestID()->withAuthorization();
try {
$response = $this->application->sendRequest($request);
$decodedData = $this->application->resultDecode($request, $response);
$this->setLastResult($decodedData);
} catch (SdkException $sdkException) {
$this->setLastException($sdkException);
$catch = $catch ?? $this->defaultFailedCallBack();
return $catch($this);
}
$then = $then ?? $this->defaultSuccessCallBack();
return $then($this);
}
}
# Easy Http SDK
## 使用
### 安装
```shell
composer require jiwei/easy-http-sdk
```
### 配置`Option`
使用 `./vendor/bin/easysdk-option -p XXX` 来进行生成Option类
详情可使用 `-h` 来查看其他参数
```PHP
class XXXOption extends Option
{
/** @var string API鉴权地址 */
private const AUTH_API_ROUTE = "/api/access/token";
/** @var int API鉴权过期时间 */
const AUTH_CACHE_EXPIRES_AT = 2400;
/** @var string 实现了AuthMiddlewareInterface 的鉴权中间件(可以不指定默认使用 JWT Breare Token的方式) */
const AUTH_MIDDLEWARE = AuthMiddlewareInterface::class;
/** @var array<string, string> API HOST */
const ENDPOINT_HOSTS = [
"local" => "127.0.0.1:9094",
"development" => "47.112.148.159:8981",
"production" => "127.0.0.1:9900",
];
/**
* 鉴权模式 需要自行实现
*
* @return Closure
*/
public function authorization(): Closure
{
return function (Client $client): string {
// 借客户端一用
$request = new Request('post', self::AUTH_API_ROUTE, [], json_encode([
"app_key" => $this->getAppId(),
"app_secret" => $this->getAppSecret()
]));
$response = $client->send($request);
if ($response->getStatusCode() >= 400) {
throw new InvalidArgumentException("invalid account.");
}
$rpcResult = json_decode($response->getBody()->getContents(), true);
if (json_last_error()) {
throw new InvalidArgumentException("invalid auth response");
}
$token = $rpcResult["token"] ?? "";
if ($token === "") {
throw new InvalidArgumentException("invalid account.");
}
return $token;
};
}
/**
* 结果处理策略,默认使用 DefaultErrorHandlingPolicy
*
* @return HandlingPolicyInterface
*/
public function handlingPolicy(): HandlingPolicyInterface
{
return new ForFormHandlingPolicy();
}
}
```
### 2. 配置 `Endpoint`
首先创建一个`endpoint`文件夹,编写`Endponit.toml`配置文件
```toml
[all]
description = "搜索XXX"
endpoint = "/api/xxx"
method = "GET"
query = [# 对应query参数,生成代码后为非必填参数
"search",
"limit",
"page"
]
cache = true # 使用 ETAG 中间件
auth = true
[Edit]
description = "修改XXX"
endpoint = "/api/xxx/{id}" # $id对应路由中的参数,生成代码后为必填参数
method = "PUT"
auth = true # 使用鉴权中间件
body = true # 使用 HTTP 请求 Body Json序列化后传递数组参数
```
然后使用 `./vendor/bin/easysdk -p "XXX\SDK" -v 8.1` 来进行生成SDK的Endpoint类
可以使用 `./vendor/bin/easysdk -h` 来查看其他参数的使用帮助。
### 愉快的使用
然后就可以愉快的使用了🎣
......@@ -179,7 +179,8 @@ class Application implements ClientInterface
throw new ApplicationException($exception->getMessage(), $request, [], $exception);
}
}
$stack->push(new JwtMiddleware($this->jwtToken));
$authMiddleware = $this->option->getAuthorizationMiddleware();
$stack->push($authMiddleware($this->jwtToken));
}
}
......
<?php
declare(strict_types=1);
namespace Jiwei\EasyHttpSdk\Middleware\Auth;
use Jiwei\EasyHttpSdk\Middleware\MiddlewareInterface;
interface AuthMiddlewareInterface extends MiddlewareInterface
{
/**
* @param string $token
*/
public function __construct(string $token = "");
}
<?php
declare(strict_types=1);
namespace Jiwei\EasyHttpSdk\Middleware;
namespace Jiwei\EasyHttpSdk\Middleware\Auth;
use Psr\Http\Message\RequestInterface;
class JwtMiddleware implements MiddlewareInterface
class JwtMiddleware implements AuthMiddlewareInterface
{
/** @var string jwtToken */
protected $token;
public function __construct(string $token){
public function __construct(string $token = ""){
$this->token = $token;
}
......
......@@ -4,19 +4,27 @@ declare(strict_types=1);
namespace Jiwei\EasyHttpSdk;
use Closure;
use Jiwei\EasyHttpSdk\Middleware\Auth\AuthMiddlewareInterface;
use Jiwei\EasyHttpSdk\Middleware\Auth\JwtMiddleware;
use Jiwei\EasyHttpSdk\Policy\DefaultErrorHandlingPolicy;
use Jiwei\EasyHttpSdk\Policy\HandlingPolicyInterface;
use RuntimeException;
abstract class Option
{
/** @var array<string, string> Api Host */
const ENDPOINT_HOSTS = [
'local' => '',
'development' => '',
'production' => ''
];
/** @var int 授权缓存时间 */
const AUTH_CACHE_EXPIRES_AT = 30000;
/** @var string AuthMiddlewareInterface 鉴权中间件 */
const AUTH_MIDDLEWARE = JwtMiddleware::class;
/** @var string App Key 应用标志 */
private $appId;
/** @var string App Secret 应用密钥 */
......@@ -37,10 +45,10 @@ abstract class Option
* 错误处理策略
* @return HandlingPolicyInterface
*/
public function handlingPolicy(): HandlingPolicyInterface
{
return new DefaultErrorHandlingPolicy();
}
public function handlingPolicy(): HandlingPolicyInterface
{
return new DefaultErrorHandlingPolicy();
}
/**
* @param string $appId
......@@ -149,4 +157,19 @@ abstract class Option
{
return $this->debug;
}
/**
* @return string
*/
public function getAuthorizationMiddleware(): string
{
$authorizationMiddleware = empty(static::AUTH_MIDDLEWARE) ? self::AUTH_MIDDLEWARE : static::AUTH_MIDDLEWARE;
if (!class_exists($authorizationMiddleware)) {
throw new RuntimeException("Auth Middleware is not exist");
}
if (!(new $authorizationMiddleware) instanceof AuthMiddlewareInterface) {
throw new RuntimeException("Auth Middleware is not implements AuthMiddlewareInterface");
}
return $authorizationMiddleware;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment