46 lines
1.6 KiB
Python
46 lines
1.6 KiB
Python
from fastapi import APIRouter, HTTPException, status
|
|
|
|
from app.config import settings
|
|
from app.schemas.sms import SmsSendRequest, SmsVerifyRequest, SmsResponse
|
|
from app.services.sms import generate_and_send_sms, verify_sms_code
|
|
|
|
router = APIRouter(prefix="/sms", tags=["sms"])
|
|
|
|
|
|
@router.post("/send", response_model=SmsResponse)
|
|
async def send_sms_code(req: SmsSendRequest):
|
|
"""Send SMS verification code. Requires captcha_token in production."""
|
|
if not settings.SMS_MOCK:
|
|
if not req.captcha_token:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="需要验证码",
|
|
)
|
|
from app.services.auth import decode_access_token
|
|
token_sub = decode_access_token(req.captcha_token)
|
|
if not token_sub or not token_sub.startswith("captcha:"):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="验证码无效",
|
|
)
|
|
|
|
ok = await generate_and_send_sms(req.phone)
|
|
if not ok:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
detail="短信发送失败,请稍后重试",
|
|
)
|
|
return SmsResponse(message="验证码已发送", success=True)
|
|
|
|
|
|
@router.post("/verify", response_model=SmsResponse)
|
|
async def verify_sms(req: SmsVerifyRequest):
|
|
"""Verify SMS code."""
|
|
ok = await verify_sms_code(req.phone, req.code)
|
|
if not ok:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="验证码错误或已过期",
|
|
)
|
|
return SmsResponse(message="验证成功", success=True)
|