nomadro/apps/api/services/ebook_svc/routers/auth.py
Eric d0262eb58d Ship WeChat audit mode, package-size fixes, and live VIP switches.
Harden weapp for review: silent audit book, no flashy module defaults, safe-area PX, subpackages/lazyCodeLoading, and CDN nav icons. Document pre3 and move next work to pre4.

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

75 lines
2.3 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
from ebook_svc.core.deps import get_current_openid
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):
from ebook_svc.services.track import ingest_events
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__"),
}