Files
ClassManager/backend/services/auth_service.py
T
canglan 1068bc6def v4.2 科目管理优化与多项修复清理
1. 科目管理:代码长度放宽至50(含数据库升级v4.2)、编辑可清空代码、重命名查重、新增 ↑↓ 快捷排序(批量重排接口)、空代码不再显示占位
2. 修复单人加减分提交空名单:showSinglePointsModal 三处重复定义收口到 points-mgmt 并共享选中状态
3. SMTP:SMTP_FROM 默认取 SMTP_USER、SMTP_ENABLED 兼容 1/yes/on、启动日志打印邮件状态、新增邮件测试接口与按钮(返回真实 SMTP 错误)
4. 密码:加密改为 bcrypt 库直连(修复 passlib 兼容问题)、重置密码不再依赖影响行数、前端统一展示422校验错误
5. 冗余清理:删除未用导入/Schema/函数、死文件 admin.js 与 sanitize.py、重复 escapeHtml、重复CSS、重复脚本加载
6. 修复11个文件被写入的 UTF-8 BOM
7. 文档与版本同步至4.2
2026-09-20 20:35:13 +08:00

473 lines
22 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# ===========================================
# 班级操行分管理系统 - 后端服务
#
# 开发者: Canglan
# 联系方式: admin@sea-studio.top
# 版权归属: Sea Network Technology Studio
# 许可证: MIT License
#
# 版权所有 © Sea Network Technology Studio
# ===========================================
from typing import Dict, Any, Optional
from html import escape as html_escape
import secrets
from config import settings
from models.user import UserModel
from models.student import StudentModel
from middleware.permission import PermissionChecker
from services.log_service import LogService
from utils.security import security
from utils.validators import is_valid_email
from utils.email_sender import EmailSender
from utils.jwt_handler import jwt_handler
from utils.redis_client import RedisClient
from utils.logger import get_logger
logger = get_logger(__name__)
def _build_group_info(group: Dict[str, Any]) -> Dict[str, Any]:
"""构建权限组摘要信息(用于登录响应与Session)"""
return {
"group_id": group.get("group_id"),
"group_name": group.get("group_name") or group.get("role_type"),
"max_add_points": group.get("max_add_points"),
"max_subtract_points": group.get("max_subtract_points"),
"can_add_points": bool(group.get("can_add_points")),
"can_subtract_points": bool(group.get("can_subtract_points")),
"is_locked": bool(group.get("is_locked"))
}
class AuthService:
"""认证服务"""
@staticmethod
async def login(username: str, password: str, ip: str, user_agent: str = None) -> Dict[str, Any]:
"""
用户登录
"""
# 检查登录失败次数
attempts = await RedisClient.get(f"login_attempts:{username}")
if attempts and int(attempts) >= 5:
await LogService.write_login_log(username, 0, ip, user_agent, "登录失败次数过多")
return {"success": False, "message": "登录失败次数过多,请5分钟后重试"}
# 获取用户信息
user = await UserModel.get_by_username(username)
if not user:
await RedisClient.set_login_attempts(username)
await LogService.write_login_log(username, 0, ip, user_agent, "用户名或密码错误")
return {"success": False, "message": "用户名或密码错误"}
# 验证密码
is_valid, needs_upgrade = security.verify_password_v2(password, user["password_hash"])
if not is_valid:
await RedisClient.set_login_attempts(username)
await LogService.write_login_log(username, 0, ip, user_agent, "用户名或密码错误")
return {"success": False, "message": "用户名或密码错误"}
# 自动升级旧哈希密码
if needs_upgrade:
try:
await UserModel.update_password(user["user_id"], password)
except Exception:
pass
# 检查账号状态
if user["status"] != 1:
await LogService.write_login_log(username, 0, ip, user_agent, "账号已被禁用")
return {"success": False, "message": "账号已被禁用"}
# 清除登录失败记录
await RedisClient.clear_login_attempts(username)
# 更新最后登录信息
await UserModel.update_last_login(user["user_id"], ip)
# 获取用户角色与权限(如果是管理员)
role = None
permissions = {}
group_info = None
if user["user_type"] == "admin":
group = await PermissionChecker.get_user_group(user["user_id"])
if group:
role = group.get("group_name") or group.get("role_type")
permissions = group.get("permissions_data", {})
group_info = _build_group_info(group)
# 生成Token
token = jwt_handler.create_token(
user_id=user["user_id"],
username=user["username"],
user_type=user["user_type"],
student_id=user["student_id"],
role=role,
real_name=user["real_name"]
)
# 存储Token到Redis
await RedisClient.set_user_token(user["user_id"], token)
# 确定跳转路径
redirect = AuthService._get_redirect_path(user["user_type"], role)
await LogService.write_login_log(username, 1, ip, user_agent)
return {
"success": True,
"token": token,
"user_id": user["user_id"],
"username": user["username"],
"real_name": user["real_name"],
"user_type": user["user_type"],
"student_id": user["student_id"],
"role": role,
"permissions": permissions,
"group": group_info,
"need_change_password": user["need_change_password"] == 1,
"redirect": redirect
}
@staticmethod
async def logout(user_id: int) -> Dict[str, Any]:
"""用户登出"""
await RedisClient.delete_user_token(user_id)
return {"success": True, "message": "登出成功"}
@staticmethod
async def change_password(user_id: int, old_password: str, new_password: str, force: bool = False) -> Dict[str, Any]:
"""修改密码"""
# 获取用户信息
user = await UserModel.get_by_user_id(user_id)
if not user:
return {"success": False, "message": "用户不存在"}
# 验证原密码
# force=True 仅在 need_change_password=1 时允许(首次登录强制改密)
# 其他情况必须验证旧密码
if force and user.get("need_change_password") == 1:
# 首次登录强制改密,跳过旧密码验证
pass
else:
# 正常改密,必须验证旧密码
if not old_password:
return {"success": False, "message": "请输入原密码"}
is_valid, _ = security.verify_password_v2(old_password, user["password_hash"])
if not is_valid:
return {"success": False, "message": "原密码错误"}
# 验证新密码强度
is_valid, msg = security.validate_password_strength(new_password)
if not is_valid:
return {"success": False, "message": msg}
# 更新密码
result = await UserModel.update_password(user_id, new_password)
if result:
# 清除所有Token
await RedisClient.delete_user_token(user_id)
return {"success": True, "message": "密码修改成功"}
else:
return {"success": False, "message": "密码修改失败"}
@staticmethod
async def get_user_info(user_id: int) -> Optional[Dict[str, Any]]:
"""获取用户信息"""
user = await UserModel.get_by_user_id(user_id)
if not user:
return None
result = {
"user_id": user["user_id"],
"username": user["username"],
"real_name": user["real_name"],
"user_type": user["user_type"],
"need_change_password": user["need_change_password"] == 1
}
# 获取学生信息
if user["student_id"]:
student = await StudentModel.get_by_id(user["student_id"])
if student:
result["student_no"] = student["student_no"]
result["student_name"] = student["name"]
result["total_points"] = student["total_points"]
# 获取管理员角色与权限
if user["user_type"] == "admin":
group = await PermissionChecker.get_user_group(user_id)
if group:
result["role"] = group.get("group_name") or group.get("role_type")
result["permissions"] = group.get("permissions_data", {})
result["group"] = _build_group_info(group)
# 绑定邮箱为可选展示字段,单独查询,避免影响登录/会话链路
try:
result["email"] = await UserModel.get_email_by_user_id(user_id)
except Exception as e:
logger.warning(f"读取绑定邮箱失败(数据库可能尚未升级): {e}")
result["email"] = None
return result
@staticmethod
async def request_password_reset(username: str, ip: str = None) -> Dict[str, Any]:
"""管理员通过绑定邮箱找回密码(SMTP)"""
generic_success = {
"success": True,
"message": f"如果该账号已绑定邮箱,重置链接已发送,请留意查收({settings.PASSWORD_RESET_EXPIRE_MINUTES}分钟内有效)"
}
if not EmailSender.is_configured():
return {"success": False, "message": "系统未配置邮件服务,请联系班主任或系统管理员"}
if not settings.FRONTEND_URL:
return {"success": False, "message": "系统未配置站点地址(FRONTEND_URL),无法生成重置链接"}
# 频率限制:同一账号 60 秒内只允许请求一次
limit_key = f"pwd_reset_req:{username}"
if await RedisClient.exists(limit_key):
return generic_success
await RedisClient.set(limit_key, "1", expire=60)
user = await UserModel.get_by_username(username)
if not user or user.get("user_type") != "admin":
logger.info(f"找回密码请求未发送(账号不存在/非管理员): {username}, IP={ip}")
return generic_success
# 绑定邮箱仅在找回密码功能中查询
try:
bound_email = await UserModel.get_email_by_user_id(user["user_id"])
except Exception as e:
logger.error(f"读取绑定邮箱失败(数据库可能待升级): {e}")
return {"success": False, "message": "数据库待升级,找回密码功能暂不可用"}
if not bound_email:
logger.info(f"找回密码请求未发送(未绑定邮箱): {username}, IP={ip}")
return generic_success
# 生成一次性令牌,并作废该用户此前的令牌
token = secrets.token_urlsafe(32)
expire_seconds = settings.PASSWORD_RESET_EXPIRE_MINUTES * 60
old_token = await RedisClient.get(f"pwd_reset_user:{user['user_id']}")
if old_token:
await RedisClient.delete(f"pwd_reset:{old_token}")
await RedisClient.set(f"pwd_reset:{token}", user["user_id"], expire=expire_seconds)
await RedisClient.set(f"pwd_reset_user:{user['user_id']}", token, expire=expire_seconds)
reset_url = f"{settings.FRONTEND_URL}/reset_password.php?token={token}"
html_body = f"""
<div style="max-width:560px;margin:0 auto;font-family:'Microsoft YaHei',Arial,sans-serif;color:#333;">
<h2 style="color:#667eea;">{html_escape(settings.APP_NAME)} - 密码重置</h2>
<p>{html_escape(user.get('real_name') or user['username'])},您好:</p>
<p>我们收到了您账号({html_escape(user['username'])})的密码重置请求。请点击下方按钮设置新密码:</p>
<p style="text-align:center;margin:28px 0;">
<a href="{reset_url}" style="display:inline-block;padding:12px 28px;background:#667eea;color:#fff;text-decoration:none;border-radius:6px;">重置密码</a>
</p>
<p style="font-size:13px;color:#888;">链接 {settings.PASSWORD_RESET_EXPIRE_MINUTES} 分钟内有效,且只能使用一次。如果按钮无法点击,请复制以下链接到浏览器打开:</p>
<p style="font-size:12px;color:#888;word-break:break-all;">{reset_url}</p>
<p style="font-size:13px;color:#888;">如果并非您本人操作,请忽略本邮件,您的密码不会被修改。</p>
</div>
"""
ok, message_text = await EmailSender.send(
bound_email,
f"{settings.APP_NAME} - 密码重置",
html_body
)
if not ok:
await RedisClient.delete(f"pwd_reset:{token}")
await RedisClient.delete(f"pwd_reset_user:{user['user_id']}")
logger.error(f"密码重置邮件发送失败: {username} - {message_text}")
return {"success": False, "message": "重置邮件发送失败,请稍后重试或联系系统管理员"}
logger.info(f"已向用户[{username}]的绑定邮箱发送密码重置链接, IP={ip}")
return generic_success
@staticmethod
async def check_reset_token(token: str) -> Dict[str, Any]:
"""校验密码重置令牌是否有效"""
if not token:
return {"valid": False}
user_id_raw = await RedisClient.get(f"pwd_reset:{token}")
if not user_id_raw:
return {"valid": False}
user = await UserModel.get_by_user_id(int(user_id_raw))
if not user or user.get("user_type") != "admin" or user.get("status") != 1:
return {"valid": False}
return {
"valid": True,
"username": user["username"],
"real_name": user["real_name"]
}
@staticmethod
async def reset_password_by_token(token: str, new_password: str) -> Dict[str, Any]:
"""使用邮件令牌重置管理员密码"""
if not token:
return {"success": False, "message": "重置链接无效"}
user_id_raw = await RedisClient.get(f"pwd_reset:{token}")
if not user_id_raw:
return {"success": False, "message": "重置链接无效或已过期,请重新申请"}
user_id = int(user_id_raw)
user = await UserModel.get_by_user_id(user_id)
if not user or user.get("user_type") != "admin" or user.get("status") != 1:
return {"success": False, "message": "账号不存在或不可重置密码"}
is_valid, message = security.validate_password_strength(new_password)
if not is_valid:
return {"success": False, "message": message}
updated = await UserModel.update_password(user_id, new_password)
if not updated:
return {"success": False, "message": "密码重置失败"}
# 令牌一次性使用;重置后强制所有会话重新登录
await RedisClient.delete(f"pwd_reset:{token}")
await RedisClient.delete(f"pwd_reset_user:{user_id}")
await RedisClient.delete_user_token(user_id)
logger.info(f"用户[{user_id}] 通过邮箱重置密码成功")
return {"success": True, "message": "密码重置成功,请使用新密码登录"}
@staticmethod
async def _get_admin_by_password(user_id: int, password: str):
"""校验当前密码,返回管理员用户(用于邮箱绑定/解绑)"""
user = await UserModel.get_by_user_id(user_id)
if not user or user.get("user_type") != "admin":
return None, "仅管理员可绑定邮箱"
is_valid, _ = security.verify_password_v2(password, user["password_hash"])
if not is_valid:
return None, "当前密码错误"
return user, None
@staticmethod
async def send_bind_email_code(user_id: int, email: str) -> Dict[str, Any]:
"""向待绑定邮箱发送验证码(验证码绑定邮箱第一步,无需密码)"""
if not EmailSender.is_configured():
return {"success": False, "message": "系统未配置邮件服务,请联系班主任或系统管理员"}
user = await UserModel.get_by_user_id(user_id)
if not user or user.get("user_type") != "admin":
return {"success": False, "message": "仅管理员可绑定邮箱"}
normalized_email = (email or "").strip()
if not is_valid_email(normalized_email):
return {"success": False, "message": "邮箱格式不正确"}
# 数据库未升级(users.email 不存在)时提前返回明确提示,避免发送无效验证码
try:
await UserModel.get_email_by_user_id(user_id)
except Exception as e:
logger.error(f"邮箱绑定失败(数据库可能待升级): {e}")
return {"success": False, "message": "数据库待升级,请先完成系统升级后再绑定邮箱"}
# 频率限制:同一账号 60 秒内只能发送一次
limit_key = f"email_bind_req:{user_id}"
if await RedisClient.exists(limit_key):
return {"success": False, "message": "验证码发送过于频繁,请稍后再试"}
await RedisClient.set(limit_key, "1", expire=60)
code = f"{secrets.randbelow(1000000):06d}"
expire_seconds = settings.EMAIL_CODE_EXPIRE_MINUTES * 60
await RedisClient.set(
f"email_bind_code:{user_id}",
{"code": code, "email": normalized_email, "attempts": 0},
expire=expire_seconds
)
html_body = f"""
<div style="max-width:560px;margin:0 auto;font-family:'Microsoft YaHei',Arial,sans-serif;color:#333;">
<h2 style="color:#667eea;">{html_escape(settings.APP_NAME)} - 邮箱绑定验证</h2>
<p>您好,您正在绑定本邮箱用于找回密码,验证码为:</p>
<p style="text-align:center;margin:24px 0;">
<span style="display:inline-block;padding:10px 28px;background:#f3f4ff;border-radius:6px;font-size:28px;font-weight:bold;letter-spacing:6px;color:#667eea;">{code}</span>
</p>
<p style="font-size:13px;color:#888;">验证码 {settings.EMAIL_CODE_EXPIRE_MINUTES} 分钟内有效,请勿泄露给他人。</p>
<p style="font-size:13px;color:#888;">如果并非您本人操作,请忽略本邮件。</p>
</div>
"""
ok, message = await EmailSender.send(
normalized_email,
f"{settings.APP_NAME} - 邮箱绑定验证码",
html_body
)
if not ok:
await RedisClient.delete(f"email_bind_code:{user_id}")
logger.error(f"邮箱验证码发送失败: 用户[{user_id}] -> {normalized_email} - {message}")
return {"success": False, "message": "验证码发送失败,请检查邮箱地址或稍后重试"}
logger.info(f"用户[{user_id}] 邮箱绑定验证码已发送至 {normalized_email}")
return {
"success": True,
"message": f"验证码已发送至 {normalized_email},{settings.EMAIL_CODE_EXPIRE_MINUTES} 分钟内有效"
}
@staticmethod
async def confirm_bind_email(user_id: int, email: str, code: str) -> Dict[str, Any]:
"""校验验证码并绑定邮箱(验证码绑定邮箱第二步)"""
normalized_email = (email or "").strip()
normalized_code = (code or "").strip()
if not is_valid_email(normalized_email):
return {"success": False, "message": "邮箱格式不正确"}
if not normalized_code:
return {"success": False, "message": "请输入验证码"}
cached = await RedisClient.get_json(f"email_bind_code:{user_id}")
if not cached or not isinstance(cached, dict):
return {"success": False, "message": "验证码已过期,请重新发送"}
if cached.get("email") != normalized_email:
return {"success": False, "message": "邮箱与验证码不匹配,请重新发送"}
attempts = int(cached.get("attempts", 0))
if attempts >= 5:
await RedisClient.delete(f"email_bind_code:{user_id}")
return {"success": False, "message": "验证码尝试次数过多,请重新发送"}
if cached.get("code") != normalized_code:
cached["attempts"] = attempts + 1
await RedisClient.set(
f"email_bind_code:{user_id}",
cached,
expire=settings.EMAIL_CODE_EXPIRE_MINUTES * 60
)
return {"success": False, "message": "验证码错误"}
try:
updated = await UserModel.update_email(user_id, normalized_email)
except Exception as e:
logger.error(f"绑定邮箱失败(数据库可能待升级): {e}")
return {"success": False, "message": "数据库待升级,请先完成系统升级后再绑定邮箱"}
if not updated:
return {"success": False, "message": "邮箱绑定失败"}
await RedisClient.delete(f"email_bind_code:{user_id}")
logger.info(f"用户[{user_id}] 邮箱绑定成功: {normalized_email}")
return {"success": True, "message": "邮箱绑定成功", "email": normalized_email}
@staticmethod
async def unbind_email(user_id: int, password: str) -> Dict[str, Any]:
"""解除绑定邮箱(验证当前密码)"""
_, error = await AuthService._get_admin_by_password(user_id, password)
if error:
return {"success": False, "message": error}
await RedisClient.delete(f"email_bind_code:{user_id}")
try:
updated = await UserModel.update_email(user_id, None)
except Exception as e:
logger.error(f"解除绑定邮箱失败(数据库可能待升级): {e}")
return {"success": False, "message": "数据库待升级,请先完成系统升级后再操作邮箱"}
if not updated:
return {"success": False, "message": "解除绑定失败"}
logger.info(f"用户[{user_id}] 已解除邮箱绑定")
return {"success": True, "message": "邮箱已解除绑定", "email": None}
@staticmethod
def _get_redirect_path(user_type: str, role: str = None) -> str:
"""获取跳转路径"""
if user_type == "student":
return "/student/dashboard.php"
elif user_type == "parent":
return "/parent/dashboard.php"
else:
return "/admin/dashboard.php"