settings: add nav visibility prefs and per-user Strava credentials

- user_prefs table in db.py with get/set helpers
- GET/PUT /api/me/prefs endpoints for bulk pref management
- GET/PUT/DELETE /api/me/strava-credentials; PUT preserves existing
  secret when client_secret field is left blank
- _strava_creds() helper resolves per-user → instance fallback across
  all five Strava endpoints
- Settings page: Navigation card (hide Feed/Community/About toggles)
  and Strava credentials card
- Base.astro: ids on feed/community/about nav links; applies
  nav_hide_* prefs after login
This commit is contained in:
Davide Scaini
2026-04-15 20:37:42 +02:00
parent 4fd5ba428e
commit 87a69bcc8b
4 changed files with 358 additions and 13 deletions
+126 -10
View File
@@ -41,6 +41,8 @@ from bincio.serve.db import (
get_session,
get_setting,
get_user,
get_user_prefs,
set_user_prefs,
list_invites,
list_users,
open_db,
@@ -99,6 +101,29 @@ def _get_db():
return _db
_STRAVA_CREDS_FILE = "strava_credentials.json"
def _strava_creds(handle: str) -> tuple[str, str]:
"""Return (client_id, client_secret) for a user.
Per-user credentials stored in {user_dir}/strava_credentials.json take
precedence over the global instance-level strava_client_id/secret.
Returns ("", "") when neither is configured.
"""
creds_path = _get_data_dir() / handle / _STRAVA_CREDS_FILE
if creds_path.exists():
try:
d = json.loads(creds_path.read_text(encoding="utf-8"))
cid = str(d.get("client_id", "")).strip()
csec = str(d.get("client_secret", "")).strip()
if cid and csec:
return cid, csec
except Exception:
pass
return strava_client_id, strava_client_secret
def _get_data_dir() -> Path:
if data_dir is None:
raise HTTPException(500, "Server not configured")
@@ -1013,6 +1038,92 @@ async def me_update_display_name(
return JSONResponse({"ok": True, "display_name": display_name})
@app.get("/api/me/prefs")
async def me_get_prefs(bincio_session: Optional[str] = Cookie(default=None)) -> JSONResponse:
"""Return all user preferences as a key→value dict."""
user = _require_user(bincio_session)
return JSONResponse(get_user_prefs(_get_db(), user.handle))
@app.put("/api/me/prefs")
async def me_set_prefs(
request: Request,
bincio_session: Optional[str] = Cookie(default=None),
) -> JSONResponse:
"""Upsert one or more user preferences. Body: {key: value, ...} (all strings)."""
user = _require_user(bincio_session)
body = await request.json()
if not isinstance(body, dict):
raise HTTPException(400, "Body must be a JSON object")
# Coerce all values to strings; ignore unknown keys silently
prefs = {str(k): str(v) for k, v in body.items()}
set_user_prefs(_get_db(), user.handle, prefs)
return JSONResponse({"ok": True})
@app.get("/api/me/strava-credentials")
async def me_get_strava_credentials(bincio_session: Optional[str] = Cookie(default=None)) -> JSONResponse:
"""Return whether per-user Strava credentials are configured (never returns the secret)."""
user = _require_user(bincio_session)
creds_path = _get_data_dir() / user.handle / _STRAVA_CREDS_FILE
has_user_creds = False
client_id_hint = ""
if creds_path.exists():
try:
d = json.loads(creds_path.read_text(encoding="utf-8"))
cid = str(d.get("client_id", "")).strip()
csec = str(d.get("client_secret", "")).strip()
if cid and csec:
has_user_creds = True
client_id_hint = cid
except Exception:
pass
return JSONResponse({
"has_user_creds": has_user_creds,
"client_id": client_id_hint,
"instance_configured": bool(strava_client_id),
})
@app.put("/api/me/strava-credentials")
async def me_set_strava_credentials(
request: Request,
bincio_session: Optional[str] = Cookie(default=None),
) -> JSONResponse:
"""Save per-user Strava credentials. Body: {client_id, client_secret}."""
user = _require_user(bincio_session)
body = await request.json()
cid = str(body.get("client_id", "")).strip()
csec = str(body.get("client_secret", "")).strip()
if not cid:
raise HTTPException(400, "client_id is required")
creds_path = _get_data_dir() / user.handle / _STRAVA_CREDS_FILE
# If client_secret is omitted, preserve existing secret (if any)
if not csec:
if creds_path.exists():
try:
existing = json.loads(creds_path.read_text(encoding="utf-8"))
csec = str(existing.get("client_secret", "")).strip()
except Exception:
pass
if not csec:
raise HTTPException(400, "client_secret is required (no existing secret to preserve)")
creds_path.write_text(
json.dumps({"client_id": cid, "client_secret": csec}, indent=2),
encoding="utf-8",
)
return JSONResponse({"ok": True})
@app.delete("/api/me/strava-credentials")
async def me_delete_strava_credentials(bincio_session: Optional[str] = Cookie(default=None)) -> JSONResponse:
"""Remove per-user Strava credentials (falls back to instance credentials)."""
user = _require_user(bincio_session)
creds_path = _get_data_dir() / user.handle / _STRAVA_CREDS_FILE
creds_path.unlink(missing_ok=True)
return JSONResponse({"ok": True})
@app.put("/api/me/password")
async def me_change_password(
request: Request,
@@ -1574,7 +1685,8 @@ _strava_oauth_states: set[str] = set()
@app.get("/api/strava/status")
async def strava_status(bincio_session: Optional[str] = Cookie(default=None)) -> JSONResponse:
user = _require_user(bincio_session)
if not strava_client_id:
cid, _ = _strava_creds(user.handle)
if not cid:
return JSONResponse({"configured": False, "connected": False, "last_sync": None})
dd = _get_data_dir() / user.handle
from bincio.extract.strava_api import load_token
@@ -1640,8 +1752,9 @@ async def strava_reset(request: Request, bincio_session: Optional[str] = Cookie(
@app.get("/api/strava/auth-url")
async def strava_auth_url(request: Request, bincio_session: Optional[str] = Cookie(default=None)) -> JSONResponse:
_require_user(bincio_session)
if not strava_client_id:
user = _require_user(bincio_session)
cid, _ = _strava_creds(user.handle)
if not cid:
raise HTTPException(400, "Strava client ID not configured on this server")
state = secrets.token_urlsafe(16)
_strava_oauth_states.add(state)
@@ -1650,7 +1763,7 @@ async def strava_auth_url(request: Request, bincio_session: Optional[str] = Cook
else:
redirect_uri = str(request.url_for("strava_callback"))
from bincio.extract.strava_api import auth_url
return JSONResponse({"url": auth_url(strava_client_id, redirect_uri, state=state)})
return JSONResponse({"url": auth_url(cid, redirect_uri, state=state)})
@app.get("/api/strava/callback", name="strava_callback")
@@ -1670,12 +1783,13 @@ async def strava_callback(
user = _current_user(bincio_session)
if not user:
return RedirectResponse(f"{site_origin}/?strava=error")
if not strava_client_id or not strava_client_secret:
cid, csec = _strava_creds(user.handle)
if not cid or not csec:
return RedirectResponse(f"{site_origin}/?strava=error")
dd = _get_data_dir() / user.handle
from bincio.extract.strava_api import StravaError, exchange_code, save_token
try:
token = exchange_code(strava_client_id, strava_client_secret, code)
token = exchange_code(cid, csec, code)
except StravaError:
return RedirectResponse(f"{site_origin}/?strava=error")
save_token(dd, token)
@@ -1686,7 +1800,8 @@ async def strava_callback(
async def serve_strava_sync_stream(bincio_session: Optional[str] = Cookie(default=None)) -> StreamingResponse:
"""SSE endpoint — streams per-activity progress then a final summary event."""
user = _require_user(bincio_session)
if not strava_client_id or not strava_client_secret:
cid, csec = _strava_creds(user.handle)
if not cid or not csec:
raise HTTPException(400, "Strava not configured on this server")
dd = _get_data_dir() / user.handle
store_orig_setting = get_setting(_get_db(), "store_originals")
@@ -1699,7 +1814,7 @@ async def serve_strava_sync_stream(bincio_session: Optional[str] = Cookie(defaul
def event_stream():
try:
for event in strava_sync_iter(dd, strava_client_id, strava_client_secret, originals_dir):
for event in strava_sync_iter(dd, cid, csec, originals_dir):
if event["type"] == "done":
_trigger_rebuild(user.handle) # start before client closes connection
yield f"data: {json.dumps(event)}\n\n"
@@ -1716,7 +1831,8 @@ async def serve_strava_sync_stream(bincio_session: Optional[str] = Cookie(defaul
@app.post("/api/strava/sync")
async def serve_strava_sync(bincio_session: Optional[str] = Cookie(default=None)) -> JSONResponse:
user = _require_user(bincio_session)
if not strava_client_id or not strava_client_secret:
cid, csec = _strava_creds(user.handle)
if not cid or not csec:
raise HTTPException(400, "Strava not configured on this server")
dd = _get_data_dir() / user.handle
store_orig_setting = get_setting(_get_db(), "store_originals")
@@ -1726,7 +1842,7 @@ async def serve_strava_sync(bincio_session: Optional[str] = Cookie(default=None)
originals_dir.mkdir(parents=True, exist_ok=True)
from bincio.edit.ops import run_strava_sync
try:
result = run_strava_sync(dd, strava_client_id, strava_client_secret, originals_dir=originals_dir)
result = run_strava_sync(dd, cid, csec, originals_dir=originals_dir)
except RuntimeError as e:
raise HTTPException(502, str(e))
_trigger_rebuild(user.handle)