diff --git a/INSTALL.md b/INSTALL.md index cc46f95..92829a6 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -342,6 +342,7 @@ sudo systemctl restart nginx | `SMTP_SSL` | 是否使用SSL直连 | true | | `SMTP_STARTTLS` | 是否使用STARTTLS | false | | `PASSWORD_RESET_EXPIRE_MINUTES` | 重置链接有效期(分钟) | 30 | +| `EMAIL_CODE_EXPIRE_MINUTES` | 邮箱绑定验证码有效期(分钟) | 10 | > 说明:v4.0 起各权限组的加减分上限改为系统内动态配置;启用 `SMTP_ENABLED=true` 并配置好 SMTP 后,管理员可在登录页通过"忘记密码"自助重置密码(需先在管理端绑定邮箱)。 diff --git a/README.md b/README.md index 424045c..ef96f12 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ - 考勤管理:按时段(早上 7:15/中午 14:00/晚修 19:30)记录考勤、自定义考勤扣分值 - 科目管理:动态增删学科 - 权限组管理:自定义权限组(勾选功能权限 + 配置加分/扣分上限),管理员账号绑定权限组与邮箱;班主任组为锁定系统组,其余预置组可编辑 -- 密码找回:管理员绑定邮箱后,可在登录页通过 SMTP 邮件自助重置密码(链接一次性、限时有效) +- 密码找回:管理员绑定邮箱(自助绑定需 SMTP 邮箱验证码),忘记密码时可在登录页通过邮箱获取一次性重置链接(限时、仅可使用一次) - 学期管理:创建/编辑/删除学期、激活学期、归档学期(含考勤/作业统计快照)、关联历史记录、归档后可选重置分数 - 个人查询:按学生查看基础分、加分合计、减分合计、月度分(月初分/加分/减分/月末分)及月度加减分理由汇总、明细记录,支持导出个人记录 - 排行榜百分比筛选:在排行榜上方输入百分比,筛选显示前N%的学生(抹零法) @@ -290,7 +290,7 @@ classmanager/ | v2.9 | 2026.6.8 | 历史记录表头优化:合并/非合并视图统一新增"类型"列(手动/作业/考勤),列顺序统一为"类型、分值、原因、学生、操作人、时间" | | v3.0 | 2026.9.17 | 导出按学期隔离(默认当前学期,可选历史/全部,历史导出不再受1000条限制);新增管理端"个人查询"页面(基础分/加分/减分/月度分/月度理由汇总/明细,可导出,支持学生列表直达);加减分与考勤记录自动关联当前学期,历史记录页新增学期筛选 | | v4.0 | 2026.9.17 | 权限体系重构:新增自定义权限组(14项功能权限 + 允许加分/加分上限/允许扣分/扣分上限动态配置),管理员账号绑定权限组,预置六组并支持新建;加减分/考勤上限改为按权限组动态校验;新增班主任导出学生名单(自选字段);前端页面与按钮全部改为权限驱动 | -| v4.1 | 2026.9.17 | 管理员可绑定邮箱;新增找回密码(SMTP邮件重置链接,一次性、30分钟有效);登录页新增忘记密码入口,管理端支持添加/编辑管理员邮箱与自助绑定 | +| v4.1 | 2026.9.17 | 管理员可绑定邮箱;自助绑定邮箱采用 SMTP 验证码验证(10分钟有效、限流+尝试次数限制),忘记密码使用一次性重置链接(30分钟有效);登录页新增忘记密码入口,管理端支持添加/编辑管理员邮箱 | ## 许可证 diff --git a/backend/.env.example b/backend/.env.example index 06ddcb7..324a61a 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -149,6 +149,8 @@ SMTP_SSL=true SMTP_STARTTLS=false # 密码重置链接有效期(分钟) PASSWORD_RESET_EXPIRE_MINUTES=30 +# 邮箱绑定验证码有效期(分钟) +EMAIL_CODE_EXPIRE_MINUTES=10 # =========================================== # 日志配置 diff --git a/backend/config.py b/backend/config.py index fbb0b3c..a3c8b5f 100644 --- a/backend/config.py +++ b/backend/config.py @@ -65,6 +65,8 @@ class Settings: SMTP_STARTTLS: bool = os.getenv("SMTP_STARTTLS", "False").lower() == "true" # 密码重置链接有效期(分钟) PASSWORD_RESET_EXPIRE_MINUTES: int = int(os.getenv("PASSWORD_RESET_EXPIRE_MINUTES", "30")) + # 邮箱验证码有效期(分钟) + EMAIL_CODE_EXPIRE_MINUTES: int = int(os.getenv("EMAIL_CODE_EXPIRE_MINUTES", "10")) DEDUCTION_HOMEWORK_NOT_SUBMIT: int = int(os.getenv("DEDUCTION_HOMEWORK_NOT_SUBMIT", "2")) DEDUCTION_HOMEWORK_LATE: int = int(os.getenv("DEDUCTION_HOMEWORK_LATE", "1")) diff --git a/backend/models/user.py b/backend/models/user.py index 5c72e66..11c38fe 100644 --- a/backend/models/user.py +++ b/backend/models/user.py @@ -9,6 +9,7 @@ # 版权所有 © Sea Network Technology Studio # =========================================== +from typing import Optional from utils.database import execute_one, execute_insert, execute_update from utils.security import security from utils.logger import get_logger @@ -21,9 +22,9 @@ class UserModel: @staticmethod async def get_by_username(username: str) -> dict: - """根据用户名获取用户""" + """根据用户名获取用户(登录主链路,不查询邮箱)""" sql = """ - SELECT user_id, username, password_hash, real_name, email, user_type, + SELECT user_id, username, password_hash, real_name, user_type, student_id, status, need_change_password, last_login_time, last_login_ip FROM users WHERE username = %s AND status = 1 @@ -32,14 +33,20 @@ class UserModel: @staticmethod async def get_by_user_id(user_id: int) -> dict: - """根据用户ID获取用户""" + """根据用户ID获取用户(不查询邮箱)""" sql = """ - SELECT user_id, username, password_hash, real_name, email, user_type, student_id, + SELECT user_id, username, password_hash, real_name, user_type, student_id, need_change_password, status FROM users WHERE user_id = %s """ return await execute_one(sql, (user_id,)) + + @staticmethod + async def get_email_by_user_id(user_id: int) -> Optional[str]: + """获取用户绑定邮箱(仅找回密码/绑定邮箱功能使用)""" + result = await execute_one("SELECT email FROM users WHERE user_id = %s", (user_id,)) + return result.get("email") if result else None @staticmethod async def create_student(username: str, password: str, real_name: str, student_id: int) -> int: @@ -97,7 +104,7 @@ class UserModel: async def get_by_username_any(username: str) -> dict: """根据用户名获取用户(含已禁用)""" sql = """ - SELECT user_id, username, password_hash, real_name, email, user_type, + SELECT user_id, username, password_hash, real_name, user_type, student_id, status, need_change_password, last_login_time, last_login_ip FROM users WHERE username = %s diff --git a/backend/routes/auth.py b/backend/routes/auth.py index 1a27c52..3e367fe 100644 --- a/backend/routes/auth.py +++ b/backend/routes/auth.py @@ -14,7 +14,8 @@ from typing import Dict, Any from schemas.auth import ( LoginRequest, ChangePasswordRequest, - ForgotPasswordRequest, ResetPasswordRequest, BindEmailRequest + ForgotPasswordRequest, ResetPasswordRequest, + SendEmailCodeRequest, ConfirmBindEmailRequest, UnbindEmailRequest ) from services.auth_service import AuthService from middleware.permission import get_current_user @@ -53,7 +54,6 @@ async def login(request: LoginRequest, http_request: Request): "role": result.get("role"), "permissions": result.get("permissions", {}), "group": result.get("group"), - "email": result.get("email"), "need_change_password": result["need_change_password"], "redirect": result["redirect"] }, @@ -148,19 +148,54 @@ async def reset_password_by_token(request: Request, req: ResetPasswordRequest): return error_response(message=result["message"], code=400) -@router.post("/bind-email") -async def bind_email(request: Request, req: BindEmailRequest): +@router.post("/email/send-code") +async def send_bind_email_code(request: Request, req: SendEmailCodeRequest): """ - 管理员绑定/修改绑定邮箱(需验证当前密码) + 发送邮箱绑定验证码(需当前密码,验证码发送至待绑定邮箱) """ user = await get_current_user(request) if user["user_type"] != "admin": return error_response(message="仅管理员可绑定邮箱", code=403) - result = await AuthService.bind_email( + result = await AuthService.send_bind_email_code( user_id=user["user_id"], password=req.password, email=req.email ) + if result["success"]: + return success_response(message=result["message"]) + return error_response(message=result["message"]) + + +@router.post("/email/confirm") +async def confirm_bind_email(request: Request, req: ConfirmBindEmailRequest): + """ + 校验验证码并绑定邮箱 + """ + user = await get_current_user(request) + if user["user_type"] != "admin": + return error_response(message="仅管理员可绑定邮箱", code=403) + result = await AuthService.confirm_bind_email( + user_id=user["user_id"], + email=req.email, + code=req.code + ) if result["success"]: return success_response(data={"email": result.get("email")}, message=result["message"]) + return error_response(message=result["message"]) + + +@router.post("/email/unbind") +async def unbind_email(request: Request, req: UnbindEmailRequest): + """ + 解除绑定邮箱(需当前密码) + """ + user = await get_current_user(request) + if user["user_type"] != "admin": + return error_response(message="仅管理员可绑定邮箱", code=403) + result = await AuthService.unbind_email( + user_id=user["user_id"], + password=req.password + ) + if result["success"]: + return success_response(data={"email": None}, message=result["message"]) return error_response(message=result["message"]) \ No newline at end of file diff --git a/backend/schemas/auth.py b/backend/schemas/auth.py index 39271e0..fa25d14 100644 --- a/backend/schemas/auth.py +++ b/backend/schemas/auth.py @@ -67,7 +67,18 @@ class ResetPasswordRequest(BaseModel): new_password: str = Field(..., min_length=6, max_length=20, description="新密码") -class BindEmailRequest(BaseModel): - """绑定/修改邮箱请求""" +class SendEmailCodeRequest(BaseModel): + """发送邮箱绑定验证码请求""" password: str = Field(..., min_length=1, max_length=50, description="当前密码") - email: str = Field(default="", max_length=100, description="新邮箱(留空解除绑定)") \ No newline at end of file + email: str = Field(..., min_length=3, max_length=100, description="待绑定的邮箱") + + +class ConfirmBindEmailRequest(BaseModel): + """确认绑定邮箱请求""" + email: str = Field(..., min_length=3, max_length=100, description="待绑定的邮箱") + code: str = Field(..., min_length=4, max_length=10, description="邮箱验证码") + + +class UnbindEmailRequest(BaseModel): + """解除绑定邮箱请求""" + password: str = Field(..., min_length=1, max_length=50, description="当前密码") \ No newline at end of file diff --git a/backend/services/auth_service.py b/backend/services/auth_service.py index 4328e73..5148326 100644 --- a/backend/services/auth_service.py +++ b/backend/services/auth_service.py @@ -131,7 +131,6 @@ class AuthService: "role": role, "permissions": permissions, "group": group_info, - "email": user.get("email"), "need_change_password": user["need_change_password"] == 1, "redirect": redirect } @@ -191,7 +190,6 @@ class AuthService: "username": user["username"], "real_name": user["real_name"], "user_type": user["user_type"], - "email": user.get("email"), "need_change_password": user["need_change_password"] == 1 } @@ -210,6 +208,12 @@ class AuthService: 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 @@ -232,8 +236,14 @@ class AuthService: await RedisClient.set(limit_key, "1", expire=60) user = await UserModel.get_by_username(username) - if not user or user.get("user_type") != "admin" or not user.get("email"): - logger.info(f"找回密码请求未发送(账号不存在/非管理员/未绑定邮箱): {username}, IP={ip}") + if not user or user.get("user_type") != "admin": + logger.info(f"找回密码请求未发送(账号不存在/非管理员): {username}, IP={ip}") + return generic_success + + # 绑定邮箱仅在找回密码功能中查询 + bound_email = await UserModel.get_email_by_user_id(user["user_id"]) + if not bound_email: + logger.info(f"找回密码请求未发送(未绑定邮箱): {username}, IP={ip}") return generic_success # 生成一次性令牌,并作废该用户此前的令牌 @@ -260,7 +270,7 @@ class AuthService: """ ok, message_text = await EmailSender.send( - user["email"], + bound_email, f"{settings.APP_NAME} - 密码重置", html_body ) @@ -319,30 +329,122 @@ class AuthService: return {"success": True, "message": "密码重置成功,请使用新密码登录"} @staticmethod - async def bind_email(user_id: int, password: str, email: str) -> Dict[str, Any]: - """管理员绑定/修改/解除绑定邮箱(需验证当前密码)""" + 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 {"success": False, "message": "仅管理员可绑定邮箱"} - + return None, "仅管理员可绑定邮箱" is_valid, _ = security.verify_password_v2(password, user["password_hash"]) if not is_valid: - return {"success": False, "message": "当前密码错误"} + return None, "当前密码错误" + return user, None + + @staticmethod + async def send_bind_email_code(user_id: int, password: str, email: str) -> Dict[str, Any]: + """向待绑定邮箱发送验证码(验证码绑定邮箱第一步)""" + if not EmailSender.is_configured(): + return {"success": False, "message": "系统未配置邮件服务,请联系班主任或系统管理员"} - normalized_email = (email or "").strip() or None - if normalized_email and not is_valid_email(normalized_email): + _, error = await AuthService._get_admin_by_password(user_id, password) + if error: + return {"success": False, "message": error} + + normalized_email = (email or "").strip() + if not is_valid_email(normalized_email): 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""" +
您好,您正在绑定本邮箱用于找回密码,验证码为:
++ {code} +
+验证码 {settings.EMAIL_CODE_EXPIRE_MINUTES} 分钟内有效,请勿泄露给他人。
+如果并非您本人操作,请忽略本邮件。
+- 绑定邮箱后,忘记密码时可在登录页通过“忘记密码”向该邮箱发送重置链接。 + 绑定邮箱需通过邮箱验证码验证;忘记密码时可在登录页通过该邮箱获取一次性重置链接。