330 lines
12 KiB
Python
330 lines
12 KiB
Python
"""
|
||
meetup 加入流程:check-user、ensure-user、complete-order
|
||
供 cnomadcna 等前端调用,当 /api/* 代理到 payjsapi 时使用
|
||
"""
|
||
import logging
|
||
import time
|
||
|
||
import requests
|
||
from fastapi import APIRouter, HTTPException
|
||
from pydantic import BaseModel
|
||
|
||
from ..config import PB_URL, PB_ADMIN_EMAIL, PB_ADMIN_PASSWORD
|
||
|
||
router = APIRouter(prefix="/api/meetup", tags=["meetup"])
|
||
DEFAULT_PASSWORD = "12345678" # PocketBase 默认要求至少 8 位
|
||
|
||
# Admin token 缓存,避免每次请求都向 PocketBase 认证(PB 远程时易超时)
|
||
_ADMIN_TOKEN_CACHE: tuple[str, float] | None = None
|
||
_TOKEN_CACHE_TTL = 300 # 5 分钟
|
||
|
||
|
||
def _get_admin_token() -> tuple[str | None, str | None]:
|
||
"""返回 (token, error_detail)。token 为 None 时 error_detail 为失败原因。带 5 分钟缓存。"""
|
||
global _ADMIN_TOKEN_CACHE
|
||
now = time.time()
|
||
if _ADMIN_TOKEN_CACHE and _ADMIN_TOKEN_CACHE[1] > now:
|
||
return _ADMIN_TOKEN_CACHE[0], None
|
||
|
||
if not PB_ADMIN_EMAIL or not PB_ADMIN_PASSWORD:
|
||
return None, "PB_ADMIN_EMAIL 或 PB_ADMIN_PASSWORD 未配置"
|
||
base = (PB_URL or "").rstrip("/")
|
||
# PocketBase v0.23+ 使用 _superusers,旧版用 admins
|
||
for path in ["/api/collections/_superusers/auth-with-password", "/api/admins/auth-with-password"]:
|
||
try:
|
||
r = requests.post(
|
||
f"{base}{path}",
|
||
json={"identity": PB_ADMIN_EMAIL, "password": PB_ADMIN_PASSWORD},
|
||
timeout=4,
|
||
)
|
||
if r.status_code == 200:
|
||
data = r.json()
|
||
token = data.get("token")
|
||
if token:
|
||
_ADMIN_TOKEN_CACHE = (token, now + _TOKEN_CACHE_TTL)
|
||
return token, None
|
||
if r.status_code == 404:
|
||
continue # 尝试下一个路径
|
||
try:
|
||
msg = r.json().get("message", r.text[:100])
|
||
except Exception:
|
||
msg = r.text[:100]
|
||
logging.warning(f"PocketBase admin auth failed: status={r.status_code}, msg={msg}")
|
||
return None, f"PocketBase 管理员认证失败: {msg}"
|
||
except requests.exceptions.ConnectionError as e:
|
||
logging.error(f"PocketBase 连接失败: {e}")
|
||
return None, f"无法连接 {PB_URL},请检查网络或 PB_URL"
|
||
except Exception as e:
|
||
logging.warning(f"PocketBase auth try {path}: {e}")
|
||
return None, "PocketBase 管理员认证失败: 请确认 PB_URL 及管理员账号密码正确"
|
||
|
||
|
||
class CheckUserRequest(BaseModel):
|
||
email: str
|
||
|
||
|
||
class EnsureUserRequest(BaseModel):
|
||
email: str
|
||
password: str | None = None
|
||
|
||
|
||
def _check_site_vip(user_id: str, site_id: str = "meetup", token: str | None = None) -> bool:
|
||
"""检查用户是否有有效 site_vip(未过期)。可传入 token 避免重复认证。"""
|
||
if not token:
|
||
token, _ = _get_admin_token()
|
||
if not token:
|
||
return False
|
||
try:
|
||
from datetime import datetime
|
||
|
||
r = requests.get(
|
||
f"{PB_URL}/api/collections/site_vip/records",
|
||
params={
|
||
"filter": f'user_id = "{user_id}" && site_id = "{site_id}"',
|
||
"perPage": 1,
|
||
"sort": "-expires_at",
|
||
},
|
||
headers={"Authorization": f"Bearer {token}"},
|
||
timeout=4,
|
||
)
|
||
if r.status_code != 200:
|
||
return False
|
||
data = r.json()
|
||
items = data.get("items") or []
|
||
if not items:
|
||
return False
|
||
rec = items[0]
|
||
exp = rec.get("expires_at")
|
||
if not exp:
|
||
return True
|
||
try:
|
||
from datetime import datetime as _dt, timezone
|
||
|
||
exp_dt = _dt.fromisoformat(exp.replace("Z", "+00:00"))
|
||
now = _dt.now(timezone.utc)
|
||
if exp_dt.tzinfo is None:
|
||
exp_dt = exp_dt.replace(tzinfo=timezone.utc)
|
||
return exp_dt > now
|
||
except Exception:
|
||
return True
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
@router.post("/check-user")
|
||
async def check_user(item: CheckUserRequest):
|
||
"""检查邮箱是否已在 users 表存在,以及 VIP 状态(新/老用户判断)"""
|
||
email = (item.email or "").strip()
|
||
if not email:
|
||
raise HTTPException(status_code=400, detail="请输入邮箱")
|
||
|
||
token, err = _get_admin_token()
|
||
if not token:
|
||
raise HTTPException(status_code=500, detail=f"服务配置错误:{err}")
|
||
|
||
try:
|
||
filter_val = f'email="{email}"'
|
||
r = requests.get(
|
||
f"{PB_URL}/api/collections/users/records",
|
||
params={"filter": filter_val, "perPage": 1},
|
||
headers={"Authorization": f"Bearer {token}"},
|
||
timeout=4,
|
||
)
|
||
if r.status_code != 200:
|
||
raise HTTPException(status_code=500, detail="查询失败")
|
||
data = r.json()
|
||
items = data.get("items") or []
|
||
exists = len(items) > 0
|
||
user_id = items[0].get("id") if items else None
|
||
vip = _check_site_vip(user_id, "meetup", token) if user_id else False
|
||
return {"ok": True, "exists": exists, "vip": vip, "user_id": user_id}
|
||
except HTTPException:
|
||
raise
|
||
except Exception as e:
|
||
logging.error(f"check-user error: {e}")
|
||
raise HTTPException(status_code=500, detail="操作失败")
|
||
|
||
|
||
@router.post("/ensure-user")
|
||
async def ensure_user(item: EnsureUserRequest):
|
||
"""确保用户存在:老用户验证密码,新用户用默认密码 12345678 创建"""
|
||
email = (item.email or "").strip()
|
||
if not email:
|
||
raise HTTPException(status_code=400, detail="请输入邮箱")
|
||
|
||
password = (item.password or "").strip() or DEFAULT_PASSWORD
|
||
|
||
try:
|
||
# 尝试用密码登录
|
||
login_r = requests.post(
|
||
f"{PB_URL}/api/collections/users/auth-with-password",
|
||
json={"identity": email, "password": password},
|
||
timeout=10,
|
||
)
|
||
if login_r.status_code == 200:
|
||
data = login_r.json()
|
||
return {
|
||
"ok": True,
|
||
"user_id": data.get("record", {}).get("id"),
|
||
"token": data.get("token"),
|
||
"record": data.get("record"),
|
||
"is_new": False,
|
||
}
|
||
|
||
try:
|
||
err_data = login_r.json()
|
||
except Exception:
|
||
err_data = {}
|
||
is_not_found = login_r.status_code == 400 and (
|
||
"Invalid" in str(err_data.get("message", ""))
|
||
or "identity" in str(err_data.get("message", "")).lower()
|
||
)
|
||
if not is_not_found and item.password:
|
||
raise HTTPException(status_code=400, detail="密码错误")
|
||
|
||
# 新用户:创建
|
||
token, err = _get_admin_token()
|
||
if not token:
|
||
raise HTTPException(status_code=500, detail=f"服务配置错误:{err}")
|
||
|
||
create_r = requests.post(
|
||
f"{PB_URL}/api/collections/users/records",
|
||
json={
|
||
"email": email,
|
||
"password": DEFAULT_PASSWORD,
|
||
"passwordConfirm": DEFAULT_PASSWORD,
|
||
"live_allowed": True,
|
||
},
|
||
headers={
|
||
"Content-Type": "application/json",
|
||
"Authorization": f"Bearer {token}",
|
||
},
|
||
timeout=10,
|
||
)
|
||
if create_r.status_code != 200:
|
||
try:
|
||
create_err = create_r.json()
|
||
except Exception:
|
||
create_err = {}
|
||
data = create_err.get("data", {})
|
||
if (
|
||
create_r.status_code == 400
|
||
and "already" in str(data.get("email", {}).get("message", "")).lower()
|
||
):
|
||
raise HTTPException(status_code=400, detail="该邮箱已注册,请输入密码登录")
|
||
msg = create_err.get("message", "创建账号失败")
|
||
logging.warning(f"ensure-user create failed: status={create_r.status_code}, msg={msg}, data={data}")
|
||
raise HTTPException(status_code=500, detail=msg)
|
||
|
||
# 登录新用户
|
||
final_r = requests.post(
|
||
f"{PB_URL}/api/collections/users/auth-with-password",
|
||
json={"identity": email, "password": DEFAULT_PASSWORD},
|
||
timeout=10,
|
||
)
|
||
if final_r.status_code != 200:
|
||
raise HTTPException(status_code=500, detail="登录失败")
|
||
|
||
auth_data = final_r.json()
|
||
return {
|
||
"ok": True,
|
||
"user_id": auth_data.get("record", {}).get("id"),
|
||
"token": auth_data.get("token"),
|
||
"record": auth_data.get("record"),
|
||
"is_new": True,
|
||
}
|
||
except HTTPException:
|
||
raise
|
||
except Exception as e:
|
||
logging.error(f"ensure-user error: {e}")
|
||
raise HTTPException(status_code=500, detail="操作失败")
|
||
|
||
|
||
def _decode_pending_email(user_id: str) -> str | None:
|
||
if not user_id.startswith("pending_"):
|
||
return None
|
||
try:
|
||
return bytes.fromhex(user_id[8:]).decode("utf-8")
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
def _query_zpay_paid(order_id: str) -> bool:
|
||
"""查询 ZPAY 订单是否已支付"""
|
||
try:
|
||
from ..payment import get_payment_provider
|
||
from ..payment.zpay import ZPayProvider
|
||
provider = get_payment_provider()
|
||
if not isinstance(provider, ZPayProvider):
|
||
return False
|
||
result = provider.query_order_status(order_id, timeout=10)
|
||
return bool(result.get("paid"))
|
||
except Exception as e:
|
||
logging.warning(f"complete-order zpay query failed: {e}")
|
||
return False
|
||
|
||
|
||
@router.post("/complete-order")
|
||
async def complete_order(item: dict):
|
||
"""
|
||
支付成功后完成订单:验证订单、为新用户同步 session。
|
||
支持 pending_ 订单(新用户)和已存在用户订单(user_id 为 PB id)。
|
||
异步通知可能晚于用户回跳,故在 site_vip 未找到时轮询重试(ZPAY 已确认支付时)。
|
||
"""
|
||
order_id = (item.get("order_id") or "").strip()
|
||
if not order_id:
|
||
raise HTTPException(status_code=400, detail="缺少 order_id")
|
||
|
||
base = (PB_URL or "").rstrip("/")
|
||
token, err = _get_admin_token()
|
||
if not token:
|
||
raise HTTPException(status_code=500, detail=f"服务配置错误:{err}")
|
||
|
||
from ..services.payment import parse_order_id
|
||
|
||
user_id, pay_type = parse_order_id(order_id)
|
||
if not user_id or pay_type != "meetup":
|
||
raise HTTPException(status_code=400, detail="订单格式无效")
|
||
|
||
# 验证订单:site_vip 中需存在该 order_id(异步通知可能晚于用户回跳,ZPAY 已支付时轮询重试)
|
||
max_retries = 4
|
||
for attempt in range(max_retries):
|
||
r = requests.get(
|
||
f"{base}/api/collections/site_vip/records",
|
||
params={"filter": f'order_id = "{order_id}"', "perPage": 1},
|
||
headers={"Authorization": f"Bearer {token}"},
|
||
timeout=10,
|
||
)
|
||
total = (r.json().get("totalItems") or 0) if r.status_code == 200 else 0
|
||
if total > 0:
|
||
break
|
||
if attempt < max_retries - 1 and _query_zpay_paid(order_id):
|
||
time.sleep(2)
|
||
continue
|
||
resp_preview = r.text[:200] if r.ok else f"status={r.status_code}"
|
||
logging.warning(f"complete-order 未找到订单: order_id={order_id}, attempt={attempt + 1}, pb_resp={resp_preview}")
|
||
raise HTTPException(status_code=400, detail="订单不存在或未支付成功")
|
||
|
||
# pending_ 新用户:用邮箱+默认密码登录返回 token
|
||
if user_id.startswith("pending_"):
|
||
email = _decode_pending_email(user_id)
|
||
if not email:
|
||
raise HTTPException(status_code=400, detail="订单格式无效")
|
||
login_r = requests.post(
|
||
f"{base}/api/collections/users/auth-with-password",
|
||
json={"identity": email, "password": DEFAULT_PASSWORD},
|
||
timeout=10,
|
||
)
|
||
if login_r.status_code != 200:
|
||
raise HTTPException(status_code=500, detail="登录失败,请稍后重试")
|
||
auth_data = login_r.json()
|
||
return {
|
||
"ok": True,
|
||
"token": auth_data.get("token"),
|
||
"record": auth_data.get("record"),
|
||
"is_new": True,
|
||
}
|
||
|
||
# 已存在用户(PB user_id):订单已验证,返回 ok,前端已有 session 则无需 token
|
||
return {"ok": True, "token": None, "record": None, "is_new": False}
|