feat: Implement Supabase authentication, account management UI, and entitlement services.
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
"""Authentication and entitlement helpers."""
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from typing import Dict, Optional
|
||||
|
||||
import requests
|
||||
from loguru import logger
|
||||
|
||||
|
||||
def _env_bool(name: str, default: bool = False) -> bool:
|
||||
raw = os.getenv(name)
|
||||
if raw is None:
|
||||
return default
|
||||
return raw.strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _env_int(name: str, default: int) -> int:
|
||||
raw = os.getenv(name)
|
||||
if raw is None:
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except Exception:
|
||||
return default
|
||||
|
||||
|
||||
def extract_bearer_token(auth_header: Optional[str]) -> str:
|
||||
if not auth_header:
|
||||
return ""
|
||||
parts = str(auth_header).strip().split()
|
||||
if len(parts) == 2 and parts[0].lower() == "bearer":
|
||||
return parts[1].strip()
|
||||
return ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class SupabaseIdentity:
|
||||
user_id: str
|
||||
email: str
|
||||
|
||||
|
||||
class SupabaseEntitlementService:
|
||||
"""
|
||||
Supabase-backed authentication and entitlement checks.
|
||||
|
||||
- Auth validation: /auth/v1/user with user access token.
|
||||
- Entitlement check: /rest/v1/subscriptions with service role key.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.enabled = _env_bool("POLYWEATHER_AUTH_ENABLED", False)
|
||||
self.require_subscription = _env_bool(
|
||||
"POLYWEATHER_AUTH_REQUIRE_SUBSCRIPTION",
|
||||
False,
|
||||
)
|
||||
self.supabase_url = str(os.getenv("SUPABASE_URL") or "").strip().rstrip("/")
|
||||
self.anon_key = str(os.getenv("SUPABASE_ANON_KEY") or "").strip()
|
||||
self.service_role_key = str(os.getenv("SUPABASE_SERVICE_ROLE_KEY") or "").strip()
|
||||
self.timeout_sec = max(3, _env_int("SUPABASE_HTTP_TIMEOUT_SEC", 8))
|
||||
self.cache_ttl_sec = max(5, _env_int("SUPABASE_AUTH_CACHE_TTL_SEC", 30))
|
||||
self.sub_cache_ttl_sec = max(5, _env_int("SUPABASE_SUB_CACHE_TTL_SEC", 60))
|
||||
|
||||
self._identity_cache: Dict[str, Dict[str, object]] = {}
|
||||
self._identity_cache_lock = threading.Lock()
|
||||
self._sub_cache: Dict[str, Dict[str, object]] = {}
|
||||
self._sub_cache_lock = threading.Lock()
|
||||
|
||||
@property
|
||||
def configured(self) -> bool:
|
||||
return bool(self.supabase_url and self.anon_key)
|
||||
|
||||
def _user_endpoint(self) -> str:
|
||||
return f"{self.supabase_url}/auth/v1/user"
|
||||
|
||||
def _subscription_endpoint(self) -> str:
|
||||
return f"{self.supabase_url}/rest/v1/subscriptions"
|
||||
|
||||
def _request_headers_for_user(self, access_token: str) -> Dict[str, str]:
|
||||
return {
|
||||
"apikey": self.anon_key,
|
||||
"Authorization": f"Bearer {access_token}",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
def _request_headers_for_service_role(self) -> Dict[str, str]:
|
||||
return {
|
||||
"apikey": self.service_role_key,
|
||||
"Authorization": f"Bearer {self.service_role_key}",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
def get_identity(self, access_token: str) -> Optional[SupabaseIdentity]:
|
||||
if not access_token:
|
||||
return None
|
||||
|
||||
now_ts = time.time()
|
||||
with self._identity_cache_lock:
|
||||
cached = self._identity_cache.get(access_token)
|
||||
if cached and now_ts - float(cached.get("ts") or 0) < self.cache_ttl_sec:
|
||||
identity = cached.get("identity")
|
||||
if isinstance(identity, SupabaseIdentity):
|
||||
return identity
|
||||
|
||||
if not self.configured:
|
||||
return None
|
||||
|
||||
try:
|
||||
response = requests.get(
|
||||
self._user_endpoint(),
|
||||
headers=self._request_headers_for_user(access_token),
|
||||
timeout=self.timeout_sec,
|
||||
)
|
||||
if response.status_code != 200:
|
||||
return None
|
||||
data = response.json() if response.content else {}
|
||||
user_id = str(data.get("id") or "").strip()
|
||||
if not user_id:
|
||||
return None
|
||||
identity = SupabaseIdentity(
|
||||
user_id=user_id,
|
||||
email=str(data.get("email") or "").strip(),
|
||||
)
|
||||
with self._identity_cache_lock:
|
||||
self._identity_cache[access_token] = {
|
||||
"identity": identity,
|
||||
"ts": now_ts,
|
||||
}
|
||||
return identity
|
||||
except Exception as exc:
|
||||
logger.warning(f"supabase auth user check failed: {exc}")
|
||||
return None
|
||||
|
||||
def has_active_subscription(self, user_id: str) -> bool:
|
||||
if not self.require_subscription:
|
||||
return True
|
||||
if not user_id:
|
||||
return False
|
||||
if not self.service_role_key:
|
||||
logger.warning(
|
||||
"POLYWEATHER_AUTH_REQUIRE_SUBSCRIPTION=true but SUPABASE_SERVICE_ROLE_KEY is missing",
|
||||
)
|
||||
return False
|
||||
|
||||
now_ts = time.time()
|
||||
with self._sub_cache_lock:
|
||||
cached = self._sub_cache.get(user_id)
|
||||
if cached and now_ts - float(cached.get("ts") or 0) < self.sub_cache_ttl_sec:
|
||||
return bool(cached.get("active"))
|
||||
|
||||
try:
|
||||
now_iso = datetime.now(timezone.utc).isoformat()
|
||||
params = {
|
||||
"select": "id,user_id,status,expires_at",
|
||||
"user_id": f"eq.{user_id}",
|
||||
"status": "eq.active",
|
||||
"expires_at": f"gt.{now_iso}",
|
||||
"order": "expires_at.desc",
|
||||
"limit": "1",
|
||||
}
|
||||
response = requests.get(
|
||||
self._subscription_endpoint(),
|
||||
headers=self._request_headers_for_service_role(),
|
||||
params=params,
|
||||
timeout=self.timeout_sec,
|
||||
)
|
||||
if response.status_code != 200:
|
||||
logger.warning(
|
||||
"supabase subscription query failed user_id={} status={}",
|
||||
user_id,
|
||||
response.status_code,
|
||||
)
|
||||
active = False
|
||||
else:
|
||||
data = response.json() if response.content else []
|
||||
active = isinstance(data, list) and len(data) > 0
|
||||
|
||||
with self._sub_cache_lock:
|
||||
self._sub_cache[user_id] = {
|
||||
"active": active,
|
||||
"ts": now_ts,
|
||||
}
|
||||
return active
|
||||
except Exception as exc:
|
||||
logger.warning(f"supabase subscription query error user_id={user_id}: {exc}")
|
||||
return False
|
||||
|
||||
|
||||
SUPABASE_ENTITLEMENT = SupabaseEntitlementService()
|
||||
|
||||
@@ -25,12 +25,27 @@ class CommandGuard:
|
||||
if decision.allowed:
|
||||
return True
|
||||
|
||||
self.io_layer.bot.reply_to(
|
||||
message,
|
||||
(
|
||||
if decision.reason == "bind_required":
|
||||
denial_text = (
|
||||
"🔒 当前指令需要订阅权限。\n"
|
||||
"请先绑定账号后再试:\n"
|
||||
"<code>/bind <supabase_user_id> [email]</code>"
|
||||
)
|
||||
elif decision.reason in {"supabase_subscription_required", "premium_required"}:
|
||||
denial_text = (
|
||||
"🔒 当前指令需要高级权限。\n"
|
||||
"请先开通订阅后再使用。"
|
||||
),
|
||||
)
|
||||
else:
|
||||
denial_text = (
|
||||
"🔒 当前指令需要高级权限。\n"
|
||||
"请先开通订阅后再使用。"
|
||||
)
|
||||
|
||||
self.io_layer.bot.reply_to(
|
||||
message,
|
||||
denial_text,
|
||||
parse_mode="HTML",
|
||||
)
|
||||
logger.info(
|
||||
"bot entitlement blocked command={} user_id={} reason={}",
|
||||
@@ -44,4 +59,3 @@ class CommandGuard:
|
||||
if not self.ensure_entitled(message, command_label):
|
||||
return False
|
||||
return self.io_layer.ensure_query_points(message, cost, command_label)
|
||||
|
||||
|
||||
@@ -36,6 +36,10 @@ class BasicCommandHandler:
|
||||
def _diag(message):
|
||||
self.handle_diag(message)
|
||||
|
||||
@self.bot.message_handler(commands=["bind"])
|
||||
def _bind(message):
|
||||
self.handle_bind(message)
|
||||
|
||||
def handle_start_help(self, message: Any) -> None:
|
||||
trace = CommandTrace("/start", message)
|
||||
try:
|
||||
@@ -73,3 +77,46 @@ class BasicCommandHandler:
|
||||
trace.set_status("ok")
|
||||
finally:
|
||||
trace.emit()
|
||||
|
||||
def handle_bind(self, message: Any) -> None:
|
||||
trace = CommandTrace("/bind", message)
|
||||
try:
|
||||
parts = (message.text or "").split(maxsplit=2)
|
||||
if len(parts) < 2:
|
||||
self.bot.reply_to(
|
||||
message,
|
||||
(
|
||||
"❌ 用法:\n"
|
||||
"<code>/bind <supabase_user_id> [email]</code>\n\n"
|
||||
"示例:\n"
|
||||
"<code>/bind 11111111-2222-3333-4444-555555555555 user@example.com</code>"
|
||||
),
|
||||
parse_mode="HTML",
|
||||
)
|
||||
trace.set_status("bad_request", "missing_supabase_user_id")
|
||||
return
|
||||
|
||||
supabase_user_id = str(parts[1] or "").strip()
|
||||
if len(supabase_user_id) < 8:
|
||||
self.bot.reply_to(message, "❌ supabase_user_id 格式不正确。")
|
||||
trace.set_status("bad_request", "invalid_supabase_user_id")
|
||||
return
|
||||
supabase_email = str(parts[2] or "").strip() if len(parts) >= 3 else ""
|
||||
user = message.from_user
|
||||
self.io_layer.db.upsert_user(user.id, self.io_layer.display_name(user))
|
||||
self.io_layer.db.bind_supabase_identity(
|
||||
telegram_id=user.id,
|
||||
supabase_user_id=supabase_user_id,
|
||||
supabase_email=supabase_email,
|
||||
)
|
||||
self.bot.reply_to(
|
||||
message,
|
||||
(
|
||||
"✅ 账号绑定完成。\n"
|
||||
f"supabase_user_id: <code>{supabase_user_id}</code>"
|
||||
),
|
||||
parse_mode="HTML",
|
||||
)
|
||||
trace.set_status("ok")
|
||||
finally:
|
||||
trace.emit()
|
||||
|
||||
@@ -59,6 +59,7 @@ class BotIOLayer:
|
||||
"/top - 查看积分排行榜\n"
|
||||
"/id - 获取当前聊天的 Chat ID\n\n"
|
||||
"/diag - 查看 Bot 启动诊断\n\n"
|
||||
"/bind - 绑定 Supabase 账号(可选)\n\n"
|
||||
"示例: <code>/city 伦敦</code>\n"
|
||||
f"💡 <i>提示: 每日签到(有效发言满 {MESSAGE_MIN_LENGTH} 字)获得 <b>{MESSAGE_POINTS}</b> 积分,"
|
||||
f"每日上限 {MESSAGE_DAILY_CAP} 分。</i>"
|
||||
|
||||
@@ -4,6 +4,7 @@ import os
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable, Set
|
||||
|
||||
from src.auth.supabase_entitlement import SUPABASE_ENTITLEMENT
|
||||
from src.database.db_manager import DBManager
|
||||
|
||||
|
||||
@@ -36,6 +37,10 @@ class BotEntitlementService:
|
||||
):
|
||||
self.db = db
|
||||
self.enabled = _env_bool("POLYWEATHER_BOT_REQUIRE_ENTITLEMENT", False) if enabled is None else enabled
|
||||
self.use_supabase = _env_bool(
|
||||
"POLYWEATHER_BOT_USE_SUPABASE_ENTITLEMENT",
|
||||
SUPABASE_ENTITLEMENT.enabled,
|
||||
)
|
||||
commands = protected_commands or ("/city", "/deb")
|
||||
self.protected_commands: Set[str] = {str(c).strip().lower() for c in commands if str(c).strip()}
|
||||
|
||||
@@ -47,8 +52,15 @@ class BotEntitlementService:
|
||||
return EntitlementDecision(True, "command_not_protected")
|
||||
|
||||
user = self.db.get_user(user_id) or {}
|
||||
if self.use_supabase:
|
||||
supabase_user_id = str(user.get("supabase_user_id") or "").strip()
|
||||
if not supabase_user_id:
|
||||
return EntitlementDecision(False, "bind_required")
|
||||
if SUPABASE_ENTITLEMENT.has_active_subscription(supabase_user_id):
|
||||
return EntitlementDecision(True, "supabase_subscription_active")
|
||||
return EntitlementDecision(False, "supabase_subscription_required")
|
||||
|
||||
has_premium = bool(user.get("is_web_premium") or user.get("is_group_premium"))
|
||||
if has_premium:
|
||||
return EntitlementDecision(True, "premium_user")
|
||||
return EntitlementDecision(False, "premium_required")
|
||||
|
||||
|
||||
@@ -45,6 +45,8 @@ class DBManager:
|
||||
""")
|
||||
self._ensure_column(conn, "users", "daily_points", "INTEGER DEFAULT 0")
|
||||
self._ensure_column(conn, "users", "daily_points_date", "TEXT")
|
||||
self._ensure_column(conn, "users", "supabase_user_id", "TEXT")
|
||||
self._ensure_column(conn, "users", "supabase_email", "TEXT")
|
||||
conn.commit()
|
||||
logger.info(f"Database initialized successfully path={self.db_path}")
|
||||
|
||||
@@ -85,6 +87,23 @@ class DBManager:
|
||||
""", (telegram_id, username))
|
||||
conn.commit()
|
||||
|
||||
def bind_supabase_identity(
|
||||
self,
|
||||
telegram_id: int,
|
||||
supabase_user_id: str,
|
||||
supabase_email: str = "",
|
||||
) -> None:
|
||||
with self._get_connection() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE users
|
||||
SET supabase_user_id = ?, supabase_email = ?
|
||||
WHERE telegram_id = ?
|
||||
""",
|
||||
(supabase_user_id.strip(), supabase_email.strip(), telegram_id),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
def add_message_activity(
|
||||
self,
|
||||
telegram_id: int,
|
||||
|
||||
Reference in New Issue
Block a user