table_game/backend/app/services/admin_group_service.py
2025-03-10 08:35:19 +08:00

60 lines
1.9 KiB
Python

from fastapi import HTTPException
from ..db import get_connection
from ..utils.jwt_handler import verify_token
def _verify_admin_permission(token: str):
"""公共权限验证方法"""
try:
payload = verify_token(token)
username = payload["sub"]
except ValueError as e:
raise HTTPException(status_code=401, detail=str(e))
connection = get_connection()
try:
cursor = connection.cursor(dictionary=True)
cursor.execute("SELECT user_type FROM users WHERE username = %s;", (username,))
admin_user = cursor.fetchone()
if not admin_user or admin_user["user_type"] != "admin":
raise HTTPException(status_code=403, detail="Permission denied")
return username
finally:
cursor.close()
connection.close()
def list_groups_service(token: str) -> list:
"""获取所有游戏群组服务"""
_verify_admin_permission(token)
connection = get_connection()
cursor = connection.cursor(dictionary=True)
try:
cursor.execute("""
SELECT gg.*, u.username AS leader_name
FROM game_groups gg
LEFT JOIN users u ON gg.user_id = u.user_id
""")
return cursor.fetchall()
finally:
cursor.close()
connection.close()
def delete_group_service(token: str, group_id: int) -> dict:
"""删除群组服务"""
_verify_admin_permission(token)
connection = get_connection()
cursor = connection.cursor()
try:
# 先删除关联的成员
cursor.execute("DELETE FROM group_members WHERE group_id = %s", (group_id,))
# 再删除群组
cursor.execute("DELETE FROM game_groups WHERE group_id = %s", (group_id,))
connection.commit()
return {"message": "删除成功"}
except Exception as e:
connection.rollback()
raise HTTPException(500, str(e))
finally:
cursor.close()
connection.close()