Spaces:
Running
Running
Download app.py from Tonic/uas-eus-webhook: direct link, hf CLI and curl.
- Browser
- Download file 32.2 kB
-
https://huggingface.co/spaces/Tonic/uas-eus-webhook/resolve/main/app.py
- Command line
-
hf download hf://spaces/Tonic/uas-eus-webhook/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Tonic/uas-eus-webhook/resolve/main/app.py
32.2 kB
| """uas.eus webhook/auth/privacy API — runs as a PROTECTED HF docker Space (region:eu), at api.uas.eus. | |
| Endpoints: | |
| GET /health | |
| GET /auth/hf/callback Hugging Face OAuth2 (PKCE) callback -> JWT -> redirect to the site | |
| GET /api/me current session (Bearer JWT or httpOnly refresh cookie) | |
| GET /api/sim-token HMAC access token for the simulator pro areas (requires `pro`) | |
| POST /webhooks/revenuecat RevenueCat webhooks (signature-verified): license certs, kit orders, | |
| HF gated-repo grants on license purchase / removal on refund | |
| GET /privacy/export GDPR data export (JSON) | |
| DELETE /privacy/me GDPR erasure (RevenueCat + Stripe + HF grants + local purge) | |
| POST /admin/orders/{id}/status fulfillment status updates (owner, flashes the kit card locally) | |
| All secrets come from env / HF Space secrets — never from git: | |
| REVENUECAT_SECRET_KEY (sk_...) RC_WEBHOOK_SECRET HF_OAUTH_CLIENT_ID / HF_OAUTH_CLIENT_SECRET | |
| HF_ADMIN_TOKEN (write on Tonic repos) JWT_SECRET SIM_ACCESS_SECRET STRIPE_SECRET_KEY | |
| ADMIN_API_TOKEN SITE_BASE COOKIE_DOMAIN (e.g. .uas.eus; empty => token in URL fragment) | |
| """ | |
| import base64, hashlib, hmac, json, os, sqlite3, time | |
| from urllib.parse import urlencode | |
| import httpx | |
| from fastapi import FastAPI, Request, Response, HTTPException, Header | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import RedirectResponse, JSONResponse | |
| # ---------------------------------------------------------------- config | |
| REVENUECAT_SECRET_KEY = os.environ.get("REVENUECAT_SECRET_KEY", "") | |
| RC_WEBHOOK_SECRET = os.environ.get("RC_WEBHOOK_SECRET", "") | |
| HF_CLIENT_ID = os.environ.get("HF_OAUTH_CLIENT_ID", "") | |
| HF_CLIENT_SECRET = os.environ.get("HF_OAUTH_CLIENT_SECRET", "") | |
| HF_ADMIN_TOKEN = os.environ.get("HF_ADMIN_TOKEN", "") | |
| JWT_SECRET = os.environ.get("JWT_SECRET", "dev-insecure-change-me") | |
| SIM_ACCESS_SECRET = os.environ.get("SIM_ACCESS_SECRET", JWT_SECRET) | |
| STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY", "") | |
| ADMIN_API_TOKEN = os.environ.get("ADMIN_API_TOKEN", "") | |
| SITE_BASE = os.environ.get("SITE_BASE", "https://tonic-uas-eus.static.hf.space") | |
| ACCOUNT_PATH = os.environ.get("ACCOUNT_PATH", "/account.html") | |
| COOKIE_DOMAIN = os.environ.get("COOKIE_DOMAIN", "") # e.g. ".uas.eus" once DNS is ours | |
| POSTHOG_HOST = os.environ.get("POSTHOG_HOST", "https://eu.i.posthog.com") # EU cloud; or a self-hosted EU Space | |
| HF_TOKEN_URL = "https://huggingface.co/oauth/token" | |
| HF_WHOAMI = "https://huggingface.co/api/whoami-v2" | |
| RC_API = "https://api.revenuecat.com/v1" | |
| HF_API = "https://huggingface.co/api" | |
| DB = os.environ.get("DB_PATH", "webhook.db") | |
| ACCESS_TTL = 15 * 60 # 15 min | |
| REFRESH_TTL = 7 * 24 * 3600 # 7 d | |
| # SKUs that map to gated HF repos. PRO also buys licenses: a pro account gets the selected | |
| # model repos + code/demos repo + hosted simulator (sim gating is via /api/sim-token). | |
| SELECTED_MODEL_REPOS = [ | |
| "Tonic/detectonic-0.1.0-KTA", | |
| "Tonic/detectonic-1-KTA", | |
| "Tonic/detectonic-0.2.0-KTA", | |
| "Tonic/detectonic-2", | |
| ] | |
| CODE_REPOS = ["Tonic/detectonic-demos"] | |
| PRO_SKUS = {"pro_monthly", "pro_yearly"} | |
| LICENSE_SKU = "license_detectonic_selected" | |
| KIT_SKU = "testing_license_kit" | |
| HW_SKUS = {"hw_xiao_license", "hw_korvo_license"} | |
| LIVE_DEMO_SKUS = {"live_demo_2days", "live_demo_3days"} # 8000/day, client picks 2 or 3 days | |
| FULFILL_SKUS = HW_SKUS | {KIT_SKU} | LIVE_DEMO_SKUS # all delivered by post on selected hardware | |
| app = FastAPI(title="uas.eus api") | |
| _ALLOWED = [SITE_BASE, "https://uas.eus", "https://c.uas.eus", | |
| "https://tonic-uas-eus.static.hf.space", "https://tonic-c-uas-eus.static.hf.space"] | |
| _ALLOWED += [o.strip() for o in os.environ.get("ALLOWED_ORIGINS", "").split(",") if o.strip()] | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=_ALLOWED, | |
| allow_credentials=True, allow_methods=["GET", "POST", "DELETE"], allow_headers=["*"], | |
| ) | |
| # ---------------------------------------------------------------- db | |
| def db(): | |
| con = sqlite3.connect(DB) | |
| con.row_factory = sqlite3.Row | |
| con.execute("""CREATE TABLE IF NOT EXISTS users( | |
| hf_id TEXT PRIMARY KEY, name TEXT, email TEXT, rc_app_user_id TEXT, created REAL)""") | |
| con.execute("""CREATE TABLE IF NOT EXISTS orders( | |
| id TEXT PRIMARY KEY, app_user_id TEXT, sku TEXT, email TEXT, status TEXT, event TEXT, created REAL)""") | |
| con.execute("""CREATE TABLE IF NOT EXISTS state_nonces(nonce TEXT PRIMARY KEY, created REAL)""") | |
| con.execute("""CREATE TABLE IF NOT EXISTS seen_events(event_id TEXT PRIMARY KEY, seen REAL)""") | |
| con.execute("""CREATE TABLE IF NOT EXISTS order_notes(app_user_id TEXT, items TEXT, created REAL)""") | |
| con.execute("""CREATE TABLE IF NOT EXISTS events( | |
| id TEXT PRIMARY KEY, kind TEXT, title TEXT, start TEXT, location TEXT, capacity INTEGER)""") | |
| con.execute("""CREATE TABLE IF NOT EXISTS signups( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, event_id TEXT, kind TEXT, name TEXT, email TEXT, | |
| org TEXT, topic TEXT, id_ack INTEGER, created REAL)""") | |
| con.execute("""CREATE TABLE IF NOT EXISTS news( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT, title TEXT, body TEXT, link TEXT, site TEXT, created REAL)""") | |
| try: # migration for DBs created before the site column | |
| con.execute("ALTER TABLE news ADD COLUMN site TEXT") | |
| except sqlite3.OperationalError: | |
| pass | |
| con.execute("""CREATE TABLE IF NOT EXISTS contacts( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, email TEXT, org TEXT, | |
| reference TEXT, profile TEXT, message TEXT, site TEXT, created REAL)""") | |
| return con | |
| def seed_news(): | |
| """Seed news items; title/body are JSON maps {lang: text} (eu default, en fallback).""" | |
| con = db() | |
| n = con.execute("SELECT COUNT(*) c FROM news").fetchone()["c"] | |
| if n: | |
| con.close(); return | |
| import json as _json | |
| items = [ | |
| ("uas.eus", "2026-12-01", | |
| {"eu": "detectonic-2 argitaratu da (w9 prune, KTA)", "en": "detectonic-2 released (w9 prune, KTA)"}, | |
| {"eu": "Gated repoetan eskuragarri; ESP32-S31-n 1,311 s, 56/56 paritatea.", | |
| "en": "Available in the gated repos; ESP32-S31: 1.311 s, 56/56 parity."}, | |
| "https://huggingface.co/Tonic/detectonic-2"), | |
| ("uas.eus", "2026-11-28", | |
| {"eu": "Leaderboard: 129 neurri-erregistro", "en": "Leaderboard: 129 measurement rows"}, | |
| {"eu": "Komunitatearen neurketak, on-device atala barne.", "en": "Community measurements incl. the on-device tab."}, | |
| ""), | |
| ("uas.eus", "2026-11-20", | |
| {"eu": "Testing kit: 2.000 modelo + 2.000 lizentzia ($2.000)", "en": "Testing kit: 2,000 models + 2,000 licenses ($2,000)"}, | |
| {"eu": "Memoria-txartel batean, postaz bidalia. Proba/demoetarako bakarrik.", | |
| "en": "On one memory card, shipped by post. Testing/demo use only."}, | |
| ""), | |
| ("c.uas.eus", "2026-12-01", | |
| {"eu": "Tailerren hilabetea: San Donibane (erdigunea)", "en": "Monthly workshop: St. Jean-de-Luz (center)"}, | |
| {"eu": "Larunbatetan 14:00. Izena eman kalendarioan; NAN-a atean. Kokalekua egun berean iragarriko da.", | |
| "en": "Saturdays 14:00. Sign up in the calendar; ID at the door. Location announced the same day."}, | |
| ""), | |
| ("c.uas.eus", "2026-11-15", | |
| {"eu": "DroneAidekin lankidetzaren akordioa", "en": "DroneAid partnership agreement"}, | |
| {"eu": "Europako sarea: 12 herrialde, 17 hiri, 2.000+ prestatu. Dohaintzen %100 piezaketara.", | |
| "en": "European network: 12 countries, 17 cities, 2,000+ trained. 100% of donations buys parts."}, | |
| "https://droneaid.fr"), | |
| ("c.uas.eus", "2026-11-02", | |
| {"eu": "10 hazbeteko interzeptore bat egun bakarrean", "en": "A 10-inch interceptor in a single day"}, | |
| {"eu": "Muntaia tailerretan, eskuz. Hurrengo tailerra beheko kalendarioan.", | |
| "en": "Assembled by hand in our workshops. Next workshop in the calendar below."}, | |
| ""), | |
| ] | |
| for site, date, title, body, link in items: | |
| con.execute("INSERT INTO news(date,title,body,link,site,created) VALUES(?,?,?,?,?,?)", | |
| (date, _json.dumps(title, ensure_ascii=False), _json.dumps(body, ensure_ascii=False), | |
| link, site, time.time())) | |
| con.commit(); con.close() | |
| def seed_events(): | |
| """Seed volunteer workshops (St. Jean-de-Luz, Saturdays) and call slots (weekdays).""" | |
| con = db() | |
| n = con.execute("SELECT COUNT(*) c FROM events").fetchone()["c"] | |
| if n: | |
| con.close(); return | |
| now = time.time() | |
| import datetime as dt | |
| today = dt.date.today() | |
| # next 4 Saturdays 14:00 | |
| d = today + dt.timedelta(days=(5 - today.weekday()) % 7 or 7) | |
| for i in range(4): | |
| s = dt.datetime.combine(d + dt.timedelta(days=7 * i), dt.time(14, 0)) | |
| con.execute("INSERT INTO events(id,kind,title,start,location,capacity) VALUES(?,?,?,?,?,?)", | |
| (f"ws-{i}", "workshop", "Tailerra · interzeptoreak 10\"", s.isoformat(), | |
| "St. Jean-de-Luz (erdigunea) — kokalekua egun berean iragarriko da", 20)) | |
| # call slots: next 5 weekdays 10:00 / 15:00 | |
| d2 = today + dt.timedelta(days=1) | |
| j = 0 | |
| while j < 5: | |
| if d2.weekday() < 5: | |
| for h in (10, 15): | |
| s = dt.datetime.combine(d2, dt.time(h, 0)) | |
| con.execute("INSERT INTO events(id,kind,title,start,location,capacity) VALUES(?,?,?,?,?,?)", | |
| (f"call-{j}-{h}", "call", "Deia · salmenta/demoa", s.isoformat(), "online", 1)) | |
| j += 1 | |
| d2 += dt.timedelta(days=1) | |
| con.commit(); con.close() | |
| # ---------------------------------------------------------------- jwt/hmac helpers | |
| def b64u(b: bytes) -> str: | |
| return base64.urlsafe_b64encode(b).decode().rstrip("=") | |
| def b64u_decode(s: str) -> bytes: | |
| return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)) | |
| def sign(payload: dict, secret: str) -> str: | |
| body = b64u(json.dumps(payload, separators=(",", ":")).encode()) | |
| sig = b64u(hmac.new(secret.encode(), body.encode(), hashlib.sha256).digest()) | |
| return f"{body}.{sig}" | |
| def verify(token: str, secret: str) -> dict | None: | |
| try: | |
| body, sig = token.split(".") | |
| expect = b64u(hmac.new(secret.encode(), body.encode(), hashlib.sha256).digest()) | |
| if not hmac.compare_digest(expect, sig): | |
| return None | |
| payload = json.loads(b64u_decode(body)) | |
| if payload.get("exp", 0) < time.time(): | |
| return None | |
| return payload | |
| except Exception: | |
| return None | |
| def issue_jwt(hf_id: str, name: str, entitlements: list[str]) -> tuple[str, str]: | |
| now = time.time() | |
| access = sign({"sub": hf_id, "name": name, "ent": entitlements, "iat": now, "exp": now + ACCESS_TTL}, JWT_SECRET) | |
| refresh = sign({"sub": hf_id, "type": "refresh", "iat": now, "exp": now + REFRESH_TTL}, JWT_SECRET) | |
| return access, refresh | |
| def current_user(authorization: str | None, request: Request) -> dict | None: | |
| token = None | |
| if authorization and authorization.startswith("Bearer "): | |
| token = authorization[7:] | |
| if not token: | |
| token = request.cookies.get("uas_refresh") | |
| if not token: | |
| return None | |
| return verify(token, JWT_SECRET) | |
| async def rc_entitlements(app_user_id: str) -> list[str]: | |
| if not REVENUECAT_SECRET_KEY or not app_user_id: | |
| return [] | |
| async with httpx.AsyncClient(timeout=20) as c: | |
| r = await c.get(f"{RC_API}/subscribers/{app_user_id}", | |
| headers={"Authorization": f"Bearer {REVENUECAT_SECRET_KEY}"}) | |
| if r.status_code != 200: | |
| return [] | |
| subs = r.json().get("subscriber", {}).get("subscriptions", {}) | |
| ents = r.json().get("subscriber", {}).get("entitlements", {}) | |
| active = [k for k, v in ents.items() if v.get("is_active")] | |
| return sorted(set(active)) | |
| # ---------------------------------------------------------------- first-party PostHog proxy | |
| # Browsers talk only to api.uas.eus/posthog/* — no third-party requests/cookies (GDPR). | |
| async def posthog_proxy(path: str, request: Request): | |
| url = f"{POSTHOG_HOST}/{path}" | |
| if request.url.query: | |
| url += "?" + request.url.query | |
| body = await request.body() | |
| fwd = {k: v for k, v in request.headers.items() | |
| if k.lower() not in ("host", "content-length", "accept-encoding", "connection")} | |
| async with httpx.AsyncClient(timeout=20, follow_redirects=False) as c: | |
| r = await c.request(request.method, url, content=body, headers=fwd) | |
| hdrs = {k: v for k, v in r.headers.items() | |
| if k.lower() not in ("content-encoding", "transfer-encoding", "connection", "content-length")} | |
| return Response(content=r.content, status_code=r.status_code, headers=hdrs, | |
| media_type=r.headers.get("content-type")) | |
| # ---------------------------------------------------------------- health | |
| async def health(): | |
| return {"ok": True, "time": time.time()} | |
| # ---------------------------------------------------------------- HF OAuth callback | |
| async def hf_callback(code: str, state: str, request: Request): | |
| con = db() | |
| row = con.execute("SELECT created FROM state_nonces WHERE nonce=?", (state,)).fetchone() | |
| if not row or time.time() - row["created"] > 600: | |
| raise HTTPException(400, "bad state") | |
| con.execute("DELETE FROM state_nonces WHERE nonce=?", (state,)); con.commit() | |
| async with httpx.AsyncClient(timeout=30) as c: | |
| tok = await c.post(HF_TOKEN_URL, data={ | |
| "grant_type": "authorization_code", "code": code, | |
| "client_id": HF_CLIENT_ID, "client_secret": HF_CLIENT_SECRET, | |
| "redirect_uri": str(request.url_for("hf_callback")), | |
| }) | |
| if tok.status_code != 200: | |
| raise HTTPException(400, f"HF token exchange failed: {tok.text[:200]}") | |
| access_token = tok.json()["access_token"] | |
| who = await c.get(HF_WHOAMI, headers={"Authorization": f"Bearer {access_token}"}) | |
| if who.status_code != 200: | |
| raise HTTPException(400, "whoami failed") | |
| me = who.json() | |
| hf_id, name, email = str(me.get("id") or me.get("name")), me.get("name"), me.get("email") | |
| app_user_id = f"hf_{hf_id}" | |
| con.execute("INSERT INTO users(hf_id,name,email,rc_app_user_id,created) VALUES(?,?,?,?,?) " | |
| "ON CONFLICT(hf_id) DO UPDATE SET name=excluded.name, email=excluded.email", | |
| (hf_id, name, email, app_user_id, time.time())) | |
| con.commit(); con.close() | |
| ents = await rc_entitlements(app_user_id) | |
| access, refresh = issue_jwt(hf_id, name, ents) | |
| resp = RedirectResponse(f"{SITE_BASE}{ACCOUNT_PATH}") | |
| if COOKIE_DOMAIN: | |
| resp.set_cookie("uas_refresh", refresh, max_age=REFRESH_TTL, httponly=True, | |
| secure=True, samesite="lax", domain=COOKIE_DOMAIN) | |
| resp.set_cookie("uas_access", access, max_age=ACCESS_TTL, httponly=True, | |
| secure=True, samesite="lax", domain=COOKIE_DOMAIN) | |
| return resp | |
| # interim (hf.space, no shared cookie domain): token in the fragment, client keeps it in sessionStorage | |
| resp = RedirectResponse(f"{SITE_BASE}{ACCOUNT_PATH}#access_token={access}") | |
| return resp | |
| async def hf_state(): | |
| """Issue a one-time state nonce for the OAuth redirect (called by the site before redirecting).""" | |
| nonce = b64u(os.urandom(16)) | |
| con = db(); con.execute("INSERT INTO state_nonces(nonce,created) VALUES(?,?)", (nonce, time.time())) | |
| con.commit(); con.close() | |
| return {"state": nonce} | |
| # ---------------------------------------------------------------- api | |
| async def api_me(request: Request, authorization: str | None = Header(default=None)): | |
| payload = current_user(authorization, request) | |
| if not payload: | |
| raise HTTPException(401, "not logged in") | |
| hf_id = payload["sub"] | |
| app_user_id = f"hf_{hf_id}" | |
| ents = await rc_entitlements(app_user_id) | |
| return {"hf_id": hf_id, "name": payload.get("name"), "entitlements": ents} | |
| async def api_sim_token(request: Request, authorization: str | None = Header(default=None)): | |
| payload = current_user(authorization, request) | |
| if not payload: | |
| raise HTTPException(401, "not logged in") | |
| ents = await rc_entitlements(f"hf_{payload['sub']}") | |
| if "pro" not in ents: | |
| raise HTTPException(403, "pro entitlement required") | |
| token = sign({"sub": payload["sub"], "pro": True, "exp": time.time() + 600}, SIM_ACCESS_SECRET) | |
| return {"access": token} | |
| # ---------------------------------------------------------------- order notes (hardware item numbers) | |
| async def orders_note(request: Request, authorization: str | None = Header(default=None)): | |
| """Attach the purchaser's hardware item number(s) to their order record. | |
| All physical products ship by post on the selected hardware.""" | |
| payload = current_user(authorization, request) | |
| if not payload: | |
| raise HTTPException(401, "not logged in") | |
| body = await request.json() | |
| items = str(body.get("items", ""))[:2000] | |
| if not items.strip(): | |
| raise HTTPException(400, "items required") | |
| con = db() | |
| con.execute("INSERT INTO order_notes(app_user_id, items, created) VALUES(?,?,?)", | |
| (f"hf_{payload['sub']}", items, time.time())) | |
| con.commit(); con.close() | |
| return {"ok": True} | |
| # ---------------------------------------------------------------- RevenueCat webhooks | |
| async def rc_webhook(request: Request): | |
| body = await request.body() | |
| # auth: either "Authorization: Bearer <RC_WEBHOOK_SECRET>" (set in the RC webhook config) | |
| # or an X-RevenueCat-Signature HMAC (t=...,v1=...) when a signing secret is configured | |
| if RC_WEBHOOK_SECRET: | |
| if request.headers.get("Authorization", "") != f"Bearer {RC_WEBHOOK_SECRET}": | |
| sig_header = request.headers.get("X-RevenueCat-Signature", "") | |
| try: | |
| parts = dict(p.split("=", 1) for p in sig_header.split(",") if "=" in p) | |
| t, v1 = parts["t"], parts["v1"] | |
| expect = hmac.new(RC_WEBHOOK_SECRET.encode(), f"{t}.".encode() + body, hashlib.sha256).hexdigest() | |
| if not hmac.compare_digest(expect, v1): | |
| raise HTTPException(401, "bad signature") | |
| except HTTPException: | |
| raise | |
| except Exception: | |
| raise HTTPException(401, "bad signature") | |
| event = json.loads(body) | |
| ev = event.get("event", {}) | |
| etype = ev.get("type", "") | |
| eid = ev.get("id", "") | |
| product = ev.get("product_id", "") | |
| app_user_id = ev.get("app_user_id", "") | |
| cancel_reason = ev.get("cancel_reason") or "" | |
| email = ev.get("subscriber_attributes", {}).get("email", {}).get("value") or ev.get("email") or "" | |
| # dedupe: RevenueCat retries reuse the same event id — never issue a grant twice | |
| con = db() | |
| if eid: | |
| try: | |
| con.execute("INSERT INTO seen_events(event_id, seen) VALUES(?,?)", (eid, time.time())) | |
| con.commit() | |
| except sqlite3.IntegrityError: | |
| con.close() | |
| return {"ok": True, "handled": etype, "duplicate": True} | |
| con.close() | |
| grant_events = ("INITIAL_PURCHASE", "RENEWAL", "UNCANCELLATION", "PRODUCT_CHANGE", "NON_RENEWING_PURCHASE") | |
| if etype in grant_events: | |
| if product in FULFILL_SKUS: | |
| record_order(product, app_user_id, email, event) # kit/demo/hw: order row; goods ship by post on the selected hardware | |
| if product == LICENSE_SKU: | |
| await grant_hf_repo(app_user_id, grant=True, repos=SELECTED_MODEL_REPOS) | |
| elif product in PRO_SKUS: | |
| # pro also buys the licenses: selected model repos + code/demos repo | |
| await grant_hf_repo(app_user_id, grant=True, repos=SELECTED_MODEL_REPOS + CODE_REPOS) | |
| elif etype == "EXPIRATION": | |
| # subscription actually ended -> revoke | |
| if product == LICENSE_SKU: | |
| await grant_hf_repo(app_user_id, grant=False, repos=SELECTED_MODEL_REPOS) | |
| elif product in PRO_SKUS: | |
| await grant_hf_repo(app_user_id, grant=False, repos=SELECTED_MODEL_REPOS + CODE_REPOS) | |
| elif etype == "CANCELLATION": | |
| # a refund arrives as CANCELLATION with cancel_reason=CUSTOMER_SUPPORT (usually a negative | |
| # price); UNSUBSCRIBE only means auto-renew was turned off -> do NOT revoke then. | |
| if cancel_reason == "CUSTOMER_SUPPORT": | |
| if product in PRO_SKUS: | |
| # a refund does not necessarily end the subscription — check live status first | |
| ents = await rc_entitlements(app_user_id) | |
| if "pro" in ents: | |
| return {"ok": True, "handled": etype, "kept": "pro still active"} | |
| await grant_hf_repo(app_user_id, grant=False, repos=SELECTED_MODEL_REPOS + CODE_REPOS) | |
| elif product == LICENSE_SKU: | |
| await grant_hf_repo(app_user_id, grant=False, repos=SELECTED_MODEL_REPOS) | |
| elif product in FULFILL_SKUS: | |
| mark_order_refunded(product, app_user_id) | |
| return {"ok": True, "handled": etype} | |
| def record_order(sku: str, app_user_id: str, email: str, event: dict): | |
| con = db() | |
| oid = f"{sku}-{int(time.time())}-{app_user_id}" | |
| con.execute("INSERT INTO orders(id,app_user_id,sku,email,status,event,created) VALUES(?,?,?,?,?,?,?)", | |
| (oid, app_user_id, sku, email, "ordered", json.dumps(event)[:4000], time.time())) | |
| con.commit(); con.close() | |
| def mark_order_refunded(sku: str, app_user_id: str): | |
| con = db() | |
| con.execute("UPDATE orders SET status='refunded' WHERE sku=? AND app_user_id=? AND status='ordered'", | |
| (sku, app_user_id)) | |
| con.commit(); con.close() | |
| async def grant_hf_repo(app_user_id: str, grant: bool, repos: list[str]): | |
| """Add/remove the purchaser's HF username on the gated repos.""" | |
| if not HF_ADMIN_TOKEN or not app_user_id.startswith("hf_"): | |
| return | |
| con = db() | |
| row = con.execute("SELECT name FROM users WHERE rc_app_user_id=?", (app_user_id,)).fetchone() | |
| con.close() | |
| if not row: | |
| return # user never logged in via our flow; grant pending manual review | |
| username = row["name"] | |
| async with httpx.AsyncClient(timeout=20) as c: | |
| for repo in repos: | |
| try: | |
| if grant: | |
| await c.put(f"{HF_API}/models/{repo}/gated/add", | |
| headers={"Authorization": f"Bearer {HF_ADMIN_TOKEN}"}, json={"user": username}) | |
| else: | |
| await c.request("DELETE", f"{HF_API}/models/{repo}/gated", | |
| headers={"Authorization": f"Bearer {HF_ADMIN_TOKEN}"}, json={"user": username}) | |
| except Exception: | |
| pass | |
| # ---------------------------------------------------------------- privacy (GDPR rights) | |
| async def privacy_export(request: Request, authorization: str | None = Header(default=None)): | |
| payload = current_user(authorization, request) | |
| if not payload: | |
| raise HTTPException(401, "log in first (HF)") | |
| hf_id = payload["sub"]; app_user_id = f"hf_{hf_id}" | |
| out = {"hf_id": hf_id, "name": payload.get("name"), "exported_at": time.time()} | |
| con = db() | |
| row = con.execute("SELECT * FROM users WHERE hf_id=?", (hf_id,)).fetchone() | |
| out["local_user"] = dict(row) if row else None | |
| out["orders"] = [dict(r) for r in con.execute("SELECT id,sku,status,created FROM orders WHERE app_user_id=?", (app_user_id,))] | |
| con.close() | |
| out["entitlements"] = await rc_entitlements(app_user_id) | |
| async with httpx.AsyncClient(timeout=20) as c: | |
| if REVENUECAT_SECRET_KEY: | |
| r = await c.get(f"{RC_API}/subscribers/{app_user_id}", | |
| headers={"Authorization": f"Bearer {REVENUECAT_SECRET_KEY}"}) | |
| if r.status_code == 200: | |
| out["revenuecat"] = r.json() | |
| if STRIPE_SECRET_KEY and row and row["email"]: | |
| r = await c.get(f"https://api.stripe.com/v1/customers?email={row['email']}&limit=1", | |
| headers={"Authorization": f"Bearer {STRIPE_SECRET_KEY}"}) | |
| if r.status_code == 200 and r.json().get("data"): | |
| cust = r.json()["data"][0] | |
| out["stripe_customer_id"] = cust["id"] | |
| out["stripe"] = {k: cust.get(k) for k in ("email", "name", "address", "created")} | |
| return JSONResponse(out) | |
| async def privacy_erase(request: Request, authorization: str | None = Header(default=None)): | |
| payload = current_user(authorization, request) | |
| if not payload: | |
| raise HTTPException(401, "log in first (HF)") | |
| hf_id = payload["sub"]; app_user_id = f"hf_{hf_id}" | |
| results = {} | |
| async with httpx.AsyncClient(timeout=30) as c: | |
| if REVENUECAT_SECRET_KEY: | |
| r = await c.delete(f"{RC_API}/subscribers/{app_user_id}", | |
| headers={"Authorization": f"Bearer {REVENUECAT_SECRET_KEY}"}) | |
| results["revenuecat_delete"] = r.status_code | |
| con = db() | |
| row = con.execute("SELECT * FROM users WHERE hf_id=?", (hf_id,)).fetchone() | |
| if STRIPE_SECRET_KEY and row and row["email"]: | |
| r = await c.get(f"https://api.stripe.com/v1/customers?email={row['email']}&limit=1", | |
| headers={"Authorization": f"Bearer {STRIPE_SECRET_KEY}"}) | |
| if r.status_code == 200 and r.json().get("data"): | |
| r2 = await c.delete(f"https://api.stripe.com/v1/customers/{r.json()['data'][0]['id']}", | |
| headers={"Authorization": f"Bearer {STRIPE_SECRET_KEY}"}) | |
| results["stripe_delete"] = r2.status_code | |
| # remove HF gated access | |
| if row and HF_ADMIN_TOKEN: | |
| for repo in SELECTED_MODEL_REPOS: | |
| try: | |
| await c.request("DELETE", f"{HF_API}/models/{repo}/gated", | |
| headers={"Authorization": f"Bearer {HF_ADMIN_TOKEN}"}, json={"user": row["name"]}) | |
| except Exception: | |
| pass | |
| con.execute("DELETE FROM orders WHERE app_user_id=?", (app_user_id,)) | |
| con.execute("DELETE FROM users WHERE hf_id=?", (hf_id,)) | |
| con.commit(); con.close() | |
| results["local_purge"] = True | |
| return results | |
| # ---------------------------------------------------------------- calendar & signups | |
| async def _seed(): | |
| seed_events() | |
| seed_news() | |
| # ---------------------------------------------------------------- news (simple backend) | |
| def _pick(field: str, lang: str) -> str: | |
| import json as _json | |
| try: | |
| m = _json.loads(field) | |
| if isinstance(m, dict): | |
| return m.get(lang) or m.get("eu") or m.get("en") or "" | |
| return str(m) | |
| except Exception: | |
| return field or "" | |
| async def api_news(lang: str = "eu", site: str = ""): | |
| con = db() | |
| if site: | |
| rows = con.execute("SELECT * FROM news WHERE site=? ORDER BY date DESC, id DESC", (site,)).fetchall() | |
| else: | |
| rows = con.execute("SELECT * FROM news ORDER BY date DESC, id DESC").fetchall() | |
| con.close() | |
| return {"news": [{"date": r["date"], "title": _pick(r["title"], lang), "body": _pick(r["body"], lang), | |
| "link": r["link"] or ""} for r in rows]} | |
| async def api_news_post(request: Request, x_admin_token: str | None = Header(default=None)): | |
| """Publish a news item: {"site":"uas.eus","date":"2026-12-02","title":{"eu":"…","en":"…"},"body":{…},"link":"…"}""" | |
| if not ADMIN_API_TOKEN or x_admin_token != ADMIN_API_TOKEN: | |
| raise HTTPException(401, "bad admin token") | |
| import json as _json | |
| body = await request.json() | |
| date, title, bod = str(body.get("date") or ""), body.get("title"), body.get("body") | |
| if not date or not title: | |
| raise HTTPException(400, "date and title required") | |
| con = db() | |
| con.execute("INSERT INTO news(date,title,body,link,site,created) VALUES(?,?,?,?,?,?)", | |
| (date, _json.dumps(title, ensure_ascii=False), _json.dumps(bod or {}, ensure_ascii=False), | |
| str(body.get("link") or ""), str(body.get("site") or "uas.eus"), time.time())) | |
| con.commit(); con.close() | |
| return {"ok": True} | |
| # ---------------------------------------------------------------- contact form | |
| async def api_contact(request: Request): | |
| body = await request.json() | |
| name, email = (body.get("name") or "").strip(), (body.get("email") or "").strip() | |
| if not name or "@" not in email: | |
| raise HTTPException(400, "name and email required") | |
| con = db() | |
| con.execute("""INSERT INTO contacts(name,email,org,reference,profile,message,site,created) | |
| VALUES(?,?,?,?,?,?,?,?)""", | |
| (name, email, body.get("org") or "", body.get("reference") or "", | |
| body.get("profile") or "", body.get("message") or "", | |
| str(request.headers.get("origin") or ""), time.time())) | |
| con.commit(); con.close() | |
| return {"ok": True} | |
| async def api_events(kind: str = "workshop"): | |
| con = db() | |
| rows = con.execute("SELECT * FROM events WHERE kind=? ORDER BY start", (kind,)).fetchall() | |
| out = [] | |
| for r in rows: | |
| taken = con.execute("SELECT COUNT(*) c FROM signups WHERE event_id=?", (r["id"],)).fetchone()["c"] | |
| out.append({"id": r["id"], "kind": r["kind"], "title": r["title"], "start": r["start"], | |
| "location": r["location"], "capacity": r["capacity"], "taken": taken}) | |
| con.close() | |
| return {"events": out} | |
| async def api_signup(eid: str, request: Request): | |
| body = await request.json() | |
| name, email = (body.get("name") or "").strip(), (body.get("email") or "").strip() | |
| if not name or "@" not in email: | |
| raise HTTPException(400, "name and email required") | |
| con = db() | |
| ev = con.execute("SELECT * FROM events WHERE id=?", (eid,)).fetchone() | |
| if not ev: | |
| con.close(); raise HTTPException(404, "event not found") | |
| taken = con.execute("SELECT COUNT(*) c FROM signups WHERE event_id=?", (eid,)).fetchone()["c"] | |
| if taken >= ev["capacity"]: | |
| con.close(); raise HTTPException(409, "event full") | |
| id_ack = 1 if (ev["kind"] == "workshop" and body.get("id_ack")) else 0 | |
| if ev["kind"] == "workshop" and not id_ack: | |
| con.close(); raise HTTPException(400, "ID acknowledgement required (ID at the door)") | |
| con.execute("INSERT INTO signups(event_id,kind,name,email,org,topic,id_ack,created) VALUES(?,?,?,?,?,?,?,?)", | |
| (eid, ev["kind"], name, email, body.get("org") or "", body.get("topic") or "", id_ack, time.time())) | |
| con.commit(); con.close() | |
| return {"ok": True, "event": eid} | |
| # ---------------------------------------------------------------- admin (kit fulfillment) | |
| async def admin_order_status(oid: str, status: str, x_admin_token: str | None = Header(default=None)): | |
| if not ADMIN_API_TOKEN or x_admin_token != ADMIN_API_TOKEN: | |
| raise HTTPException(401, "bad admin token") | |
| if status not in ("ordered", "flashed", "shipped", "delivered"): | |
| raise HTTPException(400, "bad status") | |
| con = db() | |
| con.execute("UPDATE orders SET status=? WHERE id=?", (status, oid)) | |
| con.commit(); con.close() | |
| return {"ok": True, "id": oid, "status": status} | |
| async def admin_orders(x_admin_token: str | None = Header(default=None)): | |
| if not ADMIN_API_TOKEN or x_admin_token != ADMIN_API_TOKEN: | |
| raise HTTPException(401, "bad admin token") | |
| con = db() | |
| rows = [dict(r) for r in con.execute("SELECT * FROM orders ORDER BY created DESC")] | |
| con.close() | |
| return {"orders": rows} | |