feat: 秘钥凭证管理
This commit is contained in:
@@ -9,6 +9,8 @@ from starlette.responses import JSONResponse
|
||||
|
||||
from app.config.env import env
|
||||
from app.controller.add_user_route import unauthorized_exception, get_current_user
|
||||
from app.model.ApiSecretModel import ApiSecretService
|
||||
from app.utils.api_secret_utils import api_secret_utils, ApiSecretStatus
|
||||
from app.utils.db_utils import async_session
|
||||
|
||||
|
||||
@@ -58,6 +60,30 @@ def add_app_middlewares(app: FastAPI):
|
||||
except InvalidTokenError:
|
||||
raise unauthorized_exception
|
||||
|
||||
# 如果请求的是api接口
|
||||
# api开头的接口需要额外验证秘钥
|
||||
if request.url.path.startswith("/api/"):
|
||||
# 验证秘钥状态
|
||||
secret_status = await api_secret_utils.verify_secret(token)
|
||||
print("secret_status", secret_status)
|
||||
if secret_status == ApiSecretStatus.invalid:
|
||||
# 秘钥无效
|
||||
raise unauthorized_exception
|
||||
elif secret_status == ApiSecretStatus.not_exist:
|
||||
# 秘钥没有缓存
|
||||
async with async_session() as session:
|
||||
query_cls = await ApiSecretService.query_item(session, {"secret": token})
|
||||
if query_cls:
|
||||
# 秘钥存在
|
||||
await api_secret_utils.save_secret(token, ApiSecretStatus.valid)
|
||||
else:
|
||||
# 秘钥不存在
|
||||
await api_secret_utils.save_secret(token, ApiSecretStatus.invalid)
|
||||
raise unauthorized_exception
|
||||
else:
|
||||
# 秘钥有效
|
||||
pass
|
||||
|
||||
response = await call_next(request)
|
||||
return response
|
||||
|
||||
|
||||
Reference in New Issue
Block a user