Commit 6741f885 authored by 谢宇轩's avatar 谢宇轩

refactor: 调整鉴权回调的使用方式

parent 09bd415a
...@@ -100,6 +100,34 @@ class Application implements ClientInterface ...@@ -100,6 +100,34 @@ class Application implements ClientInterface
]); ]);
} }
/**
* 从缓存中获取accessToken 使用PSR-6缓存接口
*
* @return string
* @throws CacheInvalidArgumentException
* @throws TransferException
* @throws RuntimeException
* @throws InvalidArgumentException
*/
private function getAccessTokenFromCache(): string
{
// 过期时间为0时不使用缓存
if ($this->option->getAuthExpires() == 0) {
return $this->option->authorization()($this->client);
}
$cacheKey = sprintf(self::TOKEN_CACHE_KEY, $this->option->getAppId());
$currentToken = $this->cache->getItem($cacheKey);
if (!$currentToken->isHit()) {
$token = $this->option->authorization()($this->client);
$currentToken->set($token)->expiresAfter($this->option->getAuthExpires());
$this->cache->save($currentToken);
}
return $currentToken->get();
}
/** /**
* 发送SDK的请求 * 发送SDK的请求
* *
...@@ -133,15 +161,20 @@ class Application implements ClientInterface ...@@ -133,15 +161,20 @@ class Application implements ClientInterface
if ($request->authorization()) { if ($request->authorization()) {
if ($this->jwtToken === "") { if ($this->jwtToken === "") {
try { try {
$this->jwtToken = $this->getAccessTokenFromCache($this->option->getAppId(), $this->option->getAppSecret()); $this->jwtToken = $this->getAccessTokenFromCache();
} catch (RuntimeException $exception) { } catch (CacheInvalidArgumentException $exception) {
// 缓存异常
throw new ApplicationException("auth cache error " . $exception->getMessage());
} catch (TransferException $exception) {
// 超时异常
if ($this->logger) { if ($this->logger) {
$this->logger->error("sdk error, bad Auth with: " . $exception->getMessage()); $this->logger->error("sdk error, authorization timeout.");
} }
throw new TimeOutExcetpion($request); throw new TimeOutExcetpion($request);
} catch (InvalidArgumentException $exception) { } catch (RuntimeException|InvalidArgumentException $exception) {
// 参数异常
if ($this->logger) { if ($this->logger) {
$this->logger->error("sdk error, bad Auth with:" . $exception->getMessage()); $this->logger->error("sdk error, cause by:" . $exception->getMessage());
} }
throw new ApplicationException($exception->getMessage(), $request, [], $exception); throw new ApplicationException($exception->getMessage(), $request, [], $exception);
} }
...@@ -265,69 +298,4 @@ class Application implements ClientInterface ...@@ -265,69 +298,4 @@ class Application implements ClientInterface
{ {
return $this->lastRequestContext; return $this->lastRequestContext;
} }
/**
* 从缓存中获取accessToken 使用PSR-6缓存接口
*
* @param string $app_key
* @param string $app_secret
* @return string
*/
private function getAccessTokenFromCache(string $app_key, string $app_secret): string
{
$cacheKey = sprintf(self::TOKEN_CACHE_KEY, $app_key);
try {
$currentToken = $this->cache->getItem($cacheKey);
} catch (CacheInvalidArgumentException $e) {
throw new InvalidArgumentException("cache use invalid args" . $e->getMessage());
}
if (!$currentToken->isHit()) {
$token = $this->getAccessToken($app_key, $app_secret);
$currentToken->set($token)->expiresAfter($this->option->getAuthExpires());
$this->cache->save($currentToken);
}
return $currentToken->get();
}
/**
* 鉴权
*
* @param string $app_key
* @param string $app_secret
* @return string
*/
private function getAccessToken(string $app_key, string $app_secret): string
{
try {
$request = $this->option->authorization()($app_key, $app_secret);
$response = $this->client->send($request);
} catch (TransferException $exception) {
throw new RuntimeException('time out!');
} catch (GuzzleException $exception) {
if ($this->logger) {
$this->logger->error("sdk error, Auth error");
}
throw new InvalidArgumentException("auth error." . $exception->getMessage());
}
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["access_token"] ?? "";
if ($token === "") {
throw new InvalidArgumentException("invalid account.");
}
return $token;
}
} }
...@@ -31,12 +31,26 @@ class {{ Name }}Option extends Option ...@@ -31,12 +31,26 @@ class {{ Name }}Option extends Option
public function authorization(): \Closure public function authorization(): \Closure
{ {
return function (string $appId, string $appSecret): Request { return function (string $appId, string $appSecret): Request {
return new Request('post', self::AUTH_API_ROUTE, [ $request = new Request('post', self::AUTH_API_ROUTE, [], json_encode([
"body" => json_encode([ "app_key" => $this->getAppId(),
"app_key" => $appId, "app_secret" => $this->getAppSecret()
"app_secret" => $appSecret ]));
]) $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;
}; };
} }
......
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