无密码账号验证码登录后强制设置密码
- 登录/注册/me 接口返回 has_password 标志 - 新增 POST /api/auth/set-password:登录态直接设密码(无需邮箱验证码) - 前端:has_password=false 的用户登录后弹出不可关闭的设置密码层,设置成功才能进入应用 - 测试 +4(47/47):标志返回、端点鉴权、改密生效、旧密码失效
This commit is contained in:
+25
-1
@@ -144,6 +144,8 @@ def user_public(row: Any, *, include_contact: bool = False) -> dict:
|
||||
}
|
||||
if include_contact:
|
||||
result.update(email=row["email"], phone=row["phone"] if "phone" in row.keys() else "")
|
||||
# 前端据此判断是否强制引导设置密码(老账号可能只有验证码登录)
|
||||
result["has_password"] = bool(row["password_hash"] if "password_hash" in row.keys() else False)
|
||||
return result
|
||||
|
||||
|
||||
@@ -399,6 +401,18 @@ class LoginIn(BaseModel):
|
||||
return self
|
||||
|
||||
|
||||
class SetPasswordIn(BaseModel):
|
||||
"""登录态下设置/修改密码:只需要新密码本身,不需要邮箱验证码(当前会话即凭据)。"""
|
||||
password: str = Field(min_length=10, max_length=128)
|
||||
confirm_password: str = Field(min_length=10, max_length=128)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def passwords_match(self):
|
||||
if self.password != self.confirm_password:
|
||||
raise ValueError("两次输入的密码不一致")
|
||||
return self
|
||||
|
||||
|
||||
class ResetPasswordIn(PasswordCodeIn):
|
||||
email: str = Field(max_length=255)
|
||||
|
||||
@@ -966,7 +980,7 @@ async def register(payload: RegisterIn, request: Request, db: AsyncSession = Dep
|
||||
"token": token,
|
||||
"user": {"id": user_id, "username": username, "display_name": display_name,
|
||||
"department": payload.department.strip(), "email": payload.email,
|
||||
"phone": payload.phone, "bio": "", "created_at": stamp},
|
||||
"phone": payload.phone, "bio": "", "created_at": stamp, "has_password": True},
|
||||
}
|
||||
|
||||
|
||||
@@ -1013,6 +1027,16 @@ async def login(payload: LoginIn, request: Request, db: AsyncSession = Depends(g
|
||||
return {"token": token, "user": user_public(user, include_contact=True)}
|
||||
|
||||
|
||||
@app.post("/api/auth/set-password")
|
||||
async def set_password(payload: SetPasswordIn, user: dict = Depends(current_user), db: AsyncSession = Depends(get_db)) -> dict:
|
||||
"""登录态下设置/修改密码:无需邮箱验证码(当前会话即凭据)。
|
||||
无密码老账号验证码登录后,前端会强制引导到这里。"""
|
||||
password_hash = await asyncio.to_thread(hash_password, payload.password)
|
||||
await db.execute(update(users).where(users.c.id == user["id"]).values(password_hash=password_hash))
|
||||
await db.commit()
|
||||
return {"ok": True, "has_password": True}
|
||||
|
||||
|
||||
@app.post("/api/auth/reset-password")
|
||||
async def reset_password(payload: ResetPasswordIn, request: Request, db: AsyncSession = Depends(get_db)) -> dict:
|
||||
await _auth_limit(db, "verify-ip:" + _client_ip(request), 60)
|
||||
|
||||
Reference in New Issue
Block a user