"""Web VIP ↔ 小程序打通(独立路由,不改现有 auth.py)。 安全:默认关;登录只读校验 Web;只给当前 openid 写本地 unlock / 映射列。 """ from __future__ import annotations import time from fastapi import APIRouter, Depends, HTTPException, Request from pydantic import BaseModel, Field from ebook_svc.core.deps import get_current_openid from ebook_svc.services import vip_web_bridge as bridge from ebook_svc.services.store import store router = APIRouter(prefix="/auth", tags=["vip-bridge"]) 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) def _ensure_bridge_columns() -> None: """仅 ADD COLUMN,不改既有行。""" try: with store.conn() as c: cols = {r[1] for r in c.execute("PRAGMA table_info(users)").fetchall()} for name, sql in ( ("vip_email", "ALTER TABLE users ADD COLUMN vip_email TEXT"), ("web_user_id", "ALTER TABLE users ADD COLUMN web_user_id TEXT"), ("vip_email_bound_at", "ALTER TABLE users ADD COLUMN vip_email_bound_at REAL"), ): if name not in cols: c.execute(sql) except Exception: pass def _ensure_web_user_id(openid: str, web_user_id: str) -> str: _ensure_bridge_columns() if hasattr(store, "ensure_web_user_id"): return store.ensure_web_user_id(openid, web_user_id) user = store.get_user(openid) or {} existing = (user.get("web_user_id") or "").strip() if existing: return existing with store.conn() as c: c.execute( "UPDATE users SET web_user_id=?, updated_at=? WHERE openid=?", (web_user_id, time.time(), openid), ) return web_user_id def _set_vip_email_bound(openid: str, email: str, web_user_id: str | None = None) -> None: _ensure_bridge_columns() if hasattr(store, "set_vip_email_bound"): store.set_vip_email_bound(openid, email, web_user_id) return email = (email or "").strip().lower() with store.conn() as c: if web_user_id: c.execute( """ UPDATE users SET vip_email=?, web_user_id=COALESCE(web_user_id, ?), vip_email_bound_at=?, updated_at=? WHERE openid=? """, (email, web_user_id, time.time(), time.time(), openid), ) else: c.execute( """ UPDATE users SET vip_email=?, vip_email_bound_at=?, updated_at=? WHERE openid=? """, (email, time.time(), time.time(), openid), ) @router.get("/vip-bridge-status") async def vip_bridge_status(openid: str = Depends(get_current_openid)): _ensure_bridge_columns() 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), ): 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 "验证失败")) 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: _ensure_web_user_id(openid, str(web_uid)) if bound_email: _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), ): 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 再绑定邮箱") _ensure_bridge_columns() 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 = _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"): 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() _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() _set_vip_email_bound(openid, email, web_uid) return { "ok": True, "isVip": True, "email": email, "webUserId": web_uid, "source": "weapp_bind_email", }