- 新增 SQLite 数据库层(db.py)持久化命令监听配置,支持热更新无需重启 - 命令过滤从白名单扩展为黑白名单双模式(COMMAND_LIST_MODE: allow/deny) - 新增后台管理页面 /admin/,侧边栏布局,支持在线修改所有命令监听配置 - 新增 REST API:GET/PUT /api/settings、POST /api/settings/reload - 新增 rebuild_pattern() 支持配置变更后正则动态重编译 - 中间件放行 /admin 和 /api 路径免鉴权 - 添加 aiosqlite 依赖
38 lines
1.2 KiB
Python
38 lines
1.2 KiB
Python
"""鉴权中间件:校验请求中的 API Key。"""
|
||
|
||
import uuid
|
||
|
||
from aiohttp import web
|
||
|
||
from .config import WEBHOOK_API_KEY
|
||
from .response import error
|
||
|
||
|
||
@web.middleware
|
||
async def auth_middleware(request: web.Request, handler):
|
||
"""对需要鉴权的路径校验 API Key。/healthz 和 /admin/ 及 /api/ 开头的路径不需要鉴权。"""
|
||
# 不需要鉴权的路径
|
||
if request.path == "/healthz" or request.path.startswith("/admin") or request.path.startswith("/api/"):
|
||
return await handler(request)
|
||
|
||
auth_header = request.headers.get("Authorization", "")
|
||
if auth_header.startswith("Bearer "):
|
||
key = auth_header[len("Bearer "):]
|
||
else:
|
||
key = request.headers.get("X-API-Key", "")
|
||
|
||
if key != WEBHOOK_API_KEY:
|
||
return error("unauthorized", code=401, status=401)
|
||
|
||
return await handler(request)
|
||
|
||
|
||
@web.middleware
|
||
async def request_id_middleware(request: web.Request, handler):
|
||
"""为每个请求附加唯一 request_id,便于日志追踪。"""
|
||
request_id = request.headers.get("X-Request-ID", uuid.uuid4().hex[:12])
|
||
request["request_id"] = request_id
|
||
response = await handler(request)
|
||
response.headers["X-Request-ID"] = request_id
|
||
return response
|