nomadro/apps/api/services/ebook_svc/routers/auth.py
Eric 017008dd7c Harden weapp/API P0 paths: VIP auth, ebook login, WAL limits, game stub.
Drop Three from weapp game, mount VIP library on unified API, and auto-enable local debug without manual .env.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-11 19:06:50 +08:00

78 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from __future__ import annotations
import secrets
from fastapi import APIRouter, Depends, HTTPException, Request
from ebook_svc.core.deps import get_current_openid
from ebook_svc.core.rate_limit import rate_limit
from ebook_svc.schemas.auth import LoginBody
from ebook_svc.services.pocketbase import pb
from ebook_svc.services.store import store
from ebook_svc.services.wxpay import code2session
router = APIRouter(prefix="/auth", tags=["auth"])
# 兼容旧 import 路径
__all__ = ["router", "get_current_openid", "LoginBody"]
@router.post("/login")
async def login(body: LoginBody, request: Request):
from ebook_svc.services.track import ingest_events
rate_limit(request, bucket="auth.login", limit=30, window_sec=60.0)
try:
data = await code2session(body.code)
except Exception as e:
await ingest_events(
[{"name": "login_fail", "label": "code2session", "props": {"msg": str(e)[:120]}}],
openid=None,
client="api",
)
raise HTTPException(400, str(e)) from e
openid = data["openid"]
session_key = data.get("session_key") or ""
token = secrets.token_urlsafe(24)
store.upsert_user(openid, session_key, token, data.get("unionid"))
user = store.get_user(openid)
if user and (user.get("status") or "active") == "blocked":
await ingest_events(
[{"name": "login_fail", "label": "blocked", "props": {"openid": openid[:8]}}],
openid=openid,
client="api",
)
raise HTTPException(403, "账号不可用")
try:
if user:
rid = await pb.upsert_wx_reader(user)
if rid and rid != user.get("pb_record_id"):
store.set_user_pb_id(openid, rid)
except Exception:
pass
await ingest_events(
[
{
"name": "login_ok",
"label": "api",
"props": {"session_ready": bool(session_key)},
}
],
openid=openid,
client="api",
)
return {"openid": openid, "token": token, "session_ready": bool(session_key)}
@router.post("/presence")
async def presence_ping(openid: str = Depends(get_current_openid)):
"""小程序前台心跳:刷新 last_seen,并带回 isVip 供端上近实时刷新会员态。"""
store.touch_last_seen(openid)
return {
"ok": True,
"openid": openid,
"onlineWindowSec": store.ONLINE_WINDOW_SEC,
"isVip": store.is_unlocked(openid, "__vip__"),
}