nomadro/apps/api/services/ebook_svc/routers/auth.py
eric 3e5b7c2098 Monorepo super-optimize: src layout, workspace scripts, docs.
Collapse portal under src/, unify pnpm workspace/scripts, thin VIP topic re-exports, drop orphan vip scaffolds and one-shot scripts, ignore xhs/release, document root commands.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-01 00:34:04 +08:00

63 lines
1.9 KiB
Python

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)}