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>
75 lines
2.3 KiB
Python
75 lines
2.3 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)}
|
||
|
||
|
||
@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__"),
|
||
}
|