mirror of
https://github.com/fastapiadmin/FastapiAdmin.git
synced 2026-09-28 06:57:54 +00:00
- 将 ApplicationQueryParams 改为 ApplicationQueryParam - 同步更新相关导入和函数参数类型注解 - 修改 PaginationQueryParams 为 PaginationQueryParam refactor(demo): 重命名查询参数类以统一命名风格 - 将 DemoQueryParams 改为 DemoQueryParam - 同步更新相关导入和函数参数类型注解 - 修改 PaginationQueryParams 为 PaginationQueryParam refactor(gencode): 优化代码生成模块的模型和服务层结构 - 统一模型名称后缀为 Schema,调整相关引用 - 规范 Pydantic schema 的命名和定义 - 删除无用的 Python DAO 模板文件 - 调整导入路径,统一使用 app 目录下的模块路径 - 改进服务层方法签名,添加返回类型注解 - 使用自定义异常 CustomException 替代旧异常 - 统一成功响应格式为 SuccessResponse - 优化代码生成服务中的数据库操作 DAO 调用参数传递 - 优化代码生成业务表和字段模型的字段定义,添加注释和默认值 - 优化生成代码路径处理逻辑和异常信息提示 - 整合分页查询参数定义,统一分页模型 - 修正多个服务方法的参数类型和返回类型 - 删除无用的导入和多余注释,提升代码整洁度
88 lines
3.1 KiB
Python
88 lines
3.1 KiB
Python
# -*- coding: utf-8 -*-
|
|
|
|
import json
|
|
from typing import Dict, List, Optional
|
|
from redis.asyncio.client import Redis
|
|
|
|
from app.common.enums import RedisInitKeyConfig
|
|
from app.core.redis_crud import RedisCURD
|
|
from app.core.security import decode_access_token
|
|
from app.core.logger import logger
|
|
from .param import OnlineQueryParam
|
|
from .schema import OnlineOutSchema
|
|
|
|
class OnlineService:
|
|
"""在线用户管理模块服务层"""
|
|
|
|
@classmethod
|
|
async def get_online_list_service(cls, redis: Redis, search: Optional[OnlineQueryParam] = None) -> List[Dict]:
|
|
"""
|
|
获取在线用户列表信息(支持分页和搜索)
|
|
"""
|
|
|
|
keys = await RedisCURD(redis).get_keys(f"{RedisInitKeyConfig.ACCESS_TOKEN.key}:*")
|
|
tokens = await RedisCURD(redis).mget(*keys)
|
|
|
|
online_users = []
|
|
for token in tokens:
|
|
if not token:
|
|
continue
|
|
try:
|
|
payload = decode_access_token(token=token)
|
|
session_info = json.loads(payload.sub)
|
|
if cls._match_search_conditions(session_info, search):
|
|
online_users.append(session_info)
|
|
except Exception as e:
|
|
logger.error(f"解析在线用户数据失败: {e}")
|
|
continue
|
|
# 按照 login_time 倒序排序
|
|
online_users.sort(key=lambda x: x.get('login_time', ''), reverse=True)
|
|
|
|
return online_users
|
|
|
|
|
|
@classmethod
|
|
async def delete_online_service(cls, redis: Redis, session_id: str) -> bool:
|
|
"""强制下线在线用户"""
|
|
# 删除 token
|
|
await RedisCURD(redis).delete(f"{RedisInitKeyConfig.ACCESS_TOKEN.key}:{session_id}")
|
|
await RedisCURD(redis).delete(f"{RedisInitKeyConfig.REFRESH_TOKEN.key}:{session_id}")
|
|
|
|
|
|
logger.info(f"强制下线用户会话: {session_id}")
|
|
return True
|
|
|
|
@classmethod
|
|
async def clear_online_service(cls, redis: Redis) -> bool:
|
|
"""强制下线在线用户"""
|
|
# 删除 token
|
|
await RedisCURD(redis).clear(f"{RedisInitKeyConfig.ACCESS_TOKEN.key}:*")
|
|
await RedisCURD(redis).clear(f"{RedisInitKeyConfig.REFRESH_TOKEN.key}:*")
|
|
|
|
logger.info(f"清除所有在线用户会话成功")
|
|
return True
|
|
|
|
|
|
@staticmethod
|
|
def _match_search_conditions(online_info: Dict, search: Optional[OnlineQueryParam]) -> bool:
|
|
"""检查是否匹配搜索条件"""
|
|
if not search:
|
|
return True
|
|
|
|
if search.name and search.name[1]:
|
|
keyword = search.name[1].strip('%')
|
|
if keyword.lower() not in online_info.get("name", "").lower():
|
|
return False
|
|
|
|
if search.ipaddr and search.ipaddr[1]:
|
|
keyword = search.ipaddr[1].strip('%')
|
|
if keyword not in online_info.get("ipaddr", ""):
|
|
return False
|
|
|
|
if search.login_location and search.login_location[1]:
|
|
keyword = search.login_location[1].strip('%')
|
|
if keyword.lower() not in online_info.get("login_location", "").lower():
|
|
return False
|
|
|
|
return True
|