From d28a0142095a09337bea1a57562e2a14706894dc Mon Sep 17 00:00:00 2001 From: Nick Zeng Date: Thu, 2 Apr 2026 14:41:31 +0800 Subject: [PATCH] update api key --- backend/app/Middleware/AuthMiddleware.php | 7 +++++++ backend/app/Model/ApiKey.php | 1 - .../test/Cases/Integration/Auth/ApiKeyGlobalSwitchTest.php | 6 ++++-- backend/test/Cases/Unit/Model/ApiKeyTest.php | 5 +++-- 4 files changed, 14 insertions(+), 5 deletions(-) diff --git a/backend/app/Middleware/AuthMiddleware.php b/backend/app/Middleware/AuthMiddleware.php index ff846d5..03b8f12 100644 --- a/backend/app/Middleware/AuthMiddleware.php +++ b/backend/app/Middleware/AuthMiddleware.php @@ -94,6 +94,13 @@ class AuthMiddleware implements MiddlewareInterface ])->withStatus(401); } + if (!$api_key->enabled) { + return $this->response->json([ + 'code' => 403, + 'message' => '该 API Key 已被禁用', + ])->withStatus(403); + } + $user = $api_key->user; if (!$user || $user->status !== 1) { diff --git a/backend/app/Model/ApiKey.php b/backend/app/Model/ApiKey.php index 97becf1..10c87c4 100644 --- a/backend/app/Model/ApiKey.php +++ b/backend/app/Model/ApiKey.php @@ -86,7 +86,6 @@ class ApiKey extends Model return static::query() ->where('key_hash', $hash) - ->where('enabled', true) ->where(function ($query): void { $query->whereNull('expires_at') ->orWhere('expires_at', '>', \Carbon\Carbon::now()); diff --git a/backend/test/Cases/Integration/Auth/ApiKeyGlobalSwitchTest.php b/backend/test/Cases/Integration/Auth/ApiKeyGlobalSwitchTest.php index ec52811..5f12623 100644 --- a/backend/test/Cases/Integration/Auth/ApiKeyGlobalSwitchTest.php +++ b/backend/test/Cases/Integration/Auth/ApiKeyGlobalSwitchTest.php @@ -101,8 +101,10 @@ class ApiKeyGlobalSwitchTest extends TestCase 'X-API-Key' => $result['plain_key'], ]); - // ApiKey::findByPlainKey() 查询条件包含 enabled=true,所以禁用的 Key 返回 401(无效 Key) - $response->assertStatus(401); + // 禁用的 Key 返回 403(已被禁用),区别于无效/过期 Key 的 401 + $response->assertStatus(403); + $body = json_decode($response->getBody()->getContents(), true); + $this->assertStringContainsString('已被禁用', $body['message']); $user->forceDelete(); } diff --git a/backend/test/Cases/Unit/Model/ApiKeyTest.php b/backend/test/Cases/Unit/Model/ApiKeyTest.php index 083ccc4..da09263 100644 --- a/backend/test/Cases/Unit/Model/ApiKeyTest.php +++ b/backend/test/Cases/Unit/Model/ApiKeyTest.php @@ -102,7 +102,7 @@ class ApiKeyTest extends TestCase }); } - public function test_find_by_plain_key_excludes_disabled_key(): void + public function test_find_by_plain_key_returns_disabled_key(): void { $this->runInCoroutine(function (): void { $user = $this->createTestUser(); @@ -112,7 +112,8 @@ class ApiKeyTest extends TestCase $result['api_key']->save(); $found = ApiKey::findByPlainKey($result['plain_key']); - $this->assertNull($found); + $this->assertNotNull($found); + $this->assertFalse($found->enabled); }); }