feat: add api key authentication

This commit is contained in:
QiuSW
2026-07-02 17:40:26 +08:00
parent e34b4c65f8
commit 47e6aed7a8
11 changed files with 224 additions and 17 deletions
+22
View File
@@ -550,3 +550,25 @@
- 阻塞:无。远程 MySQL 仍可能偶发链路超时;后续测试不要并行跑共享同一 `test_cmhub` 的数据库测试,必要时用 `--keepdb` 串行重跑。
- 决策:T-204 的 P2-2 已补齐单次完整测试全绿证据;并发扣点测试仍必须在 MySQL 上跑,SQLite 不可作为验收依据。
- 下一步:领取 T-301 API Key 鉴权(DRF Authentication)。
## 2026-07-02 T-301 API Key 鉴权(DRF Authentication)
- 状态:DONE
- 变更:
- 新增 `apps/api/authentication.py`:实现 `ApiKeyAuthentication`,只解析 `Authorization: Bearer <API_KEY>`;对明文 Key 做 SHA-256 hash 后查 `ApiKey`,成功后返回 `(user, api_key)`,并更新 `last_used_at`。
- 新增 `apps/api/errors.py`:提供统一错误响应结构 `{"error":{"code":...,"message":...}}`。
- 更新 `apps/api/views.py`:新增 `ExternalApiView`,外部 API 只挂 `ApiKeyAuthentication + IsAuthenticated`,缺失/无效 Key 返回 `401 unauthorized`,不接受 Web session。
- 更新 `apps/api/tests.py`:覆盖有效 Bearer Key、缺失 Key、无效 Key、错误鉴权 scheme、Key revoked、User disabled、Web session 不被外部 API 接受。
- 同步更新 `README.md`、`docs/00-ai-start-here.md`、`docs/04-architecture.md`、`docs/api.md`、`docs/06-tasks.md`、`docs/current-state.md`:T-301 完成,下一步 T-302。
- 验证:
- `./init.ps1`:开工前通过;完成后再次通过。
- `py -3.12 -m py_compile apps\api\authentication.py apps\api\errors.py apps\api\views.py apps\api\tests.py`:通过。
- `py -3.12 manage.py check`:通过,0 issues。
- `py -3.12 manage.py test apps.api --noinput --keepdb --verbosity 2`:通过,8 tests OK。
- `py -3.12 manage.py makemigrations --check`:通过,No changes detected。
- `py -3.12 -m compileall apps config`:通过。
- `git diff --check`:通过,仅 Windows CRLF 提示。
- `py -3.12 manage.py test --noinput --keepdb --verbosity 2`:通过,52 tests OK,耗时 54.905s。
- 阻塞:无。
- 决策:生成/余额等对外 API 后续统一继承 `ExternalApiView`;充值下单/状态查询仍按用户端 session 流程另行实现,不使用该外部 API 基类。
- 下一步:领取 T-302 生成标题 / 图片接口。