登录链路去除邮箱查询,绑定邮箱改为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
+273
-50
No files matched your search
@@ -342,6 +342,7 @@ sudo systemctl restart nginx
|
|||||||
| `SMTP_SSL` | 是否使用SSL直连 | true |
|
| `SMTP_SSL` | 是否使用SSL直连 | true |
|
||||||
| `SMTP_STARTTLS` | 是否使用STARTTLS | false |
|
| `SMTP_STARTTLS` | 是否使用STARTTLS | false |
|
||||||
| `PASSWORD_RESET_EXPIRE_MINUTES` | 重置链接有效期(分钟) | 30 |
|
| `PASSWORD_RESET_EXPIRE_MINUTES` | 重置链接有效期(分钟) | 30 |
|
||||||
|
| `EMAIL_CODE_EXPIRE_MINUTES` | 邮箱绑定验证码有效期(分钟) | 10 |
|
||||||
|
|
||||||
> 说明:v4.0 起各权限组的加减分上限改为系统内动态配置;启用 `SMTP_ENABLED=true` 并配置好 SMTP 后,管理员可在登录页通过"忘记密码"自助重置密码(需先在管理端绑定邮箱)。
|
> 说明:v4.0 起各权限组的加减分上限改为系统内动态配置;启用 `SMTP_ENABLED=true` 并配置好 SMTP 后,管理员可在登录页通过"忘记密码"自助重置密码(需先在管理端绑定邮箱)。
|
||||||
|
|
||||||
|
|||||||
@@ -27,7 +27,7 @@
|
|||||||
- 考勤管理:按时段(早上 7:15/中午 14:00/晚修 19:30)记录考勤、自定义考勤扣分值
|
- 考勤管理:按时段(早上 7:15/中午 14:00/晚修 19:30)记录考勤、自定义考勤扣分值
|
||||||
- 科目管理:动态增删学科
|
- 科目管理:动态增删学科
|
||||||
- 权限组管理:自定义权限组(勾选功能权限 + 配置加分/扣分上限),管理员账号绑定权限组与邮箱;班主任组为锁定系统组,其余预置组可编辑
|
- 权限组管理:自定义权限组(勾选功能权限 + 配置加分/扣分上限),管理员账号绑定权限组与邮箱;班主任组为锁定系统组,其余预置组可编辑
|
||||||
- 密码找回:管理员绑定邮箱后,可在登录页通过 SMTP 邮件自助重置密码(链接一次性、限时有效)
|
- 密码找回:管理员绑定邮箱(自助绑定需 SMTP 邮箱验证码),忘记密码时可在登录页通过邮箱获取一次性重置链接(限时、仅可使用一次)
|
||||||
- 学期管理:创建/编辑/删除学期、激活学期、归档学期(含考勤/作业统计快照)、关联历史记录、归档后可选重置分数
|
- 学期管理:创建/编辑/删除学期、激活学期、归档学期(含考勤/作业统计快照)、关联历史记录、归档后可选重置分数
|
||||||
- 个人查询:按学生查看基础分、加分合计、减分合计、月度分(月初分/加分/减分/月末分)及月度加减分理由汇总、明细记录,支持导出个人记录
|
- 个人查询:按学生查看基础分、加分合计、减分合计、月度分(月初分/加分/减分/月末分)及月度加减分理由汇总、明细记录,支持导出个人记录
|
||||||
- 排行榜百分比筛选:在排行榜上方输入百分比,筛选显示前N%的学生(抹零法)
|
- 排行榜百分比筛选:在排行榜上方输入百分比,筛选显示前N%的学生(抹零法)
|
||||||
@@ -290,7 +290,7 @@ classmanager/
|
|||||||
| v2.9 | 2026.6.8 | 历史记录表头优化:合并/非合并视图统一新增"类型"列(手动/作业/考勤),列顺序统一为"类型、分值、原因、学生、操作人、时间" |
|
| v2.9 | 2026.6.8 | 历史记录表头优化:合并/非合并视图统一新增"类型"列(手动/作业/考勤),列顺序统一为"类型、分值、原因、学生、操作人、时间" |
|
||||||
| v3.0 | 2026.9.17 | 导出按学期隔离(默认当前学期,可选历史/全部,历史导出不再受1000条限制);新增管理端"个人查询"页面(基础分/加分/减分/月度分/月度理由汇总/明细,可导出,支持学生列表直达);加减分与考勤记录自动关联当前学期,历史记录页新增学期筛选 |
|
| v3.0 | 2026.9.17 | 导出按学期隔离(默认当前学期,可选历史/全部,历史导出不再受1000条限制);新增管理端"个人查询"页面(基础分/加分/减分/月度分/月度理由汇总/明细,可导出,支持学生列表直达);加减分与考勤记录自动关联当前学期,历史记录页新增学期筛选 |
|
||||||
| v4.0 | 2026.9.17 | 权限体系重构:新增自定义权限组(14项功能权限 + 允许加分/加分上限/允许扣分/扣分上限动态配置),管理员账号绑定权限组,预置六组并支持新建;加减分/考勤上限改为按权限组动态校验;新增班主任导出学生名单(自选字段);前端页面与按钮全部改为权限驱动 |
|
| v4.0 | 2026.9.17 | 权限体系重构:新增自定义权限组(14项功能权限 + 允许加分/加分上限/允许扣分/扣分上限动态配置),管理员账号绑定权限组,预置六组并支持新建;加减分/考勤上限改为按权限组动态校验;新增班主任导出学生名单(自选字段);前端页面与按钮全部改为权限驱动 |
|
||||||
| v4.1 | 2026.9.17 | 管理员可绑定邮箱;新增找回密码(SMTP邮件重置链接,一次性、30分钟有效);登录页新增忘记密码入口,管理端支持添加/编辑管理员邮箱与自助绑定 |
|
| v4.1 | 2026.9.17 | 管理员可绑定邮箱;自助绑定邮箱采用 SMTP 验证码验证(10分钟有效、限流+尝试次数限制),忘记密码使用一次性重置链接(30分钟有效);登录页新增忘记密码入口,管理端支持添加/编辑管理员邮箱 |
|
||||||
|
|
||||||
## 许可证
|
## 许可证
|
||||||
|
|
||||||
|
|||||||
@@ -149,6 +149,8 @@ SMTP_SSL=true
|
|||||||
SMTP_STARTTLS=false
|
SMTP_STARTTLS=false
|
||||||
# 密码重置链接有效期(分钟)
|
# 密码重置链接有效期(分钟)
|
||||||
PASSWORD_RESET_EXPIRE_MINUTES=30
|
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"
|
SMTP_STARTTLS: bool = os.getenv("SMTP_STARTTLS", "False").lower() == "true"
|
||||||
# 密码重置链接有效期(分钟)
|
# 密码重置链接有效期(分钟)
|
||||||
PASSWORD_RESET_EXPIRE_MINUTES: int = int(os.getenv("PASSWORD_RESET_EXPIRE_MINUTES", "30"))
|
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_NOT_SUBMIT: int = int(os.getenv("DEDUCTION_HOMEWORK_NOT_SUBMIT", "2"))
|
||||||
DEDUCTION_HOMEWORK_LATE: int = int(os.getenv("DEDUCTION_HOMEWORK_LATE", "1"))
|
DEDUCTION_HOMEWORK_LATE: int = int(os.getenv("DEDUCTION_HOMEWORK_LATE", "1"))
|
||||||
|
|||||||
+12
-5
@@ -9,6 +9,7 @@
|
|||||||
# 版权所有 © Sea Network Technology Studio
|
# 版权所有 © Sea Network Technology Studio
|
||||||
# ===========================================
|
# ===========================================
|
||||||
|
|
||||||
|
from typing import Optional
|
||||||
from utils.database import execute_one, execute_insert, execute_update
|
from utils.database import execute_one, execute_insert, execute_update
|
||||||
from utils.security import security
|
from utils.security import security
|
||||||
from utils.logger import get_logger
|
from utils.logger import get_logger
|
||||||
@@ -21,9 +22,9 @@ class UserModel:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def get_by_username(username: str) -> dict:
|
async def get_by_username(username: str) -> dict:
|
||||||
"""根据用户名获取用户"""
|
"""根据用户名获取用户(登录主链路,不查询邮箱)"""
|
||||||
sql = """
|
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
|
student_id, status, need_change_password, last_login_time, last_login_ip
|
||||||
FROM users
|
FROM users
|
||||||
WHERE username = %s AND status = 1
|
WHERE username = %s AND status = 1
|
||||||
@@ -32,15 +33,21 @@ class UserModel:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def get_by_user_id(user_id: int) -> dict:
|
async def get_by_user_id(user_id: int) -> dict:
|
||||||
"""根据用户ID获取用户"""
|
"""根据用户ID获取用户(不查询邮箱)"""
|
||||||
sql = """
|
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
|
need_change_password, status
|
||||||
FROM users
|
FROM users
|
||||||
WHERE user_id = %s
|
WHERE user_id = %s
|
||||||
"""
|
"""
|
||||||
return await execute_one(sql, (user_id,))
|
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
|
@staticmethod
|
||||||
async def create_student(username: str, password: str, real_name: str, student_id: int) -> int:
|
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:
|
async def get_by_username_any(username: str) -> dict:
|
||||||
"""根据用户名获取用户(含已禁用)"""
|
"""根据用户名获取用户(含已禁用)"""
|
||||||
sql = """
|
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
|
student_id, status, need_change_password, last_login_time, last_login_ip
|
||||||
FROM users
|
FROM users
|
||||||
WHERE username = %s
|
WHERE username = %s
|
||||||
|
|||||||
+41
-6
@@ -14,7 +14,8 @@ from typing import Dict, Any
|
|||||||
|
|
||||||
from schemas.auth import (
|
from schemas.auth import (
|
||||||
LoginRequest, ChangePasswordRequest,
|
LoginRequest, ChangePasswordRequest,
|
||||||
ForgotPasswordRequest, ResetPasswordRequest, BindEmailRequest
|
ForgotPasswordRequest, ResetPasswordRequest,
|
||||||
|
SendEmailCodeRequest, ConfirmBindEmailRequest, UnbindEmailRequest
|
||||||
)
|
)
|
||||||
from services.auth_service import AuthService
|
from services.auth_service import AuthService
|
||||||
from middleware.permission import get_current_user
|
from middleware.permission import get_current_user
|
||||||
@@ -53,7 +54,6 @@ async def login(request: LoginRequest, http_request: Request):
|
|||||||
"role": result.get("role"),
|
"role": result.get("role"),
|
||||||
"permissions": result.get("permissions", {}),
|
"permissions": result.get("permissions", {}),
|
||||||
"group": result.get("group"),
|
"group": result.get("group"),
|
||||||
"email": result.get("email"),
|
|
||||||
"need_change_password": result["need_change_password"],
|
"need_change_password": result["need_change_password"],
|
||||||
"redirect": result["redirect"]
|
"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)
|
return error_response(message=result["message"], code=400)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/bind-email")
|
@router.post("/email/send-code")
|
||||||
async def bind_email(request: Request, req: BindEmailRequest):
|
async def send_bind_email_code(request: Request, req: SendEmailCodeRequest):
|
||||||
"""
|
"""
|
||||||
管理员绑定/修改绑定邮箱(需验证当前密码)
|
发送邮箱绑定验证码(需当前密码,验证码发送至待绑定邮箱)
|
||||||
"""
|
"""
|
||||||
user = await get_current_user(request)
|
user = await get_current_user(request)
|
||||||
if user["user_type"] != "admin":
|
if user["user_type"] != "admin":
|
||||||
return error_response(message="仅管理员可绑定邮箱", code=403)
|
return error_response(message="仅管理员可绑定邮箱", code=403)
|
||||||
result = await AuthService.bind_email(
|
result = await AuthService.send_bind_email_code(
|
||||||
user_id=user["user_id"],
|
user_id=user["user_id"],
|
||||||
password=req.password,
|
password=req.password,
|
||||||
email=req.email
|
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"]:
|
if result["success"]:
|
||||||
return success_response(data={"email": result.get("email")}, message=result["message"])
|
return success_response(data={"email": result.get("email")}, message=result["message"])
|
||||||
return error_response(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="新密码")
|
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(..., 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="当前密码")
|
password: str = Field(..., min_length=1, max_length=50, description="当前密码")
|
||||||
email: str = Field(default="", max_length=100, description="新邮箱(留空解除绑定)")
|
|
||||||
@@ -131,7 +131,6 @@ class AuthService:
|
|||||||
"role": role,
|
"role": role,
|
||||||
"permissions": permissions,
|
"permissions": permissions,
|
||||||
"group": group_info,
|
"group": group_info,
|
||||||
"email": user.get("email"),
|
|
||||||
"need_change_password": user["need_change_password"] == 1,
|
"need_change_password": user["need_change_password"] == 1,
|
||||||
"redirect": redirect
|
"redirect": redirect
|
||||||
}
|
}
|
||||||
@@ -191,7 +190,6 @@ class AuthService:
|
|||||||
"username": user["username"],
|
"username": user["username"],
|
||||||
"real_name": user["real_name"],
|
"real_name": user["real_name"],
|
||||||
"user_type": user["user_type"],
|
"user_type": user["user_type"],
|
||||||
"email": user.get("email"),
|
|
||||||
"need_change_password": user["need_change_password"] == 1
|
"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["role"] = group.get("group_name") or group.get("role_type")
|
||||||
result["permissions"] = group.get("permissions_data", {})
|
result["permissions"] = group.get("permissions_data", {})
|
||||||
result["group"] = _build_group_info(group)
|
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
|
return result
|
||||||
|
|
||||||
@@ -232,8 +236,14 @@ class AuthService:
|
|||||||
await RedisClient.set(limit_key, "1", expire=60)
|
await RedisClient.set(limit_key, "1", expire=60)
|
||||||
|
|
||||||
user = await UserModel.get_by_username(username)
|
user = await UserModel.get_by_username(username)
|
||||||
if not user or user.get("user_type") != "admin" or not user.get("email"):
|
if not user or user.get("user_type") != "admin":
|
||||||
logger.info(f"找回密码请求未发送(账号不存在/非管理员/未绑定邮箱): {username}, IP={ip}")
|
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
|
return generic_success
|
||||||
|
|
||||||
# 生成一次性令牌,并作废该用户此前的令牌
|
# 生成一次性令牌,并作废该用户此前的令牌
|
||||||
@@ -260,7 +270,7 @@ class AuthService:
|
|||||||
</div>
|
</div>
|
||||||
"""
|
"""
|
||||||
ok, message_text = await EmailSender.send(
|
ok, message_text = await EmailSender.send(
|
||||||
user["email"],
|
bound_email,
|
||||||
f"{settings.APP_NAME} - 密码重置",
|
f"{settings.APP_NAME} - 密码重置",
|
||||||
html_body
|
html_body
|
||||||
)
|
)
|
||||||
@@ -319,30 +329,122 @@ class AuthService:
|
|||||||
return {"success": True, "message": "密码重置成功,请使用新密码登录"}
|
return {"success": True, "message": "密码重置成功,请使用新密码登录"}
|
||||||
|
|
||||||
@staticmethod
|
@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)
|
user = await UserModel.get_by_user_id(user_id)
|
||||||
if not user or user.get("user_type") != "admin":
|
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"])
|
is_valid, _ = security.verify_password_v2(password, user["password_hash"])
|
||||||
if not is_valid:
|
if not is_valid:
|
||||||
return {"success": False, "message": "当前密码错误"}
|
return None, "当前密码错误"
|
||||||
|
return user, None
|
||||||
|
|
||||||
normalized_email = (email or "").strip() or None
|
@staticmethod
|
||||||
if normalized_email and not is_valid_email(normalized_email):
|
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": "系统未配置邮件服务,请联系班主任或系统管理员"}
|
||||||
|
|
||||||
|
_, 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": "邮箱格式不正确"}
|
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)
|
updated = await UserModel.update_email(user_id, normalized_email)
|
||||||
if not updated:
|
if not updated:
|
||||||
return {"success": False, "message": "邮箱更新失败"}
|
return {"success": False, "message": "邮箱绑定失败"}
|
||||||
|
|
||||||
logger.info(f"用户[{user_id}] 更新绑定邮箱: {normalized_email or '(解除绑定)'}")
|
await RedisClient.delete(f"email_bind_code:{user_id}")
|
||||||
return {
|
logger.info(f"用户[{user_id}] 邮箱绑定成功: {normalized_email}")
|
||||||
"success": True,
|
return {"success": True, "message": "邮箱绑定成功", "email": normalized_email}
|
||||||
"message": "邮箱绑定成功" if normalized_email else "邮箱已解除绑定",
|
|
||||||
"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
|
@staticmethod
|
||||||
def _get_redirect_path(user_type: str, role: str = None) -> str:
|
def _get_redirect_path(user_type: str, role: str = None) -> str:
|
||||||
|
|||||||
@@ -39,7 +39,7 @@
|
|||||||
- **撤销记录**:历史记录页或学生个人查询页 → 点击撤销按钮
|
- **撤销记录**:历史记录页或学生个人查询页 → 点击撤销按钮
|
||||||
- **导入学生**:学生管理页 → 导入学生(JSON格式,需包含 `student_no` 和 `name`)
|
- **导入学生**:学生管理页 → 导入学生(JSON格式,需包含 `student_no` 和 `name`)
|
||||||
- **添加班干部**:管理员管理页 → 添加管理员 → 填写账号信息、绑定邮箱(选填)并选择权限组
|
- **添加班干部**:管理员管理页 → 添加管理员 → 填写账号信息、绑定邮箱(选填)并选择权限组
|
||||||
- **绑定邮箱/找回密码**:修改密码页 → 绑定邮箱;忘记密码时在登录页点击"忘记密码?"通过邮箱重置
|
- **绑定邮箱/找回密码**:修改密码页 → 输入新邮箱+当前密码 → 发送验证码 → 输入验证码确认绑定;忘记密码时在登录页点击"忘记密码?"通过邮箱获取一次性重置链接
|
||||||
- **重置班干部密码**:管理员管理页 → 重置密码 → 输入新密码
|
- **重置班干部密码**:管理员管理页 → 重置密码 → 输入新密码
|
||||||
- **权限组管理**:管理员管理页 → 新建/编辑权限组 → 勾选功能权限并配置加分/扣分上限
|
- **权限组管理**:管理员管理页 → 新建/编辑权限组 → 勾选功能权限并配置加分/扣分上限
|
||||||
- **导出学生名单**:学生管理页 → 导出学生名单 → 勾选字段 → 开始导出
|
- **导出学生名单**:学生管理页 → 导出学生名单 → 勾选字段 → 开始导出
|
||||||
|
|||||||
+7
-2
@@ -315,14 +315,19 @@
|
|||||||
- 输入原密码和新密码
|
- 输入原密码和新密码
|
||||||
- 新密码需符合密码强度要求
|
- 新密码需符合密码强度要求
|
||||||
- 修改成功后需重新登录
|
- 修改成功后需重新登录
|
||||||
- 页面下方可**绑定邮箱**(需输入当前密码):绑定后忘记密码时可在登录页自助申请重置邮件;留空保存则解除绑定
|
- 页面下方可**绑定邮箱**(找回密码用):
|
||||||
|
1. 输入新邮箱和当前密码,点击"发送验证码"
|
||||||
|
2. 系统通过 SMTP 向该邮箱发送6位验证码(10分钟内有效)
|
||||||
|
3. 输入验证码后点击"确认绑定"
|
||||||
|
4. 点击"解除绑定"可解除已绑定邮箱(需当前密码)
|
||||||
|
- 管理员管理页添加/编辑账号时也可由班主任直接填写绑定邮箱
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 常见问题
|
## 常见问题
|
||||||
|
|
||||||
### Q: 忘记密码怎么办?
|
### Q: 忘记密码怎么办?
|
||||||
1. 已在管理端绑定邮箱的账号:在登录页点击"忘记密码?",输入用户名,系统会向绑定邮箱发送重置链接(30分钟内有效);
|
1. 已绑定邮箱的账号:在登录页点击"忘记密码?",输入用户名,系统会向绑定邮箱发送**一次性重置链接**(30分钟内有效、仅可使用一次);
|
||||||
2. 班主任账号或未绑定邮箱的账号:请联系系统管理员,通过数据库/调试接口重置。
|
2. 班主任账号或未绑定邮箱的账号:请联系系统管理员,通过数据库/调试接口重置。
|
||||||
|
|
||||||
### Q: 如何导出全班德育分记录?
|
### Q: 如何导出全班德育分记录?
|
||||||
|
|||||||
+70
-12
@@ -49,24 +49,32 @@ include __DIR__ . '/../includes/header.php';
|
|||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-title">绑定邮箱(找回密码)</div>
|
<div class="card-title">绑定邮箱(找回密码)</div>
|
||||||
<p style="font-size:13px; color:var(--color-text-secondary); margin-bottom:12px;">
|
<p style="font-size:13px; color:var(--color-text-secondary); margin-bottom:12px;">
|
||||||
绑定邮箱后,忘记密码时可在登录页通过“忘记密码”向该邮箱发送重置链接。
|
绑定邮箱需通过邮箱验证码验证;忘记密码时可在登录页通过该邮箱获取一次性重置链接。
|
||||||
</p>
|
</p>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>当前绑定邮箱</label>
|
<label>当前绑定邮箱</label>
|
||||||
<div id="currentEmail"><?php echo $bound_email ? htmlspecialchars($bound_email) : '未绑定'; ?></div>
|
<div id="currentEmail"><?php echo $bound_email ? htmlspecialchars($bound_email) : '未绑定'; ?></div>
|
||||||
</div>
|
</div>
|
||||||
<form id="emailForm">
|
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>新邮箱</label>
|
<label>新邮箱</label>
|
||||||
<input type="email" id="bindEmail" maxlength="100" placeholder="留空则解除绑定">
|
<input type="email" id="bindEmail" maxlength="100" placeholder="请输入要绑定的邮箱">
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label>当前密码 <span style="color:red;">*</span></label>
|
<label>当前密码 <span style="color:red;">*</span></label>
|
||||||
<input type="password" id="emailPassword" required>
|
<input type="password" id="emailPassword">
|
||||||
<small>安全验证:绑定邮箱需要输入当前登录密码</small>
|
<small>安全验证:发送验证码需要输入当前登录密码</small>
|
||||||
|
</div>
|
||||||
|
<div style="display:flex; gap:8px; flex-wrap:wrap;">
|
||||||
|
<button type="button" class="btn btn-secondary" onclick="sendBindEmailCode()">发送验证码</button>
|
||||||
|
</div>
|
||||||
|
<div class="form-group" style="margin-top:16px;">
|
||||||
|
<label>邮箱验证码</label>
|
||||||
|
<input type="text" id="emailCode" maxlength="6" inputmode="numeric" placeholder="请输入6位验证码">
|
||||||
|
</div>
|
||||||
|
<div style="display:flex; gap:8px; flex-wrap:wrap;">
|
||||||
|
<button type="button" class="btn btn-primary" onclick="confirmBindEmail()">确认绑定</button>
|
||||||
|
<button type="button" class="btn btn-outline-danger" onclick="unbindEmail()">解除绑定</button>
|
||||||
</div>
|
</div>
|
||||||
<button type="submit" class="btn btn-primary">保存邮箱</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -101,28 +109,78 @@ document.getElementById('passwordForm').addEventListener('submit', async (e) =>
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('emailForm').addEventListener('submit', async (e) => {
|
async function sendBindEmailCode() {
|
||||||
e.preventDefault();
|
|
||||||
const email = document.getElementById('bindEmail').value.trim();
|
const email = document.getElementById('bindEmail').value.trim();
|
||||||
const password = document.getElementById('emailPassword').value;
|
const password = document.getElementById('emailPassword').value;
|
||||||
|
if (!email) {
|
||||||
|
showToast('请输入要绑定的邮箱', 'warning');
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (!password) {
|
if (!password) {
|
||||||
showToast('请输入当前密码', 'warning');
|
showToast('请输入当前密码', 'warning');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const res = await apiPost('/api/auth/bind-email', {
|
const res = await apiPost('/api/auth/email/send-code', {
|
||||||
password: password,
|
password: password,
|
||||||
email: email
|
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) {
|
if (res && res.success) {
|
||||||
const bound = res.data && res.data.email ? res.data.email : '';
|
const bound = res.data && res.data.email ? res.data.email : '';
|
||||||
document.getElementById('currentEmail').textContent = bound || '未绑定';
|
document.getElementById('currentEmail').textContent = bound || '未绑定';
|
||||||
document.getElementById('bindEmail').value = '';
|
document.getElementById('bindEmail').value = '';
|
||||||
document.getElementById('emailPassword').value = '';
|
document.getElementById('emailPassword').value = '';
|
||||||
showToast(res.message || '邮箱保存成功');
|
document.getElementById('emailCode').value = '';
|
||||||
|
showToast(res.message || '邮箱绑定成功');
|
||||||
} else {
|
} 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');
|
||||||
|
}
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
<?php include __DIR__ . '/../includes/footer.php'; ?>
|
||||||
Reference in new issue
Block a user