RECORDGOD/app/settings_routes.py
type-two 0e8c84b0e7 feat(dash): connection testing — Discogs / Woo / DealGod
POST /settings/test/{service} validates stored creds against the live service
(Discogs identity, Woo orders, DealGod /api/me) so "connected" means connected.
Dash gets per-service Test buttons with green/amber status.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-21 15:03:18 +10:00

94 lines
4.1 KiB
Python

from urllib.parse import urlparse
import httpx
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from . import vault
from .auth import require_token
from .db import get_db
# Admin-gated. The dash POSTs credentials in; values are encrypted at rest and NEVER returned.
router = APIRouter(prefix="/settings", tags=["settings"])
# The credentials the dash knows how to collect (name → human label).
KNOWN = {
"woo_base_url": "WooCommerce store URL (https://…)",
"woo_consumer_key": "WooCommerce REST consumer key (ck_…)",
"woo_consumer_secret": "WooCommerce REST consumer secret (cs_…)",
"discogs_consumer_key": "Discogs OAuth consumer key",
"discogs_consumer_secret": "Discogs OAuth consumer secret",
"discogs_token": "Discogs personal access token",
"cloudflare_api_token": "Cloudflare API token",
"dealgod_api_key": "DealGod API key (X-Api-Key)",
}
class SecretIn(BaseModel):
name: str
value: str
@router.get("/secrets")
async def list_secrets(ident=Depends(require_token), db=Depends(get_db)):
have = {s["name"]: s["updated_at"] for s in await vault.list_secret_names(db)}
return {"ok": True, "fields": [
{"name": n, "label": label, "set": n in have, "updated_at": have.get(n)}
for n, label in KNOWN.items()
]}
@router.post("/secrets")
async def save_secret(body: SecretIn, ident=Depends(require_token), db=Depends(get_db)):
if body.name not in KNOWN:
raise HTTPException(400, "unknown secret name")
if not body.value.strip():
raise HTTPException(400, "empty value")
try:
await vault.set_secret(db, body.name, body.value.strip())
except vault.SecretsUnconfigured as e:
raise HTTPException(503, str(e))
return {"ok": True, "name": body.name, "set": True}
@router.post("/test/{service}")
async def test_connection(service: str, ident=Depends(require_token), db=Depends(get_db)):
"""Validate stored credentials against the live service — so 'connected' means connected."""
async with httpx.AsyncClient(timeout=15, follow_redirects=True) as c:
if service == "discogs":
tok = await vault.get_secret(db, "discogs_token")
if not tok:
raise HTTPException(400, "save a Discogs personal access token first")
r = await c.get("https://api.discogs.com/oauth/identity",
headers={"Authorization": f"Discogs token={tok}",
"User-Agent": "RecordGod/0.1"})
if r.status_code == 200:
return {"ok": True, "connected": True, "as": r.json().get("username")}
return {"ok": True, "connected": False, "detail": f"HTTP {r.status_code}"}
if service == "woo":
base = await vault.get_secret(db, "woo_base_url")
ck = await vault.get_secret(db, "woo_consumer_key")
cs = await vault.get_secret(db, "woo_consumer_secret")
if not (base and ck and cs):
raise HTTPException(400, "save Woo store URL + consumer key + secret first")
r = await c.get(base.rstrip("/") + "/wp-json/wc/v3/orders",
params={"per_page": 1}, auth=(ck, cs))
if r.status_code == 200:
return {"ok": True, "connected": True, "as": urlparse(base).netloc}
return {"ok": True, "connected": False, "detail": f"HTTP {r.status_code}"}
if service == "dealgod":
key = await vault.get_secret(db, "dealgod_api_key")
if not key:
raise HTTPException(400, "save a DealGod API key first")
r = await c.get("https://api.dealgod.pro/api/me", headers={"X-Api-Key": key})
if r.status_code == 200:
j = r.json()
return {"ok": True, "connected": True, "as": f"{j.get('user')} · {j.get('plan')}"}
if r.status_code == 404:
return {"ok": True, "connected": False, "detail": "DealGod /api/me not deployed yet"}
return {"ok": True, "connected": False, "detail": f"HTTP {r.status_code}"}
raise HTTPException(400, "unknown service")