Refresh audience/admin UX, ntfy/track, social paths, and replace ebook chapters with the expanded catalog; keep local SQLite and one-off probe scripts out of tree. Co-authored-by: Cursor <cursoragent@cursor.com>
341 lines
12 KiB
Python
341 lines
12 KiB
Python
from __future__ import annotations
|
||
|
||
import secrets
|
||
|
||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||
from pydantic import BaseModel, Field
|
||
|
||
from ebook_svc.config import settings
|
||
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 import oa_users as oa_svc
|
||
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)
|
||
|
||
|
||
class BindOaBody(BaseModel):
|
||
"""公众号私信 userid(OA openid),来自小程序 path ?userid="""
|
||
userid: str | None = Field(default=None, max_length=128)
|
||
wechat_userid: str | None = Field(default=None, max_length=128)
|
||
oa_userid: str | None = Field(default=None, max_length=128)
|
||
|
||
|
||
@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)}
|
||
|
||
|
||
def _oa_profile_payload(user: dict, profile: dict | None = None) -> dict:
|
||
oa_userid = (user.get("oa_userid") or "").strip()
|
||
p = profile or (store.get_oa_profile(oa_userid) if oa_userid else None) or {}
|
||
nick = (p.get("nick") or user.get("nickname") or "").strip()
|
||
avatar = (p.get("avatar") or user.get("avatar_url") or "").strip()
|
||
mp_appid = (user.get("oa_mp_appid") or p.get("mp_appid") or "").strip()
|
||
return {
|
||
"oaUserid": oa_userid or None,
|
||
"oaNick": nick or None,
|
||
"oaAvatar": avatar or None,
|
||
"oaSignature": (p.get("signature") or "").strip() or None,
|
||
"oaRegion": (p.get("region") or "").strip() or None,
|
||
"oaRemark": (p.get("remark") or "").strip() or None,
|
||
"oaFollowSince": (p.get("follow_since") or "").strip() or None,
|
||
"oaBoundAt": user.get("oa_bound_at"),
|
||
"oaMpAppid": mp_appid or None,
|
||
}
|
||
|
||
|
||
@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(),
|
||
**_oa_profile_payload(user),
|
||
}
|
||
|
||
|
||
@router.post("/bind-oa")
|
||
async def bind_oa_userid(
|
||
body: BindOaBody,
|
||
request: Request,
|
||
openid: str = Depends(get_current_openid),
|
||
):
|
||
"""强制绑定:公众号 userid ↔ 当前微信小程序 openid(按 AppID 隔离)。
|
||
|
||
同一小程序 AppID 下,该 OA userid 已被其他 openid 占用则 409;
|
||
不同小程序(A/B)openid 命名空间不同,互不抢绑。
|
||
"""
|
||
rate_limit(request, bucket="auth.bind_oa", limit=20, window_sec=60.0)
|
||
if store.is_blocked(openid):
|
||
raise HTTPException(403, "账号不可用")
|
||
oa_userid = (
|
||
(body.userid or body.wechat_userid or body.oa_userid or "")
|
||
.strip()
|
||
)
|
||
if not oa_userid or len(oa_userid) < 8:
|
||
raise HTTPException(400, "userid 无效")
|
||
|
||
mp_appid = (settings.wx_appid or "").strip()
|
||
if not mp_appid:
|
||
raise HTTPException(500, "小程序 AppID 未配置")
|
||
|
||
vip = oa_svc.fetch_vip_wechat_profile(oa_userid)
|
||
parsed = oa_svc.profile_from_vip_payload(vip, oa_userid)
|
||
nick = parsed.get("nick") or ""
|
||
avatar = parsed.get("avatar") or ""
|
||
try:
|
||
store.bind_oa_userid(
|
||
openid,
|
||
oa_userid,
|
||
nick=nick or None,
|
||
avatar=avatar or None,
|
||
mp_appid=mp_appid,
|
||
force=True,
|
||
)
|
||
except ValueError as e:
|
||
code = str(e)
|
||
if code == "oa_bound_other":
|
||
raise HTTPException(
|
||
409,
|
||
"该公众号参数已绑定其他用户,无法再次绑定",
|
||
) from e
|
||
if code == "oa_mp_appid_required":
|
||
raise HTTPException(500, "小程序 AppID 未配置") from e
|
||
raise HTTPException(400, code) from e
|
||
|
||
# 档案字段刷新(不再改写绑定归属;bind 已写 mp_openid/mp_appid)
|
||
if vip.get("found") or nick or avatar:
|
||
store.upsert_oa_profile(
|
||
{
|
||
"userid": oa_userid,
|
||
"nick": nick,
|
||
"avatar": avatar,
|
||
"raw_json": {
|
||
"vip_profile": vip.get("profile"),
|
||
"relations": vip.get("relations"),
|
||
"synced_at": oa_svc.now_ts(),
|
||
"mp_appid": mp_appid,
|
||
},
|
||
},
|
||
partial=True,
|
||
)
|
||
user = store.get_user(openid) or {}
|
||
profile = store.get_oa_profile(oa_userid)
|
||
return {
|
||
"ok": True,
|
||
"found": bool(vip.get("found")),
|
||
"openid": openid,
|
||
"mpAppid": mp_appid,
|
||
**_oa_profile_payload(user, profile),
|
||
"relations": parsed.get("relations") or {},
|
||
}
|
||
|
||
|
||
@router.get("/oa-profile")
|
||
async def get_oa_profile(openid: str = Depends(get_current_openid)):
|
||
"""当前登录用户的公众号档案(本地 + 可再拉 VIP)。"""
|
||
user = store.get_user(openid) or {}
|
||
return {"ok": True, "openid": openid, **_oa_profile_payload(user)}
|
||
|
||
|
||
@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",
|
||
}
|