fourcal-pms/backend/app/api/audit.py

203 lines
8.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""审计查询:操作日志与登录日志。
日志由 :mod:`app.service.audit` 中间件负责写,这里只负责让人查得动:按人、按动作、
按对象、按时间窗,失败的操作单列。审计页的存在本身就是这套机制的一半——记了没人看
的日志等于没记。
口径上有两条要说清楚:
* 审计不做数据权限过滤。它是"谁动了系统"的账,按 ``system:audit:view`` 这一个权限码
放行;给它套项目数据范围,等于让被审计的人自己决定别人能看到他什么。
* 明细里的请求体是脱敏后存的(口令/令牌/验证码在写入时就被抹成 ``***``),
上传类请求只留字节数,不留内容。
"""
from __future__ import annotations
import json
from datetime import datetime, timedelta
from typing import Any
from fastapi import APIRouter, Query
from sqlalchemy import func, or_, select
from ..deps import DbSession, PrincipalOf
from ..envelope import forbidden, not_found, ok, page
from ..models import LoginLog, OperationLog
from ..service.audit import action_label
router = APIRouter(prefix="/system", tags=["audit"])
#: 一次最多翻多少天。审计表只增不删,不设上限的话一个全表扫能把库拖住。
MAX_WINDOW_DAYS = 366
def _need(current: PrincipalOf) -> None:
if not current.permission.can("system:audit:view"):
raise forbidden("缺少权限:system:audit:view")
def _detail(row: OperationLog) -> dict[str, Any]:
if not row.detail_json:
return {}
try:
parsed = json.loads(row.detail_json)
except ValueError:
return {"_raw": row.detail_json[:2000]}
return parsed if isinstance(parsed, dict) else {"_raw": parsed}
def _window(days: int, from_date: str, to_date: str) -> tuple[datetime, datetime | None]:
def parse(value: str) -> datetime | None:
try:
return datetime.fromisoformat(value.strip()[:10])
except ValueError:
return None
start = parse(from_date) or (datetime.now() - timedelta(days=max(1, min(days, MAX_WINDOW_DAYS))))
end = parse(to_date)
if end:
end = end + timedelta(days=1) # 闭区间:填 2026-10-13 要把 13 号整天算进来
return start, end
@router.get("/operation-logs")
def operation_logs(
db: DbSession,
current: PrincipalOf,
keyword: str = "",
accountName: str = "",
action: str = "",
objectType: str = "",
days: int = Query(30, ge=1, le=MAX_WINDOW_DAYS),
fromDate: str = "",
toDate: str = "",
onlyFailures: bool = False,
pageNo: int = Query(1, ge=1),
pageSize: int = Query(20, ge=1, le=200),
) -> dict[str, Any]:
_need(current)
start, end = _window(days, fromDate, toDate)
statement = select(OperationLog).where(OperationLog.created_at >= start)
if end:
statement = statement.where(OperationLog.created_at < end)
if accountName:
statement = statement.where(OperationLog.account_name.like(f"%{accountName.strip()}%"))
if action:
statement = statement.where(OperationLog.action == action)
if objectType:
statement = statement.where(OperationLog.object_type == objectType)
if keyword:
like = f"%{keyword.strip()}%"
statement = statement.where(or_(
OperationLog.object_name.like(like), OperationLog.object_id.like(like),
OperationLog.account_name.like(like), OperationLog.detail_json.like(like),
))
total = db.execute(select(func.count()).select_from(statement.subquery())).scalar() or 0
rows = db.execute(statement.order_by(OperationLog.id.desc())
.offset((pageNo - 1) * pageSize).limit(pageSize)).scalars().all()
items = []
for row in rows:
detail = _detail(row)
error = detail.get("error") if isinstance(detail.get("error"), dict) else {}
items.append({
"id": row.id,
"accountName": row.account_name,
"action": row.action,
"actionLabel": action_label(row.action),
"objectType": row.object_type,
"objectId": row.object_id,
"objectName": row.object_name,
"ip": row.ip,
"createdAt": row.created_at.isoformat(sep=" ", timespec="seconds") if row.created_at else "",
"method": detail.get("method", ""),
"path": detail.get("path", ""),
"status": detail.get("status", 0),
"ok": bool(detail.get("ok", True)),
"durationMs": detail.get("durationMs", 0),
"errorCode": error.get("code", ""),
"errorMessage": error.get("message", ""),
"traceId": error.get("traceId", ""),
})
result = page(items, total, pageNo, pageSize)
result["data"]["window"] = {
"from": start.isoformat(timespec="seconds"),
"to": end.isoformat(timespec="seconds") if end else "",
}
return result
@router.get("/operation-logs/options")
def operation_log_options(db: DbSession, current: PrincipalOf,
days: int = Query(90, ge=1, le=MAX_WINDOW_DAYS)) -> dict[str, Any]:
"""筛选下拉的取值:只用这段时间里真出现过的动作与对象,不摆一长串用不上的选项。"""
_need(current)
start = datetime.now() - timedelta(days=days)
actions = db.execute(
select(OperationLog.action, func.count(OperationLog.id))
.where(OperationLog.created_at >= start)
.group_by(OperationLog.action).order_by(func.count(OperationLog.id).desc())
).all()
objects = db.execute(
select(OperationLog.object_type, func.count(OperationLog.id))
.where(OperationLog.created_at >= start, OperationLog.object_type != "")
.group_by(OperationLog.object_type).order_by(func.count(OperationLog.id).desc())
).all()
return ok({
"actions": [{"value": value, "label": action_label(value), "count": count}
for value, count in actions],
"objectTypes": [{"value": value or "", "label": value or "未标注", "count": count}
for value, count in objects],
})
@router.get("/operation-logs/{log_id}")
def operation_log_detail(log_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
"""单条明细:把脱敏后的请求体、参数、错误与业务补充原样给出。"""
_need(current)
row = db.get(OperationLog, log_id)
if row is None:
raise not_found("没有这条操作日志")
detail = _detail(row)
return ok({
"id": row.id, "accountId": row.account_id, "accountName": row.account_name,
"action": row.action, "actionLabel": action_label(row.action),
"objectType": row.object_type, "objectId": row.object_id, "objectName": row.object_name,
"ip": row.ip,
"createdAt": row.created_at.isoformat(sep=" ", timespec="seconds") if row.created_at else "",
"detail": detail,
})
@router.get("/login-logs")
def login_logs(
db: DbSession,
current: PrincipalOf,
keyword: str = "",
onlyFailed: bool = False,
days: int = Query(30, ge=1, le=MAX_WINDOW_DAYS),
pageNo: int = Query(1, ge=1),
pageSize: int = Query(20, ge=1, le=200),
) -> dict[str, Any]:
"""登录审计。审计"谁进过系统"这件事靠 ``login_log``,操作日志管的是进来之后改了什么。"""
_need(current)
start = datetime.now() - timedelta(days=days)
statement = select(LoginLog).where(LoginLog.created_at >= start)
if onlyFailed:
statement = statement.where(LoginLog.success.is_(False))
if keyword:
like = f"%{keyword.strip()}%"
statement = statement.where(or_(LoginLog.account.like(like), LoginLog.ip.like(like),
LoginLog.reason.like(like)))
total = db.execute(select(func.count()).select_from(statement.subquery())).scalar() or 0
rows = db.execute(statement.order_by(LoginLog.id.desc())
.offset((pageNo - 1) * pageSize).limit(pageSize)).scalars().all()
return page([{
"id": row.id, "account": row.account, "success": bool(row.success), "reason": row.reason,
"ip": row.ip, "userAgent": row.user_agent, "mode": row.mode,
"createdAt": row.created_at.isoformat(sep=" ", timespec="seconds") if row.created_at else "",
} for row in rows], total, pageNo, pageSize)