diff --git a/backend/models/user.py b/backend/models/user.py index b07ebe9..5062988 100644 --- a/backend/models/user.py +++ b/backend/models/user.py @@ -102,6 +102,23 @@ class UserModel: return True exists = await execute_one("SELECT 1 FROM users WHERE user_id = %s", (user_id,)) return exists is not None + + @staticmethod + async def upgrade_password_hash(user_id: int, password: str) -> bool: + """仅升级密码哈希格式(bcrypt),不改变 need_change_password 标记 + + 登录时自动升级旧哈希不等于用户主动改密,不能清除"密码待修改"标记。 + """ + try: + password_hash = security.bcrypt_password(password) + except Exception as e: + logger.error(f"密码加密失败: {e}") + raise + result = await execute_update( + "UPDATE users SET password_hash = %s WHERE user_id = %s", + (password_hash, user_id) + ) + return result > 0 @staticmethod async def update_last_login(user_id: int, ip: str) -> None: diff --git a/backend/services/auth_service.py b/backend/services/auth_service.py index ecb91ad..6113ef2 100644 --- a/backend/services/auth_service.py +++ b/backend/services/auth_service.py @@ -71,10 +71,10 @@ class AuthService: 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) + await UserModel.upgrade_password_hash(user["user_id"], password) except Exception: pass @@ -148,13 +148,13 @@ class AuthService: return {"success": False, "message": "用户不存在"} # 验证原密码 - # force=True 仅在 need_change_password=1 时允许(首次登录强制改密) - # 其他情况必须验证旧密码 + # 仅当"密码待修改"(need_change_password=1:初始密码/被重置后未修改)且 force=True 时免原密码 + # 其他情况必须验证原密码 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"]) @@ -181,7 +181,7 @@ class AuthService: @staticmethod async def init_password(user_id: int, new_password: str) -> Dict[str, Any]: - """首次登录初始化密码(无需原密码,仅 need_change_password=1 时可用)""" + """密码待修改时初始化新密码(无需原密码,仅 need_change_password=1 时可用)""" user = await UserModel.get_by_user_id(user_id) if not user: return {"success": False, "message": "用户不存在"} diff --git a/docs/teacher.md b/docs/teacher.md index a6eb35b..ccf4cc6 100644 --- a/docs/teacher.md +++ b/docs/teacher.md @@ -385,7 +385,7 @@ - 输入原密码和新密码 - 新密码需符合密码强度要求(密码策略可在「系统设置」中调整) - 修改成功后需重新登录 -- **首次登录或被管理员重置密码后**:登录时会弹窗要求设置新密码(**无需输入原密码**);日常主动改密仍需原密码 +- **密码待修改时(首次使用或被管理员重置后)**:登录时会弹窗要求设置新密码(**无需输入原密码**);日常主动改密仍需原密码 - 页面下方可**绑定邮箱**(找回密码用): 1. 输入新邮箱,点击"发送验证码"(无需密码) 2. 系统通过 SMTP 向该邮箱发送6位验证码(10分钟内有效) diff --git a/frontend/includes/header.php b/frontend/includes/header.php index 0cf2942..4176091 100644 --- a/frontend/includes/header.php +++ b/frontend/includes/header.php @@ -109,12 +109,13 @@ $page_title = $page_title ?? '首页'; - +