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
+38
View File
@@ -59,9 +59,17 @@ CREATE TABLE IF NOT EXISTS settings (
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS user_prefs (
handle TEXT NOT NULL REFERENCES users(handle) ON DELETE CASCADE,
key TEXT NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY (handle, key)
);
CREATE INDEX IF NOT EXISTS sessions_handle ON sessions(handle);
CREATE INDEX IF NOT EXISTS invites_created_by ON invites(created_by);
CREATE INDEX IF NOT EXISTS reset_codes_handle ON reset_codes(handle);
CREATE INDEX IF NOT EXISTS user_prefs_handle ON user_prefs(handle);
"""
_SESSION_DAYS = 30
@@ -361,6 +369,36 @@ def create_reset_code(db: sqlite3.Connection, handle: str, created_by: str) -> s
return code
# ── User preferences ─────────────────────────────────────────────────────────
def get_user_prefs(db: sqlite3.Connection, handle: str) -> dict[str, str]:
"""Return all preferences for a user as a plain dict."""
rows = db.execute(
"SELECT key, value FROM user_prefs WHERE handle = ?", (handle,)
).fetchall()
return {r["key"]: r["value"] for r in rows}
def set_user_pref(db: sqlite3.Connection, handle: str, key: str, value: str) -> None:
db.execute(
"INSERT INTO user_prefs (handle, key, value) VALUES (?, ?, ?) "
"ON CONFLICT(handle, key) DO UPDATE SET value = excluded.value",
(handle, key, value),
)
db.commit()
def set_user_prefs(db: sqlite3.Connection, handle: str, prefs: dict[str, str]) -> None:
"""Bulk-upsert multiple preferences for a user."""
for key, value in prefs.items():
db.execute(
"INSERT INTO user_prefs (handle, key, value) VALUES (?, ?, ?) "
"ON CONFLICT(handle, key) DO UPDATE SET value = excluded.value",
(handle, key, value),
)
db.commit()
def use_reset_code(db: sqlite3.Connection, code: str, handle: str) -> bool:
"""Validate a reset code for the given handle and mark it used.
+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)
+22 -3
View File
@@ -166,7 +166,7 @@ try {
<div class="nav-links flex items-center gap-5 overflow-x-auto flex-1 min-w-0">
<!-- Feed tab: only shown for multi-user (more than one shard) -->
{!singleHandle && (
<a href={baseUrl} class="text-sm text-zinc-400 hover:text-white transition-colors shrink-0">Feed</a>
<a id="nav-feed" href={baseUrl} class="text-sm text-zinc-400 hover:text-white transition-colors shrink-0">Feed</a>
)}
<!-- Single-user: static handle link. Multi-user: populated by user-widget script. -->
{singleHandle
@@ -177,7 +177,7 @@ try {
<a id="nav-stats" href={singleHandle ? `${baseUrl}u/${singleHandle}/stats/` : `${baseUrl}stats/`} data-user-path="stats/" class="text-sm text-zinc-400 hover:text-white transition-colors shrink-0">Stats</a>
<a id="nav-athlete" href={singleHandle ? `${baseUrl}u/${singleHandle}/athlete/` : `${baseUrl}athlete/`} data-user-path="athlete/" class="text-sm text-zinc-400 hover:text-white transition-colors shrink-0">Athlete</a>
{!singleHandle && (
<a href={`${baseUrl}community/`} class="text-sm text-zinc-400 hover:text-white transition-colors shrink-0">Community</a>
<a id="nav-community" href={`${baseUrl}community/`} class="text-sm text-zinc-400 hover:text-white transition-colors shrink-0">Community</a>
)}
{mobileApp && (
<a id="nav-record" href={singleHandle ? `${baseUrl}u/${singleHandle}/record/` : `${baseUrl}record/`} data-user-path="record/" class="text-sm text-zinc-400 hover:text-white transition-colors shrink-0">Record</a>
@@ -185,7 +185,7 @@ try {
{mobileApp && (
<a href={`${baseUrl}convert/`} class="text-sm text-zinc-400 hover:text-white transition-colors shrink-0">Convert</a>
)}
<a href={`${baseUrl}about/`} class="text-sm text-zinc-400 hover:text-white transition-colors shrink-0">About</a>
<a id="nav-about" href={`${baseUrl}about/`} class="text-sm text-zinc-400 hover:text-white transition-colors shrink-0">About</a>
</div>
)}
@@ -511,6 +511,25 @@ try {
const chk = document.getElementById('upload-keep-original');
if (chk && user.store_originals_default) chk.checked = true;
// Apply nav visibility prefs
try {
const pr = await fetch('/api/me/prefs', { credentials: 'include' });
if (pr.ok) {
const prefs = await pr.json();
const navHideMap: Record<string, string> = {
'nav_hide_feed': 'nav-feed',
'nav_hide_community': 'nav-community',
'nav_hide_about': 'nav-about',
};
for (const [key, elId] of Object.entries(navHideMap)) {
if (prefs[key] === 'true') {
const el = document.getElementById(elId);
if (el) el.style.display = 'none';
}
}
}
} catch (_) {}
// Admin: show admin link and poll for active jobs
if (user.is_admin) {
const adminLink = document.getElementById('nav-admin');
+172
View File
@@ -85,6 +85,58 @@ import Base from '../../layouts/Base.astro';
</form>
</section>
<!-- Navigation visibility card -->
<section class="mb-6 rounded-xl bg-zinc-900 border border-zinc-800 p-5">
<h2 class="text-sm font-semibold text-zinc-400 uppercase tracking-wider mb-1">Navigation</h2>
<p class="text-xs text-zinc-600 mb-4">Hide items from the top nav bar. Affects only your view.</p>
<div class="space-y-3">
<label class="flex items-center gap-3 cursor-pointer group">
<input id="nav-hide-feed" type="checkbox" class="accent-[--accent]" />
<span class="text-sm text-zinc-300 group-hover:text-white transition-colors">Hide Feed</span>
</label>
<label class="flex items-center gap-3 cursor-pointer group">
<input id="nav-hide-community" type="checkbox" class="accent-[--accent]" />
<span class="text-sm text-zinc-300 group-hover:text-white transition-colors">Hide Community</span>
</label>
<label class="flex items-center gap-3 cursor-pointer group">
<input id="nav-hide-about" type="checkbox" class="accent-[--accent]" />
<span class="text-sm text-zinc-300 group-hover:text-white transition-colors">Hide About</span>
</label>
</div>
<p id="nav-prefs-status" class="text-xs mt-3 hidden"></p>
</section>
<!-- Strava credentials card -->
<section class="mb-6 rounded-xl bg-zinc-900 border border-zinc-800 p-5">
<h2 class="text-sm font-semibold text-zinc-400 uppercase tracking-wider mb-1">Strava API credentials</h2>
<p id="strava-creds-desc" class="text-xs text-zinc-600 mb-4">Loading…</p>
<form id="strava-creds-form" class="space-y-3">
<div>
<label class="block text-xs text-zinc-500 mb-1" for="strava-client-id">Client ID</label>
<input id="strava-client-id" type="text" autocomplete="off"
class="w-full px-3 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white placeholder-zinc-500 focus:outline-none focus:border-[--accent] text-sm"
placeholder="123456" />
</div>
<div>
<label class="block text-xs text-zinc-500 mb-1" for="strava-client-secret">Client secret</label>
<input id="strava-client-secret" type="password" autocomplete="off"
class="w-full px-3 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white placeholder-zinc-500 focus:outline-none focus:border-[--accent] text-sm"
placeholder="Leave blank to keep existing" />
</div>
<p id="strava-creds-status" class="text-xs hidden"></p>
<div class="flex gap-2">
<button type="submit"
class="px-4 py-2 rounded-lg text-sm bg-zinc-700 hover:bg-zinc-600 text-white transition-colors">
Save
</button>
<button type="button" id="strava-creds-clear"
class="px-4 py-2 rounded-lg text-sm bg-zinc-800 hover:bg-red-900 hover:text-red-300 text-zinc-400 transition-colors">
Use instance credentials
</button>
</div>
</form>
</section>
<!-- Danger zone -->
<section class="rounded-xl bg-zinc-900 border border-red-900/40 p-5">
<h2 class="text-sm font-semibold text-red-400/70 uppercase tracking-wider mb-4">Danger zone</h2>
@@ -342,8 +394,128 @@ import Base from '../../layouts/Base.astro';
document.getElementById('del-activities-btn')?.addEventListener('click', () => openConfirm('activities'));
document.getElementById('del-account-btn')?.addEventListener('click', () => openConfirm('account'));
// ── Navigation prefs ─────────────────────────────────────────────────────────
const NAV_PREF_KEYS: Record<string, string> = {
'nav-hide-feed': 'nav_hide_feed',
'nav-hide-community': 'nav_hide_community',
'nav-hide-about': 'nav_hide_about',
};
async function loadNavPrefs() {
try {
const r = await fetch('/api/me/prefs', { credentials: 'include' });
if (!r.ok) return;
const prefs = await r.json();
for (const [elId, key] of Object.entries(NAV_PREF_KEYS)) {
const el = document.getElementById(elId) as HTMLInputElement | null;
if (el) el.checked = prefs[key] === 'true';
}
} catch {}
}
async function saveNavPref(key: string, value: boolean) {
const statusEl = document.getElementById('nav-prefs-status')!;
try {
const r = await fetch('/api/me/prefs', {
method: 'PUT',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ [key]: String(value) }),
});
if (r.ok) {
setStatus(statusEl, 'Saved.', true);
setTimeout(() => statusEl.classList.add('hidden'), 2000);
} else {
const d = await r.json();
setStatus(statusEl, d.detail ?? 'Failed', false);
}
} catch {
setStatus(statusEl, 'Could not reach server', false);
}
}
for (const [elId, key] of Object.entries(NAV_PREF_KEYS)) {
document.getElementById(elId)?.addEventListener('change', (e) => {
saveNavPref(key, (e.target as HTMLInputElement).checked);
});
}
// ── Strava credentials ────────────────────────────────────────────────────────
async function loadStravaCreds() {
const desc = document.getElementById('strava-creds-desc')!;
try {
const r = await fetch('/api/me/strava-credentials', { credentials: 'include' });
if (!r.ok) { desc.textContent = 'Not available.'; return; }
const d = await r.json();
if (d.has_user_creds) {
desc.textContent = `Using your own credentials (Client ID: ${d.client_id}).`;
(document.getElementById('strava-client-id') as HTMLInputElement).value = d.client_id ?? '';
} else if (d.instance_configured) {
desc.textContent = 'Using instance-level credentials. Enter your own below to override.';
} else {
desc.textContent = 'Strava is not configured on this instance. You can set your own API credentials below.';
}
} catch {
desc.textContent = 'Could not load Strava settings.';
}
}
document.getElementById('strava-creds-form')?.addEventListener('submit', async (e) => {
e.preventDefault();
const statusEl = document.getElementById('strava-creds-status')!;
const clientId = (document.getElementById('strava-client-id') as HTMLInputElement).value.trim();
const clientSecret = (document.getElementById('strava-client-secret') as HTMLInputElement).value.trim();
if (!clientId) {
setStatus(statusEl, 'Client ID is required.', false);
return;
}
try {
const body: Record<string, string> = { client_id: clientId };
if (clientSecret) body.client_secret = clientSecret;
const r = await fetch('/api/me/strava-credentials', {
method: 'PUT',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const d = await r.json();
if (r.ok) {
setStatus(statusEl, 'Saved.', true);
(document.getElementById('strava-client-secret') as HTMLInputElement).value = '';
loadStravaCreds();
} else {
setStatus(statusEl, d.detail ?? 'Failed', false);
}
} catch {
setStatus(statusEl, 'Could not reach server', false);
}
});
document.getElementById('strava-creds-clear')?.addEventListener('click', async () => {
const statusEl = document.getElementById('strava-creds-status')!;
if (!confirm('Remove your custom Strava credentials and fall back to instance credentials?')) return;
try {
const r = await fetch('/api/me/strava-credentials', { method: 'DELETE', credentials: 'include' });
if (r.ok) {
setStatus(statusEl, 'Cleared — using instance credentials.', true);
(document.getElementById('strava-client-id') as HTMLInputElement).value = '';
(document.getElementById('strava-client-secret') as HTMLInputElement).value = '';
loadStravaCreds();
} else {
const d = await r.json();
setStatus(statusEl, d.detail ?? 'Failed', false);
}
} catch {
setStatus(statusEl, 'Could not reach server', false);
}
});
// ── Init ─────────────────────────────────────────────────────────────────────
loadMe();
loadStorage();
loadNavPrefs();
loadStravaCreds();
</script>