""" 邮箱验证码路由 """ import re from fastapi import APIRouter, HTTPException from pydantic import BaseModel from app.services.email_service import email_code_service router = APIRouter(prefix="/api/email", tags=["邮箱验证码"]) EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") class SendEmailCodeRequest(BaseModel): email: str scene: str = "register" # register / login / reset_password @router.post("/send-code") async def send_email_code(body: SendEmailCodeRequest): """发送邮箱验证码""" email = body.email.strip().lower() if not EMAIL_RE.match(email): raise HTTPException(status_code=400, detail="邮箱格式不正确") ok, msg = await email_code_service.send_code(email, body.scene) if not ok: raise HTTPException(status_code=429, detail=msg) return {"code": 200, "message": msg} class VerifyEmailCodeRequest(BaseModel): email: str email_code: str @router.post("/verify-code") async def verify_email_code(body: VerifyEmailCodeRequest): """验证邮箱验证码(不删除,供两步流程第一步使用)""" email = body.email.strip().lower() if not EMAIL_RE.match(email): raise HTTPException(status_code=400, detail="邮箱格式不正确") ok = await email_code_service.verify_code(email, body.email_code, delete_after=False) if not ok: raise HTTPException(status_code=400, detail="验证码错误或已过期") return {"code": 200, "message": "验证成功"}