旧库升级期全链路兼容:登录/权限降级与待升级提示
1. 权限解析降级:数据库无 permission_groups/group_id 时按旧 role_type 使用内置预置权限,保证登录、会话同步、升级弹窗可用(升级后自动切真实权限组) 2. 管理员列表/角色查询降级;权限组列表降级为只读占位 3. 管理员/权限组/邮箱写操作在旧库返回明确的待升级提示;create_admin 不传邮箱不写 email 列 4. 全局异常对缺表/缺列错误返回待升级提示
This commit is contained in:
1 parent
6c8fd2b432
commit
8cd2c83412
7 files changed
+273
-79
No files matched your search
@@ -11,6 +11,10 @@
|
||||
|
||||
from typing import Optional, Dict, Any, List
|
||||
from utils.database import execute_one, execute_query, execute_insert, execute_update
|
||||
from utils.logger import get_logger
|
||||
from models.permission_group import apply_legacy_group_fields
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class AdminRoleModel:
|
||||
@@ -30,7 +34,19 @@ class AdminRoleModel:
|
||||
WHERE ar.user_id = %s
|
||||
LIMIT 1
|
||||
"""
|
||||
return await execute_one(sql, (user_id,))
|
||||
try:
|
||||
return await execute_one(sql, (user_id,))
|
||||
except Exception as e:
|
||||
# 数据库尚未升级(缺少 group_id / permission_groups)时按旧角色降级
|
||||
logger.warning(f"读取管理员角色失败,按旧角色降级(数据库可能待升级): {e}")
|
||||
legacy_sql = """
|
||||
SELECT ar.*, s.subject_name
|
||||
FROM admin_roles ar
|
||||
LEFT JOIN subjects s ON ar.subject_id = s.subject_id
|
||||
WHERE ar.user_id = %s
|
||||
LIMIT 1
|
||||
"""
|
||||
return apply_legacy_group_fields(await execute_one(legacy_sql, (user_id,)))
|
||||
|
||||
@staticmethod
|
||||
async def get_all() -> List[Dict[str, Any]]:
|
||||
@@ -45,7 +61,20 @@ class AdminRoleModel:
|
||||
LEFT JOIN permission_groups pg ON ar.group_id = pg.group_id
|
||||
ORDER BY COALESCE(pg.is_locked, 0) DESC, COALESCE(pg.is_system, 0) DESC, ar.user_id
|
||||
"""
|
||||
return await execute_query(sql)
|
||||
try:
|
||||
return await execute_query(sql)
|
||||
except Exception as e:
|
||||
# 数据库尚未升级(缺少 group_id / permission_groups / users.email)时降级
|
||||
logger.warning(f"读取管理员列表失败,按旧角色降级(数据库可能待升级): {e}")
|
||||
legacy_sql = """
|
||||
SELECT ar.*, u.real_name, u.username, u.status, s.subject_name
|
||||
FROM admin_roles ar
|
||||
JOIN users u ON ar.user_id = u.user_id
|
||||
LEFT JOIN subjects s ON ar.subject_id = s.subject_id
|
||||
ORDER BY ar.user_id
|
||||
"""
|
||||
rows = await execute_query(legacy_sql)
|
||||
return [apply_legacy_group_fields(row) for row in rows]
|
||||
|
||||
@staticmethod
|
||||
async def create(
|
||||
|
||||
@@ -35,6 +35,66 @@ PERMISSION_KEYS = [
|
||||
"manage_upgrade", # 系统升级
|
||||
]
|
||||
|
||||
# 预置权限组默认配置(数据库尚未升级时按旧角色降级使用,与 sql/init.sql 种子一致)
|
||||
DEFAULT_GROUP_PERMISSIONS = {
|
||||
"班主任": {key: True for key in PERMISSION_KEYS},
|
||||
"班长": {"manage_conduct": True, "revoke_any": True, "view_all_records": True},
|
||||
"学习委员": {"manage_conduct": True, "manage_homework": True, "manage_subjects": True},
|
||||
"考勤委员": {"manage_conduct": True, "manage_attendance": True, "revoke_own": True},
|
||||
"劳动委员": {"manage_conduct": True},
|
||||
"志愿委员": {"manage_conduct": True, "view_all_records": True},
|
||||
}
|
||||
|
||||
DEFAULT_GROUP_CAPS = {
|
||||
"班主任": (True, None, True, None),
|
||||
"班长": (True, 5, True, 5),
|
||||
"学习委员": (True, 5, True, 5),
|
||||
"考勤委员": (False, None, True, 8),
|
||||
"劳动委员": (True, 1, True, 1),
|
||||
"志愿委员": (True, 5, False, None),
|
||||
}
|
||||
|
||||
|
||||
def build_legacy_group(role_type: Optional[str]) -> Optional[Dict[str, Any]]:
|
||||
"""数据库未升级时,按旧角色名构建内置权限组(仅用于过渡期)"""
|
||||
if not role_type:
|
||||
return None
|
||||
base_permissions = DEFAULT_GROUP_PERMISSIONS.get(role_type, {})
|
||||
can_add, max_add, can_subtract, max_subtract = DEFAULT_GROUP_CAPS.get(
|
||||
role_type, (False, None, False, None)
|
||||
)
|
||||
return {
|
||||
"group_id": None,
|
||||
"group_name": role_type,
|
||||
"role_type": role_type,
|
||||
"description": "内置权限(数据库待升级)",
|
||||
"permissions_data": {key: bool(base_permissions.get(key, False)) for key in PERMISSION_KEYS},
|
||||
"can_add_points": can_add,
|
||||
"max_add_points": max_add,
|
||||
"can_subtract_points": can_subtract,
|
||||
"max_subtract_points": max_subtract,
|
||||
"is_system": 1 if role_type in DEFAULT_GROUP_PERMISSIONS else 0,
|
||||
"is_locked": 1 if role_type == "班主任" else 0,
|
||||
}
|
||||
|
||||
|
||||
def apply_legacy_group_fields(row: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
||||
"""为旧库查询结果补充内置权限组展示字段(不覆盖已有真实权限组字段)"""
|
||||
if not row:
|
||||
return row
|
||||
group = build_legacy_group(row.get("role_type"))
|
||||
if not group:
|
||||
return row
|
||||
row.setdefault("email", None)
|
||||
row["group_name"] = row.get("group_name") or group["group_name"]
|
||||
row["is_system"] = group["is_system"]
|
||||
row["is_locked"] = group["is_locked"]
|
||||
row["can_add_points"] = group["can_add_points"]
|
||||
row["max_add_points"] = group["max_add_points"]
|
||||
row["can_subtract_points"] = group["can_subtract_points"]
|
||||
row["max_subtract_points"] = group["max_subtract_points"]
|
||||
return row
|
||||
|
||||
|
||||
class PermissionGroupModel:
|
||||
"""权限组数据模型"""
|
||||
@@ -81,14 +141,25 @@ class PermissionGroupModel:
|
||||
|
||||
@staticmethod
|
||||
async def get_all() -> List[Dict[str, Any]]:
|
||||
rows = await execute_query(
|
||||
"""
|
||||
SELECT pg.*, (SELECT COUNT(*) FROM admin_roles ar WHERE ar.group_id = pg.group_id) AS member_count
|
||||
FROM permission_groups pg
|
||||
ORDER BY pg.is_locked DESC, pg.is_system DESC, pg.group_id ASC
|
||||
"""
|
||||
)
|
||||
return [PermissionGroupModel.parse_group(row) for row in rows]
|
||||
try:
|
||||
rows = await execute_query(
|
||||
"""
|
||||
SELECT pg.*, (SELECT COUNT(*) FROM admin_roles ar WHERE ar.group_id = pg.group_id) AS member_count
|
||||
FROM permission_groups pg
|
||||
ORDER BY pg.is_locked DESC, pg.is_system DESC, pg.group_id ASC
|
||||
"""
|
||||
)
|
||||
return [PermissionGroupModel.parse_group(row) for row in rows]
|
||||
except Exception as e:
|
||||
# 数据库尚未升级:返回内置预置组(只读占位),升级后自动切换真实权限组
|
||||
logger.warning(f"读取权限组列表失败,返回内置预置组(数据库可能待升级): {e}")
|
||||
fallback_groups = []
|
||||
for group_name in DEFAULT_GROUP_PERMISSIONS:
|
||||
group = build_legacy_group(group_name)
|
||||
group["is_locked"] = 1 # 待升级期间只读,避免误操作
|
||||
group["member_count"] = 0
|
||||
fallback_groups.append(group)
|
||||
return fallback_groups
|
||||
|
||||
@staticmethod
|
||||
async def create(
|
||||
@@ -155,7 +226,7 @@ class PermissionGroupModel:
|
||||
|
||||
@staticmethod
|
||||
async def get_by_user_id(user_id: int) -> Optional[Dict[str, Any]]:
|
||||
"""获取用户绑定权限组(兼容仅有 role_type 的旧数据)"""
|
||||
"""获取用户绑定权限组(兼容仅有 role_type 的旧数据/未升级数据库)"""
|
||||
sql = """
|
||||
SELECT ar.role_type,
|
||||
pg.group_id, pg.group_name, pg.description, pg.permissions,
|
||||
@@ -167,7 +238,20 @@ class PermissionGroupModel:
|
||||
WHERE ar.user_id = %s
|
||||
LIMIT 1
|
||||
"""
|
||||
row = await execute_one(sql, (user_id,))
|
||||
try:
|
||||
row = await execute_one(sql, (user_id,))
|
||||
except Exception as e:
|
||||
# 数据库尚未升级(缺少 admin_roles.group_id / permission_groups)时按旧角色降级
|
||||
logger.warning(f"读取权限组失败,按旧角色降级(数据库可能待升级): {e}")
|
||||
try:
|
||||
legacy = await execute_one(
|
||||
"SELECT role_type FROM admin_roles WHERE user_id = %s LIMIT 1",
|
||||
(user_id,)
|
||||
)
|
||||
except Exception as legacy_error:
|
||||
logger.error(f"读取旧角色失败: {legacy_error}")
|
||||
return None
|
||||
return build_legacy_group(legacy.get("role_type") if legacy else None)
|
||||
if not row:
|
||||
return None
|
||||
if not row.get("group_id") and row.get("role_type"):
|
||||
|
||||
+10
-4
@@ -70,13 +70,19 @@ class UserModel:
|
||||
|
||||
@staticmethod
|
||||
async def create_admin(username: str, password: str, real_name: str, email: str = None) -> int:
|
||||
"""创建管理员账号"""
|
||||
"""创建管理员账号(不传邮箱时不写 email 列)"""
|
||||
password_hash = security.bcrypt_password(password)
|
||||
if email:
|
||||
sql = """
|
||||
INSERT INTO users (username, password_hash, real_name, email, user_type, need_change_password)
|
||||
VALUES (%s, %s, %s, %s, 'admin', 1)
|
||||
"""
|
||||
return await execute_insert(sql, (username, password_hash, real_name, email))
|
||||
sql = """
|
||||
INSERT INTO users (username, password_hash, real_name, email, user_type, need_change_password)
|
||||
VALUES (%s, %s, %s, %s, 'admin', 1)
|
||||
INSERT INTO users (username, password_hash, real_name, user_type, need_change_password)
|
||||
VALUES (%s, %s, %s, 'admin', 1)
|
||||
"""
|
||||
return await execute_insert(sql, (username, password_hash, real_name, email))
|
||||
return await execute_insert(sql, (username, password_hash, real_name))
|
||||
|
||||
@staticmethod
|
||||
async def update_password(user_id: int, new_password: str) -> bool:
|
||||
|
||||
Reference in new issue
Block a user