登录链路去除邮箱查询,绑定邮箱改为SMTP验证码
1. 登录/会话/改密/重激活等主链路不再查询 email,仅找回密码与绑定邮箱功能查询,避免数据库未升级时登录500 2. 自助绑定邮箱改为验证码流程:发送验证码(当前密码+60秒限流)→ 校验验证码(10分钟有效、最多5次尝试)→ 绑定;解绑需当前密码 3. 重置密码保持一次性链接(30分钟、用后即删、重置后强制重新登录) 4. 新增 EMAIL_CODE_EXPIRE_MINUTES 配置,文档同步
This commit is contained in:
1 parent
7d22b2b922
commit
6c8fd2b432
11 files changed
+280
-57
No files matched your search
@@ -149,6 +149,8 @@ SMTP_SSL=true
|
||||
SMTP_STARTTLS=false
|
||||
# 密码重置链接有效期(分钟)
|
||||
PASSWORD_RESET_EXPIRE_MINUTES=30
|
||||
# 邮箱绑定验证码有效期(分钟)
|
||||
EMAIL_CODE_EXPIRE_MINUTES=10
|
||||
|
||||
# ===========================================
|
||||
# 日志配置
|
||||
|
||||
@@ -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"))
|
||||
|
||||
+12
-5
@@ -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
|
||||
|
||||
+41
-6
@@ -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"])
|
||||
+14
-3
@@ -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="新邮箱(留空解除绑定)")
|
||||
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="当前密码")
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user