from __future__ import annotations import secrets from fastapi import APIRouter, Depends, HTTPException, Request from pydantic import BaseModel, Field 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 import vip_web_bridge as bridge from ebook_svc.services.wxpay import code2session router = APIRouter(prefix="/auth", tags=["auth"]) # 兼容旧 import 路径 __all__ = ["router", "get_current_openid", "LoginBody"] VIP_BOOK_ID = "__vip__" class VipWebLoginBody(BaseModel): email: str | None = Field(default=None, max_length=200) password: str | None = Field(default=None, max_length=200) user_id: str | None = Field(default=None, max_length=80) class VipWebBindBody(BaseModel): email: str = Field(min_length=3, max_length=200) password: str = Field(min_length=6, max_length=200) @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) user = store.get_user(openid) or {} return { "ok": True, "openid": openid, "onlineWindowSec": store.ONLINE_WINDOW_SEC, "isVip": store.is_unlocked(openid, VIP_BOOK_ID), "vipEmailBound": bool((user.get("vip_email") or "").strip()), "bridgeEnabled": bridge.bridge_enabled(), } @router.get("/vip-bridge-status") async def vip_bridge_status(openid: str = Depends(get_current_openid)): """只读:桥接开关 + 当前用户绑定状态(不写库)。""" user = store.get_user(openid) or {} return { "ok": True, "bridgeEnabled": bridge.bridge_enabled(), "isVip": store.is_unlocked(openid, VIP_BOOK_ID), "vipEmail": (user.get("vip_email") or "").strip() or None, "webUserId": (user.get("web_user_id") or "").strip() or None, "vipEmailBound": bool((user.get("vip_email") or "").strip()), } @router.post("/vip-web-login") async def vip_web_login( body: VipWebLoginBody, request: Request, openid: str = Depends(get_current_openid), ): """已有 Web VIP:邮箱密码只读校验 → 仅给当前 openid 写入本地 __vip__。 不修改 web/PB 既有会员数据;失败不写库。 """ rate_limit(request, bucket="auth.vip_web_login", limit=12, window_sec=60.0) if not bridge.bridge_enabled(): raise HTTPException(503, "Web 账号打通未开启") if store.is_blocked(openid): raise HTTPException(403, "账号不可用") email = (body.email or "").strip().lower() password = (body.password or "").strip() user_id = (body.user_id or "").strip() if email and password: result = await bridge.check_web_vip_by_email( email, password, user_id=user_id or None, wechat_userid=openid, ) elif user_id: result = await bridge.check_web_vip_by_user_id(user_id) else: raise HTTPException(400, "请填写邮箱密码,或输入会员账号") if not result.get("vip"): raise HTTPException(401, str(result.get("error") or "验证失败")) # 仅本机当前 openid:发会员权益(幂等 upsert) store.grant_unlock(openid, VIP_BOOK_ID, source="web_vip_login") bound_email = str(result.get("email") or email or "").strip().lower() web_uid = ( (result.get("anonymousUserId") or result.get("effectiveUserId") or user_id or "") or bridge.openid_to_web_user_id(openid) ) try: store.ensure_web_user_id(openid, str(web_uid)) if bound_email: store.set_vip_email_bound(openid, bound_email, str(web_uid)) except Exception: pass return { "ok": True, "isVip": True, "email": bound_email or None, "source": "web_vip_login", } @router.post("/vip-bind-email") async def vip_bind_email( body: VipWebBindBody, request: Request, openid: str = Depends(get_current_openid), ): """小程序已是 VIP 时绑定邮箱,便于反向登录 Web。 安全:邮箱已是 Web 会员则拒绝(引导走 vip-web-login),不覆盖他人绑定。 """ rate_limit(request, bucket="auth.vip_bind_email", limit=8, window_sec=60.0) if not bridge.bridge_enabled(): raise HTTPException(503, "Web 账号打通未开启") if store.is_blocked(openid): raise HTTPException(403, "账号不可用") if not store.is_unlocked(openid, VIP_BOOK_ID): raise HTTPException(403, "请先开通小程序 VIP 再绑定邮箱") user = store.get_user(openid) or {} if (user.get("vip_email") or "").strip(): return { "ok": True, "alreadyBound": True, "email": (user.get("vip_email") or "").strip(), "isVip": True, } web_uid = store.ensure_web_user_id(openid, bridge.openid_to_web_user_id(openid)) linked = await bridge.link_email_on_web(body.email, body.password, web_uid) if not linked.get("ok"): # alreadyVip:可直接走登录打通,仍不覆盖 web 数据 if linked.get("alreadyVip"): login = await bridge.check_web_vip_by_email( body.email, body.password, wechat_userid=openid ) if login.get("vip"): store.grant_unlock(openid, VIP_BOOK_ID, source="web_vip_login") email = str(login.get("email") or body.email).strip().lower() store.set_vip_email_bound(openid, email, web_uid) return { "ok": True, "isVip": True, "email": email, "source": "web_vip_login", "note": "邮箱已是 Web 会员,已打通小程序", } raise HTTPException(400, str(linked.get("error") or "绑定失败")) email = str(linked.get("email") or body.email).strip().lower() store.set_vip_email_bound(openid, email, web_uid) return { "ok": True, "isVip": True, "email": email, "webUserId": web_uid, "source": "weapp_bind_email", }