200 lines
7.3 KiB
Python
200 lines
7.3 KiB
Python
|
|
"""账号:注册 / 登录 / 登出 / 资料。会话 token 白名单式存 Redis。"""
|
|||
|
|
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
from typing import Annotated
|
|||
|
|
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
|||
|
|
|
|||
|
|
from fastapi import APIRouter, Header, HTTPException, status
|
|||
|
|
from sqlalchemy import func, select
|
|||
|
|
|
|||
|
|
from app.api.deps import CurrentUser, SessionDep
|
|||
|
|
from app.core.security import (
|
|||
|
|
hash_password,
|
|||
|
|
new_token,
|
|||
|
|
normalize_web_login_code,
|
|||
|
|
token_hash,
|
|||
|
|
verify_password,
|
|||
|
|
)
|
|||
|
|
from app.models import User
|
|||
|
|
from app.schemas.auth import (
|
|||
|
|
LoginIn,
|
|||
|
|
LoginOut,
|
|||
|
|
OkOut,
|
|||
|
|
ProfileIn,
|
|||
|
|
QrLoginIn,
|
|||
|
|
RegisterIn,
|
|||
|
|
UserOut,
|
|||
|
|
user_out,
|
|||
|
|
)
|
|||
|
|
from app.services import astro, catalog, redis_store
|
|||
|
|
|
|||
|
|
router = APIRouter(tags=["auth"])
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _split_account(account: str) -> tuple[str | None, str | None]:
|
|||
|
|
a = account.strip()
|
|||
|
|
if "@" in a:
|
|||
|
|
return a.lower(), None
|
|||
|
|
digits = "".join(ch for ch in a if ch.isdigit() or ch == "+")
|
|||
|
|
return None, digits or None
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post("/auth/register", response_model=LoginOut, status_code=status.HTTP_201_CREATED)
|
|||
|
|
async def register(body: RegisterIn, db: SessionDep) -> LoginOut:
|
|||
|
|
email, phone = _split_account(body.account)
|
|||
|
|
if not email and not phone:
|
|||
|
|
raise HTTPException(400, "account must be an email or a phone number")
|
|||
|
|
|
|||
|
|
exists = await db.scalar(
|
|||
|
|
select(func.count()).select_from(User).where(
|
|||
|
|
(User.email == email) if email else (User.phone == phone)
|
|||
|
|
)
|
|||
|
|
)
|
|||
|
|
if exists:
|
|||
|
|
raise HTTPException(409, "account already registered")
|
|||
|
|
|
|||
|
|
# 第一个注册者成为管理员,省掉手工改库引导(后续可在管理端增删)
|
|||
|
|
total = await db.scalar(select(func.count()).select_from(User)) or 0
|
|||
|
|
|
|||
|
|
user = User(
|
|||
|
|
email=email,
|
|||
|
|
phone=phone,
|
|||
|
|
password_hash=hash_password(body.password),
|
|||
|
|
nickname=body.nickname or (email.split("@")[0] if email else f"用户{phone[-4:]}"),
|
|||
|
|
role="admin" if total == 0 else "user",
|
|||
|
|
)
|
|||
|
|
db.add(user)
|
|||
|
|
await db.commit()
|
|||
|
|
await db.refresh(user)
|
|||
|
|
|
|||
|
|
token = new_token()
|
|||
|
|
await redis_store.save_session(token_hash(token), str(user.id))
|
|||
|
|
return LoginOut(token=token, user=user_out(user, await catalog.zodiac_map(db)))
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post("/auth/login", response_model=LoginOut)
|
|||
|
|
async def login(body: LoginIn, db: SessionDep) -> LoginOut:
|
|||
|
|
email, phone = _split_account(body.account)
|
|||
|
|
user = await db.scalar(
|
|||
|
|
select(User).where((User.email == email) if email else (User.phone == phone))
|
|||
|
|
)
|
|||
|
|
# 统一错误文案,不暴露账号是否存在
|
|||
|
|
if user is None or not verify_password(body.password, user.password_hash):
|
|||
|
|
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "account or password incorrect")
|
|||
|
|
if user.status != "active":
|
|||
|
|
raise HTTPException(status.HTTP_403_FORBIDDEN, "account disabled")
|
|||
|
|
|
|||
|
|
token = new_token()
|
|||
|
|
await redis_store.save_session(token_hash(token), str(user.id))
|
|||
|
|
return LoginOut(token=token, user=user_out(user, await catalog.zodiac_map(db)))
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post("/auth/qr-login", response_model=LoginOut)
|
|||
|
|
async def qr_login(body: QrLoginIn, db: SessionDep) -> LoginOut:
|
|||
|
|
"""设备屏上二维码换会话:免密登录到该设备的绑定账号。
|
|||
|
|
|
|||
|
|
票据一码一用(取出即删),有效期 5 分钟;这样即使二维码被旁人拍到,
|
|||
|
|
也只有第一个打开的人能用,设备重开二维码会立刻换新码。
|
|||
|
|
"""
|
|||
|
|
code = normalize_web_login_code(body.code)
|
|||
|
|
payload = await redis_store.pop_web_login(code) if code else None
|
|||
|
|
if not payload:
|
|||
|
|
raise HTTPException(
|
|||
|
|
status.HTTP_401_UNAUTHORIZED,
|
|||
|
|
"二维码已失效,请在设备上重新打开",
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
user = await db.get(User, payload.get("user_id", ""))
|
|||
|
|
if user is None or user.status != "active":
|
|||
|
|
raise HTTPException(status.HTTP_403_FORBIDDEN, "account disabled")
|
|||
|
|
|
|||
|
|
token = new_token()
|
|||
|
|
await redis_store.save_session(token_hash(token), str(user.id))
|
|||
|
|
return LoginOut(token=token, user=user_out(user, await catalog.zodiac_map(db)))
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post("/auth/logout", response_model=OkOut)
|
|||
|
|
async def logout(authorization: Annotated[str | None, Header()] = None) -> OkOut:
|
|||
|
|
"""只清当前这条会话;同一账号在其它设备上的登录不受影响。"""
|
|||
|
|
raw = (authorization or "").strip()
|
|||
|
|
if raw.lower().startswith("bearer "):
|
|||
|
|
await redis_store.drop_session(token_hash(raw[7:].strip()))
|
|||
|
|
return OkOut(ok=True)
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.get("/user/profile", response_model=UserOut)
|
|||
|
|
async def get_profile(user: CurrentUser, db: SessionDep) -> UserOut:
|
|||
|
|
return user_out(user, await catalog.zodiac_map(db))
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.put("/user/profile", response_model=UserOut)
|
|||
|
|
async def update_profile(body: ProfileIn, user: CurrentUser, db: SessionDep) -> UserOut:
|
|||
|
|
data = body.model_dump(exclude_unset=True)
|
|||
|
|
|
|||
|
|
# 出生地/居住地:入参是码表 code,名字由码表反查后落库,前端不传名字
|
|||
|
|
birth_code_changed = "birth_region_code" in data
|
|||
|
|
if birth_code_changed:
|
|||
|
|
code = data.pop("birth_region_code")
|
|||
|
|
if code:
|
|||
|
|
city, place, _tz = await catalog.resolve_place(db, code)
|
|||
|
|
if place is None:
|
|||
|
|
raise HTTPException(400, "出生城市不在码表里")
|
|||
|
|
user.birth_region_code = code
|
|||
|
|
user.birth_city = city
|
|||
|
|
user.birth_place = place
|
|||
|
|
else:
|
|||
|
|
user.birth_region_code = None
|
|||
|
|
user.birth_city = None
|
|||
|
|
user.birth_place = None
|
|||
|
|
|
|||
|
|
if "residence_region_code" in data:
|
|||
|
|
code = data.pop("residence_region_code")
|
|||
|
|
if code:
|
|||
|
|
city, place, _tz = await catalog.resolve_place(db, code)
|
|||
|
|
if place is None:
|
|||
|
|
raise HTTPException(400, "居住城市不在码表里")
|
|||
|
|
user.residence_region_code = code
|
|||
|
|
user.residence_city = city
|
|||
|
|
user.residence_place = place
|
|||
|
|
else:
|
|||
|
|
user.residence_region_code = None
|
|||
|
|
user.residence_city = None
|
|||
|
|
user.residence_place = None
|
|||
|
|
|
|||
|
|
# 居住时区:必须是合法 IANA 名;星盘不受它影响(星盘用出生地时区)
|
|||
|
|
if "timezone" in data:
|
|||
|
|
tz = data["timezone"]
|
|||
|
|
if tz:
|
|||
|
|
try:
|
|||
|
|
ZoneInfo(tz)
|
|||
|
|
except ZoneInfoNotFoundError:
|
|||
|
|
raise HTTPException(400, f"未知时区:{tz}") from None
|
|||
|
|
user.timezone = tz or None
|
|||
|
|
|
|||
|
|
for k, v in data.items():
|
|||
|
|
setattr(user, k, v)
|
|||
|
|
|
|||
|
|
# 星盘:日期/时间/出生地任一变化都重算;没生日就清空
|
|||
|
|
if user.birthday is None:
|
|||
|
|
user.sun_sign = user.moon_sign = None
|
|||
|
|
user.sun_degree = user.moon_degree = None
|
|||
|
|
elif birth_code_changed or "birthday" in data or "birth_time" in data or not user.sun_sign:
|
|||
|
|
await _recompute_astro(db, user)
|
|||
|
|
|
|||
|
|
await db.commit()
|
|||
|
|
await db.refresh(user)
|
|||
|
|
return user_out(user, await catalog.zodiac_map(db))
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def _recompute_astro(db, user: User) -> None:
|
|||
|
|
"""月亮走得太快,时区差一小时就可能跨星座,所以强调「出生地」而不是「现在所在地」。"""
|
|||
|
|
tz = "Asia/Shanghai"
|
|||
|
|
if user.birth_region_code:
|
|||
|
|
_, _, tz = await catalog.resolve_place(db, user.birth_region_code)
|
|||
|
|
result = astro.compute(user.birthday, user.birth_time, tz)
|
|||
|
|
user.sun_sign = result.sun_sign
|
|||
|
|
user.moon_sign = result.moon_sign
|
|||
|
|
user.sun_degree = result.sun_degree
|
|||
|
|
user.moon_degree = result.moon_degree
|