audit_log.py 2.3 KB
"""操作审计日志查询路由(超管/授权可见)。"""
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