登录链路去除邮箱查询,绑定邮箱改为SMTP验证码

1. 登录/会话/改密/重激活等主链路不再查询 email,仅找回密码与绑定邮箱功能查询,避免数据库未升级时登录500
2. 自助绑定邮箱改为验证码流程:发送验证码(当前密码+60秒限流)→ 校验验证码(10分钟有效、最多5次尝试)→ 绑定;解绑需当前密码
3. 重置密码保持一次性链接(30分钟、用后即删、重置后强制重新登录)
4. 新增 EMAIL_CODE_EXPIRE_MINUTES 配置,文档同步
This commit is contained in:
canglan committed 2026-09-18 08:33:23 +08:00
1 parent 7d22b2b922
commit 6c8fd2b432
11 files changed
+280 -57

No files matched your search

+121 -19
View File
@@ -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:
</div>
"""
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"""
<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": "验证码错误"}
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: