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""" +
+

{html_escape(settings.APP_NAME)} - 邮箱绑定验证

+

您好,您正在绑定本邮箱用于找回密码,验证码为:

+

+ {code} +

+

验证码 {settings.EMAIL_CODE_EXPIRE_MINUTES} 分钟内有效,请勿泄露给他人。

+

如果并非您本人操作,请忽略本邮件。

+
+ """ + 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": "验证码错误"} + updated = await UserModel.update_email(user_id, normalized_email) if not updated: - return {"success": False, "message": "邮箱更新失败"} + return {"success": False, "message": "邮箱绑定失败"} - logger.info(f"用户[{user_id}] 更新绑定邮箱: {normalized_email or '(解除绑定)'}") - return { - "success": True, - "message": "邮箱绑定成功" if normalized_email else "邮箱已解除绑定", - "email": normalized_email - } + 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}") + updated = await UserModel.update_email(user_id, None) + 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: diff --git a/docs/guide/teacher.md b/docs/guide/teacher.md index 939eea1..12d36f8 100644 --- a/docs/guide/teacher.md +++ b/docs/guide/teacher.md @@ -39,7 +39,7 @@ - **撤销记录**:历史记录页或学生个人查询页 → 点击撤销按钮 - **导入学生**:学生管理页 → 导入学生(JSON格式,需包含 `student_no` 和 `name`) - **添加班干部**:管理员管理页 → 添加管理员 → 填写账号信息、绑定邮箱(选填)并选择权限组 -- **绑定邮箱/找回密码**:修改密码页 → 绑定邮箱;忘记密码时在登录页点击"忘记密码?"通过邮箱重置 +- **绑定邮箱/找回密码**:修改密码页 → 输入新邮箱+当前密码 → 发送验证码 → 输入验证码确认绑定;忘记密码时在登录页点击"忘记密码?"通过邮箱获取一次性重置链接 - **重置班干部密码**:管理员管理页 → 重置密码 → 输入新密码 - **权限组管理**:管理员管理页 → 新建/编辑权限组 → 勾选功能权限并配置加分/扣分上限 - **导出学生名单**:学生管理页 → 导出学生名单 → 勾选字段 → 开始导出 diff --git a/docs/teacher.md b/docs/teacher.md index b82c42d..5b47445 100644 --- a/docs/teacher.md +++ b/docs/teacher.md @@ -315,14 +315,19 @@ - 输入原密码和新密码 - 新密码需符合密码强度要求 - 修改成功后需重新登录 -- 页面下方可**绑定邮箱**(需输入当前密码):绑定后忘记密码时可在登录页自助申请重置邮件;留空保存则解除绑定 +- 页面下方可**绑定邮箱**(找回密码用): + 1. 输入新邮箱和当前密码,点击"发送验证码" + 2. 系统通过 SMTP 向该邮箱发送6位验证码(10分钟内有效) + 3. 输入验证码后点击"确认绑定" + 4. 点击"解除绑定"可解除已绑定邮箱(需当前密码) +- 管理员管理页添加/编辑账号时也可由班主任直接填写绑定邮箱 --- ## 常见问题 ### Q: 忘记密码怎么办? -1. 已在管理端绑定邮箱的账号:在登录页点击"忘记密码?",输入用户名,系统会向绑定邮箱发送重置链接(30分钟内有效); +1. 已绑定邮箱的账号:在登录页点击"忘记密码?",输入用户名,系统会向绑定邮箱发送**一次性重置链接**(30分钟内有效、仅可使用一次); 2. 班主任账号或未绑定邮箱的账号:请联系系统管理员,通过数据库/调试接口重置。 ### Q: 如何导出全班德育分记录? diff --git a/frontend/admin/password.php b/frontend/admin/password.php index ff6cbb1..9c84cfc 100644 --- a/frontend/admin/password.php +++ b/frontend/admin/password.php @@ -49,24 +49,32 @@ include __DIR__ . '/../includes/header.php';
绑定邮箱(找回密码)

- 绑定邮箱后,忘记密码时可在登录页通过“忘记密码”向该邮箱发送重置链接。 + 绑定邮箱需通过邮箱验证码验证;忘记密码时可在登录页通过该邮箱获取一次性重置链接。

-
-
- - -
-
- - - 安全验证:绑定邮箱需要输入当前登录密码 -
- -
+
+ + +
+
+ + + 安全验证:发送验证码需要输入当前登录密码 +
+
+ +
+
+ + +
+
+ + +
@@ -101,28 +109,78 @@ document.getElementById('passwordForm').addEventListener('submit', async (e) => } }); -document.getElementById('emailForm').addEventListener('submit', async (e) => { - e.preventDefault(); +async function sendBindEmailCode() { const email = document.getElementById('bindEmail').value.trim(); const password = document.getElementById('emailPassword').value; + if (!email) { + showToast('请输入要绑定的邮箱', 'warning'); + return; + } if (!password) { showToast('请输入当前密码', 'warning'); return; } - const res = await apiPost('/api/auth/bind-email', { + const res = await apiPost('/api/auth/email/send-code', { password: password, email: email }); + if (res && res.success) { + showToast(res.message || '验证码已发送,请查收邮箱'); + document.getElementById('emailCode').focus(); + } else { + showToast(res?.message || '验证码发送失败', 'error'); + } +} + +async function confirmBindEmail() { + const email = document.getElementById('bindEmail').value.trim(); + const code = document.getElementById('emailCode').value.trim(); + if (!email) { + showToast('请输入要绑定的邮箱', 'warning'); + return; + } + if (!code) { + showToast('请输入邮箱验证码', 'warning'); + return; + } + const res = await apiPost('/api/auth/email/confirm', { + email: email, + code: code + }); if (res && res.success) { const bound = res.data && res.data.email ? res.data.email : ''; document.getElementById('currentEmail').textContent = bound || '未绑定'; document.getElementById('bindEmail').value = ''; document.getElementById('emailPassword').value = ''; - showToast(res.message || '邮箱保存成功'); + document.getElementById('emailCode').value = ''; + showToast(res.message || '邮箱绑定成功'); } else { - showToast(res?.message || '邮箱保存失败', 'error'); + showToast(res?.message || '邮箱绑定失败', 'error'); } -}); +} + +async function unbindEmail() { + const password = document.getElementById('emailPassword').value; + if (!password) { + showToast('请输入当前密码', 'warning'); + return; + } + if (!confirm('确定解除绑定邮箱吗?解除后将无法通过邮箱找回密码。')) { + return; + } + const res = await apiPost('/api/auth/email/unbind', { + password: password + }); + if (res && res.success) { + document.getElementById('currentEmail').textContent = '未绑定'; + document.getElementById('bindEmail').value = ''; + document.getElementById('emailPassword').value = ''; + document.getElementById('emailCode').value = ''; + showToast(res.message || '邮箱已解除绑定'); + } else { + showToast(res?.message || '解除绑定失败', 'error'); + } +} \ No newline at end of file