70 lines
2.2 KiB
Python
70 lines
2.2 KiB
Python
|
|
"""操作审计日志工具:记录关键业务操作。"""
|
|||
|
|
from flask import request
|
|||
|
|
from insurance.db.compat import db
|
|||
|
|
from insurance.models.operation_log import SystemOperationLog
|
|||
|
|
|
|||
|
|
|
|||
|
|
def log_operation(user_id: str, action: str, target_type: str = "",
|
|||
|
|
target_id: str = "", detail: dict = None):
|
|||
|
|
"""写入一条操作日志。
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
user_id: 操作人 ID
|
|||
|
|
action: 操作类型(login/logout/create/update/delete/export/share 等)
|
|||
|
|
target_type: 操作对象类型(user/proposal/document/datasource 等)
|
|||
|
|
target_id: 操作对象 ID
|
|||
|
|
detail: 附加信息
|
|||
|
|
"""
|
|||
|
|
try:
|
|||
|
|
log = SystemOperationLog(
|
|||
|
|
user_id=str(user_id),
|
|||
|
|
action=action,
|
|||
|
|
target_type=target_type,
|
|||
|
|
target_id=str(target_id),
|
|||
|
|
detail=detail or {},
|
|||
|
|
ip=request.remote_addr if request else "",
|
|||
|
|
user_agent=str(request.user_agent)[:256] if request else "",
|
|||
|
|
)
|
|||
|
|
db.session.add(log)
|
|||
|
|
db.session.commit()
|
|||
|
|
except Exception:
|
|||
|
|
db.session.rollback()
|
|||
|
|
|
|||
|
|
|
|||
|
|
def log_config_change(user_id: str, target_type: str, target_id: str,
|
|||
|
|
old_value: dict = None, new_value: dict = None):
|
|||
|
|
"""记录配置变更日志(含变更前后值)。
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
user_id: 操作人 ID
|
|||
|
|
target_type: 配置类型(prompt/template/llm_config/notification 等)
|
|||
|
|
target_id: 配置ID
|
|||
|
|
old_value: 变更前的值
|
|||
|
|
new_value: 变更后的值
|
|||
|
|
"""
|
|||
|
|
detail = {
|
|||
|
|
"old_value": old_value or {},
|
|||
|
|
"new_value": new_value or {},
|
|||
|
|
"changes": _get_changes(old_value or {}, new_value or {}),
|
|||
|
|
}
|
|||
|
|
log_operation(user_id, "update", target_type, target_id, detail)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _get_changes(old: dict, new: dict) -> list:
|
|||
|
|
"""比较两个字典,返回变更列表。"""
|
|||
|
|
changes = []
|
|||
|
|
all_keys = set(list(old.keys()) + list(new.keys()))
|
|||
|
|
|
|||
|
|
for key in all_keys:
|
|||
|
|
old_val = old.get(key)
|
|||
|
|
new_val = new.get(key)
|
|||
|
|
|
|||
|
|
if old_val != new_val:
|
|||
|
|
changes.append({
|
|||
|
|
"field": key,
|
|||
|
|
"old": old_val,
|
|||
|
|
"new": new_val,
|
|||
|
|
})
|
|||
|
|
|
|||
|
|
return changes
|