Files
gsfdc/server/app/api/site/auth.py
T
wuzilongandCursor 2074a45681 feat: 增加会员服务与估价模版智能体
会员服务改为固定栏目,首页在线服务不再进入报告审核。估价模版智能体可多会话制作模版并下载,下载过程显示加载状态。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-23 13:36:19 +08:00

186 lines
6.8 KiB
Python

from datetime import datetime, timezone
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.core.deps import require_agent
from app.core.security import create_access_token
from app.db import get_db
from app.models.agent_user import find_login_account, load_agent_actor, presented_credential_version
from app.models.member import create_member, get_member_by_email, set_member_password
from app.services.login_guard import clear_failures, is_currently_locked, record_failure
from app.services.email_code import (
consume_email_code,
is_valid_email,
issue_email_code,
normalize_email,
)
from app.services.password import hash_password, validate_password, verify_password
router = APIRouter()
class EmailCodeRequest(BaseModel):
email: str
purpose: str
class RegisterRequest(BaseModel):
email: str
code: str
password: str
privacyAccepted: bool = False
class LoginRequest(BaseModel):
email: str
password: str
code: str | None = None
class AgentLoginRequest(BaseModel):
username: str
password: str
class ResetPasswordRequest(BaseModel):
email: str
code: str
password: str
def _bad(detail: str) -> None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=detail)
@router.post("/auth/email-code")
def send_email_code(body: EmailCodeRequest, db: Session = Depends(get_db)) -> dict:
purpose = (body.purpose or "").strip()
email = normalize_email(body.email)
if purpose not in {"register", "login", "reset"}:
_bad("验证码用途不正确")
if not is_valid_email(email):
_bad("邮箱格式不正确")
existing = get_member_by_email(db, email)
if purpose == "register" and existing is not None:
_bad("该邮箱已注册")
if purpose in {"login", "reset"} and existing is None:
_bad("该邮箱尚未注册")
if purpose in {"login", "reset"} and existing is not None and existing.status != "active":
_bad("账号不可用")
try:
issue_email_code(email=email, purpose=purpose)
except ValueError as exc:
_bad(str(exc))
return {"ok": True}
@router.post("/auth/register")
def register(body: RegisterRequest, db: Session = Depends(get_db)) -> dict:
email = normalize_email(body.email)
if not is_valid_email(email):
_bad("邮箱格式不正确")
if not body.privacyAccepted:
_bad("请先阅读并同意隐私政策")
if get_member_by_email(db, email) is not None:
_bad("该邮箱已注册")
# 先校验密码,避免弱密码拒收时已消费验证码,用户改密后无法再用同一码。
validate_password(body.password)
if not consume_email_code(email=email, purpose="register", code=body.code):
_bad("验证码不正确或已过期")
member = create_member(
db,
email=email,
password_hash=hash_password(body.password),
privacy_accepted_at=datetime.now(timezone.utc).replace(tzinfo=None),
)
token = create_access_token(str(member.id), "member")
return {"accessToken": token, "tokenType": "member", "email": member.email}
@router.post("/auth/login")
def login(body: LoginRequest, db: Session = Depends(get_db)) -> dict:
email = normalize_email(body.email)
if not is_valid_email(email):
_bad("邮箱格式不正确")
member = get_member_by_email(db, email)
if member is None or member.status != "active":
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="邮箱或密码不正确")
if body.code is not None and str(body.code).strip():
if not consume_email_code(email=email, purpose="login", code=body.code):
_bad("验证码不正确或已过期")
if not verify_password(body.password, member.password_hash):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="邮箱或密码不正确")
token = create_access_token(str(member.id), "member")
return {"accessToken": token, "tokenType": "member", "email": member.email}
AGENT_LOGIN_FAILURE = "用户名或密码错误"
def _reject_agent_login(db: Session, user, *, record: bool) -> None:
if record and user is not None:
record_failure(db, user)
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=AGENT_LOGIN_FAILURE)
@router.post("/auth/agent-login")
def agent_login(body: AgentLoginRequest, db: Session = Depends(get_db)) -> dict:
found = find_login_account(db, body.username)
if found is None:
_reject_agent_login(db, None, record=False)
kind, user, allowed = found
if is_currently_locked(user):
_reject_agent_login(db, user, record=False)
if not verify_password(body.password, user.password_hash):
_reject_agent_login(db, user, record=True)
if user.status != "active":
_reject_agent_login(db, user, record=True)
if not allowed:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="该账号未开通智能体登录")
clear_failures(db, user)
subject = f"s:{user.id}" if kind == "staff" else f"m:{user.id}"
username = user.username if kind == "staff" else user.email
display_name = user.display_name if kind == "staff" else user.email.split("@", 1)[0]
token = create_access_token(subject, "agent", version=int(getattr(user, "credential_epoch", 0) or 0))
return {
"accessToken": token,
"tokenType": "agent",
"username": username,
"displayName": display_name or username,
}
@router.get("/auth/agent/me")
def agent_me(principal: dict = Depends(require_agent), db: Session = Depends(get_db)) -> dict:
try:
actor = load_agent_actor(
db,
str(principal.get("sub") or ""),
credential_version=presented_credential_version(principal),
)
except LookupError as exc:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="登录已失效") from exc
return {
"username": actor.username,
"displayName": actor.display_name,
"canManage": actor.can_manage,
}
@router.post("/auth/reset-password")
def reset_password(body: ResetPasswordRequest, db: Session = Depends(get_db)) -> dict:
email = normalize_email(body.email)
if not is_valid_email(email):
_bad("邮箱格式不正确")
member = get_member_by_email(db, email)
if member is None or member.status != "active":
_bad("该邮箱尚未注册")
validate_password(body.password)
if not consume_email_code(email=email, purpose="reset", code=body.code):
_bad("验证码不正确或已过期")
set_member_password(db, member, hash_password(body.password))
token = create_access_token(str(member.id), "member")
return {"accessToken": token, "tokenType": "member", "email": member.email}