Files
FastapiAdmin/backend/app/api/v1/module_system/log/service.py
T
zhangtao cf88ab8897 refactor: 整合仪表盘功能到监控模块,清理冗余代码
- 移除原监控仪表盘独立模块,将相关功能合并到在线监控模块
- 重构租户配置字段名,统一使用logo_url和name替代tenant_logo/tenant_name
- 优化搜索工具函数,移除重复导入
- 调整参数配置模型字段长度限制,移除config_value的max_length约束
- 清理冗余的常量定义和导入语句
- 修复批量状态设置接口的redis依赖注入
- 增强OAuth登录安全性,添加租户默认归属和state一次性消费
- 优化资源目录缓存逻辑,减少重复计算
- 新增API Token模块基础框架
- 完善用户token版本管理,支持主动失效JWT
- 调整AI模型配置缓存过期时间
- 修复菜单类型字段索引,提升查询性能
- 简化前端刷新token调用逻辑
- 新增滑块验证完成接口和忘记密码验证码校验
- 调整系统配置默认值,添加操作日志保留天数和接口白名单配置
- 限制Mock支付回调仅在开发环境可用
- 重构websocket认证方式,支持更安全的subprotocol传参
2026-07-13 01:14:20 +08:00

120 lines
4.3 KiB
Python

from datetime import datetime, timedelta
from typing import Any
from sqlalchemy import delete
from sqlalchemy.ext.asyncio import AsyncSession
from app.config.setting import settings
from app.core.base_schema import AuthSchema, PageResultSchema
from app.core.database import async_db_session
from app.core.exceptions import CustomException
from app.core.logger import logger
from app.utils.common_util import search_to_dict
from .crud import LoginLogCRUD, OperationLogCRUD
from .schema import (
LoginLogDetailOutSchema,
LoginLogOutSchema,
LoginLogQueryParam,
OperationLogDetailOutSchema,
OperationLogOutSchema,
OperationLogQueryParam,
)
class LoginLogService:
"""登录日志管理服务"""
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
self.auth = auth
self.db = db
async def detail(self, id: int) -> LoginLogDetailOutSchema:
obj = await LoginLogCRUD(self.auth, self.db).get_or_404(id=id)
return LoginLogDetailOutSchema.model_validate(obj)
async def page(
self,
page_no: int,
page_size: int,
search: LoginLogQueryParam | None = None,
order_by: list[dict[str, str]] | None = None,
) -> PageResultSchema[LoginLogOutSchema]:
return await LoginLogCRUD(self.auth, self.db).page(
offset=(page_no - 1) * page_size,
limit=page_size,
order_by=order_by or [{"updated_time": "desc"}],
search=search_to_dict(search),
out_schema=LoginLogOutSchema,
)
async def delete(self, ids: list[int]) -> None:
if not ids:
raise CustomException(msg="删除失败,删除对象不能为空")
existing = await LoginLogCRUD(self.auth, self.db).get_list(search={"id": ("in", ids)})
existing_map = {obj.id for obj in existing}
for nid in ids:
if nid not in existing_map:
raise CustomException(msg=f"删除失败,ID为{nid}的数据不存在")
await LoginLogCRUD(self.auth, self.db).delete(ids=ids)
class OperationLogService:
"""操作日志管理服务"""
def __init__(self, auth: AuthSchema, db: AsyncSession) -> None:
self.auth = auth
self.db = db
@staticmethod
async def cleanup_operation_log() -> bool:
from .model import LoginLogModel, OperationLogModel
retention_days = settings.OPERATION_LOG_RETENTION_DAYS
cutoff = datetime.now() - timedelta(days=retention_days)
async with async_db_session() as session:
op_stmt = delete(OperationLogModel).where(OperationLogModel.created_time < cutoff)
op_result: Any = await session.execute(op_stmt)
login_stmt = delete(LoginLogModel).where(LoginLogModel.created_time < cutoff)
login_result: Any = await session.execute(login_stmt)
await session.commit()
logger.info(f"操作日志清理完成: 操作日志 {op_result.rowcount} 条, 登录日志 {login_result.rowcount} 条")
return True
async def page(
self,
page_no: int,
page_size: int,
search: OperationLogQueryParam | None = None,
order_by: list[dict[str, str]] | None = None,
) -> PageResultSchema[OperationLogOutSchema]:
crud = OperationLogCRUD(self.auth, self.db)
return await crud.page(
offset=(page_no - 1) * page_size,
limit=page_size,
order_by=order_by or [{"id": "desc"}],
search=search_to_dict(search),
out_schema=OperationLogOutSchema,
)
async def detail(self, id: int) -> OperationLogDetailOutSchema:
crud = OperationLogCRUD(self.auth, self.db)
obj = await crud.get_or_404(id=id)
return OperationLogDetailOutSchema.model_validate(obj)
async def delete(self, ids: list[int]) -> None:
if not ids:
raise CustomException(msg="删除失败,删除对象不能为空")
existing = await OperationLogCRUD(self.auth, self.db).get_list(search={"id": ("in", ids)})
existing_map = {obj.id for obj in existing}
for nid in ids:
if nid not in existing_map:
raise CustomException(msg="删除失败,该数据不存在")
crud = OperationLogCRUD(self.auth, self.db)
await crud.delete(ids=ids)