|
| 1 | +"""用户名可用性检查端点。 |
| 2 | +
|
| 3 | +供注册页前端实时校验用户名是否可用,无需身份认证。 |
| 4 | +校验流程:格式合法性 → 保留名检查 → 唯一性查询。 |
| 5 | +""" |
| 6 | + |
| 7 | +from fastapi import APIRouter, Depends, Query |
| 8 | +from sqlalchemy import select |
| 9 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 10 | + |
| 11 | +from app.models.session import get_db |
| 12 | +from app.models.user import User |
| 13 | +from app.services.user.name_validator import ( |
| 14 | + is_name_reserved, |
| 15 | + validate_username_format, |
| 16 | +) |
| 17 | + |
| 18 | +router = APIRouter() |
| 19 | + |
| 20 | + |
| 21 | +@router.get("/username") |
| 22 | +async def check_username_availability( |
| 23 | + value: str = Query(..., min_length=3, max_length=64, description="待检查的用户名"), |
| 24 | + db: AsyncSession = Depends(get_db), |
| 25 | +): |
| 26 | + """检查用户名是否可用。 |
| 27 | +
|
| 28 | + 依次校验格式、保留名和唯一性,返回结果与不可用原因。 |
| 29 | + """ |
| 30 | + if not validate_username_format(value): |
| 31 | + return {"available": False, "reason": "用户名格式不合法"} |
| 32 | + if await is_name_reserved(value, db): |
| 33 | + return {"available": False, "reason": "该名称为系统保留名"} |
| 34 | + result = await db.execute(select(User.id).where(User.username == value)) |
| 35 | + if result.scalar_one_or_none() is not None: |
| 36 | + return {"available": False, "reason": "该用户名已被占用"} |
| 37 | + return {"available": True} |
0 commit comments