feat: api秘钥只能访问api接口,access token只能访问内部接口
This commit is contained in:
@@ -10,6 +10,7 @@ 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.CrpyUtils import TokenInfo, CryptUtils
|
||||
from app.utils.api_secret_utils import api_secret_utils, ApiSecretStatus
|
||||
from app.utils.db_utils import async_session
|
||||
|
||||
@@ -49,9 +50,20 @@ def add_app_middlewares(app: FastAPI):
|
||||
if oauth_header and oauth_header.startswith("Bearer "):
|
||||
token = oauth_header.split(" ")[1].strip()
|
||||
|
||||
# 没有得到token信息,直接返回错误
|
||||
if not token:
|
||||
raise unauthorized_exception
|
||||
|
||||
# 从token秘钥中解析token信息
|
||||
try:
|
||||
token_info: TokenInfo = CryptUtils.get_token_info(token)
|
||||
# 既不是access token,也不是api token,直接返回错误信息
|
||||
if token_info.get('type') != 'access' and token_info.get('type') != 'api':
|
||||
raise unauthorized_exception
|
||||
except InvalidTokenError:
|
||||
raise unauthorized_exception
|
||||
|
||||
# 根据token信息获取用户信息
|
||||
async with async_session() as session:
|
||||
try:
|
||||
public_user = await get_current_user(session, token)
|
||||
@@ -63,6 +75,9 @@ def add_app_middlewares(app: FastAPI):
|
||||
# 如果请求的是api接口
|
||||
# api开头的接口需要额外验证秘钥
|
||||
if request.url.path.startswith("/api/"):
|
||||
# /api/开头的接口,只能使用 api token 访问
|
||||
if token_info.get('type') != "api":
|
||||
raise unauthorized_exception
|
||||
# 验证秘钥状态
|
||||
secret_status = await api_secret_utils.verify_secret(token)
|
||||
print("secret_status", secret_status)
|
||||
@@ -83,7 +98,10 @@ def add_app_middlewares(app: FastAPI):
|
||||
else:
|
||||
# 秘钥有效
|
||||
pass
|
||||
|
||||
else:
|
||||
# 非/api/接口,智能使用 access token 访问
|
||||
if token_info.get('type') != "access":
|
||||
raise unauthorized_exception
|
||||
response = await call_next(request)
|
||||
return response
|
||||
|
||||
|
||||
Reference in New Issue
Block a user