audit_log.py
2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""操作审计日志查询路由(超管/授权可见)。"""
import json
from fastapi import APIRouter, Depends, Query
from sqlalchemy import func, select
from src.database.models import WikiOaOperLog, WikiOaUser
from src.database.session import AsyncSessionLocal
from src.services.oa.deps import require_perm
router = APIRouter()
@router.get("/oa/oper-logs", dependencies=[Depends(require_perm("oa:log:list"))])
async def list_oper_logs(
module: str = Query(default=""),
keyword: str = Query(default=""),
limit: int = Query(default=20, ge=1, le=200),
offset: int = Query(default=0, ge=0),
):
"""操作日志列表:按模块/关键字筛选 + 分页,倒序。"""
async with AsyncSessionLocal() as session:
stmt = select(WikiOaOperLog)
count_stmt = select(func.count()).select_from(WikiOaOperLog)
if module.strip():
stmt = stmt.where(WikiOaOperLog.module == module.strip())
count_stmt = count_stmt.where(WikiOaOperLog.module == module.strip())
if keyword.strip():
pat = f"%{keyword.strip()}%"
cond = (
WikiOaOperLog.operator_name.like(pat)
| WikiOaOperLog.target_name.like(pat)
| WikiOaOperLog.action.like(pat)
)
stmt = stmt.where(cond)
count_stmt = count_stmt.where(cond)
total = (await session.execute(count_stmt)).scalar() or 0
rows = (
await session.execute(
stmt.order_by(WikiOaOperLog.created_at.desc()).limit(limit).offset(offset)
)
).scalars().all()
items = [
{
"id": r.id,
"operatorName": r.operator_name,
"module": r.module,
"action": r.action,
"targetType": r.target_type,
"targetName": r.target_name,
"detail": _safe_json(r.detail),
"clientIp": r.client_ip,
"result": r.result,
"createdAt": r.created_at.isoformat() if r.created_at else None,
}
for r in rows
]
return {"success": True, "total": total, "items": items}
def _safe_json(s: str | None):
if not s:
return None
try:
return json.loads(s)
except Exception:
return s