Files
video/encryption/encrypt_decorator.py
2025-09-15 18:08:54 +08:00

39 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from functools import wraps
from fastapi import HTTPException
from schema.response_schema import APIResponse
from encryption.encryption import AESCipher
def encrypt_response(func):
"""
返回值加密装饰器:
- 仅对 APIResponse 的 data 字段加密code/message 不加密,便于前端判断基础状态)
- 若 data 为 None如注册接口不加密
"""
@wraps(func) # 保留原函数元信息(如 __name__、__doc__避免 FastAPI 路由异常)
async def wrapper(*args, **kwargs):
try:
# 1. 执行原接口函数获取返回值APIResponse 对象)
response: APIResponse = await func(*args, **kwargs)
# 2. 仅当 data 不为 None 时加密
if response.data is not None:
# 加密 data 字段(字典类型)
encrypted_result = AESCipher.encrypt(response.data)
# 替换原 data 为加密后的数据(包含密文和 IV
response.data = {
"is_encrypted": True, # 标记是否加密,便于前端处理
**encrypted_result
}
return response
except Exception as e:
# 加密过程异常时,返回 500 错误
raise HTTPException(
status_code=500,
detail=f"返回值加密失败:{str(e)}"
) from e
return wrapper