mirror of
https://github.com/fastapiadmin/FastapiAdmin.git
synced 2026-09-23 05:10:57 +00:00
style: 统一代码风格和格式 docs: 完善函数和方法的文档字符串 refactor(base_model): 移除冗余的表名和表参数生成方法 refactor(constant): 更新返回码注释格式 refactor(router_class): 添加路由处理器的详细文档 refactor(database): 完善数据库连接函数的文档 refactor(security): 添加认证类和方法的详细文档 refactor(validator): 更新验证器函数的文档格式 refactor(serialize): 优化序列化工具类的文档 refactor(response): 完善响应类的文档字符串 refactor(dependencies): 添加依赖函数的详细文档 refactor(initialize): 完善初始化脚本的文档 refactor(plugin): 添加生命周期和中间件注册的文档 refactor(service): 完善服务层方法的文档 refactor(controller): 添加控制器方法的详细文档 refactor(crud): 完善CRUD操作的文档字符串 refactor(schema): 简化模型类并移除冗余字段 refactor(param): 更新查询参数类的注释格式 refactor(template): 优化代码生成模板的格式 refactor(console): 添加控制台输出功能的实现 refactor(util): 完善工具函数的文档字符串
121 lines
3.9 KiB
Python
121 lines
3.9 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
|
|
|
|
|
|
class OnlineService:
|
|
"""在线用户管理模块服务层"""
|
|
|
|
@classmethod
|
|
async def get_online_list_service(cls, redis: Redis, search: Optional[OnlineQueryParam] = None) -> List[Dict]:
|
|
"""
|
|
获取在线用户列表信息(支持分页和搜索)
|
|
|
|
参数:
|
|
- redis (Redis): Redis异步客户端实例。
|
|
- search (Optional[OnlineQueryParam]): 查询参数模型。
|
|
|
|
返回:
|
|
- 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:
|
|
"""
|
|
强制下线指定在线用户
|
|
|
|
参数:
|
|
- redis (Redis): Redis异步客户端实例。
|
|
- session_id (str): 在线用户会话ID。
|
|
|
|
返回:
|
|
- bool: 如果操作成功则返回True,否则返回False。
|
|
"""
|
|
# 删除 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:
|
|
"""
|
|
强制下线所有在线用户
|
|
|
|
参数:
|
|
- redis (Redis): Redis异步客户端实例。
|
|
|
|
返回:
|
|
- bool: 如果操作成功则返回True,否则返回False。
|
|
"""
|
|
# 删除 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:
|
|
"""
|
|
检查是否匹配搜索条件
|
|
|
|
参数:
|
|
- online_info (Dict): 在线用户信息字典。
|
|
- search (Optional[OnlineQueryParam]): 查询参数模型。
|
|
|
|
返回:
|
|
- bool: 如果匹配则返回True,否则返回False。
|
|
"""
|
|
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
|