Require logging in to the web UI and API
The first visit to the UI creates the account from a username and password; after that every API route needs a session cookie from logging in. Accounts are stored in app_user (Argon2id password hashes) and sessions in user_session (SHA-256 token hashes, 30 days). The account page lets the user save a Listenbrainz token, checked with Listenbrainz first. It takes priority over listenbrainz.token from the config for LB Radio suggestions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0767c21a6f
commit
53c1bffa6d
33 files changed
+1249
-39
No files matched your search
@@ -0,0 +1,130 @@
|
||||
import { FormEvent, useState } from "react";
|
||||
import { Account, authApi } from "./api";
|
||||
import * as Icon from "./icons";
|
||||
|
||||
export function AccountView(props: {
|
||||
account: Account;
|
||||
onChange: (account: Account) => void;
|
||||
onLogout: () => void;
|
||||
onToast: (message: string) => void;
|
||||
}) {
|
||||
const { account } = props;
|
||||
const [token, setToken] = useState("");
|
||||
const [busy, setBusy] = useState<"save" | "remove" | "logout" | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const saveToken = async (value: string) => {
|
||||
setBusy(value ? "save" : "remove");
|
||||
setError(null);
|
||||
try {
|
||||
const updated = await authApi.setListenbrainzToken(value);
|
||||
props.onChange(updated);
|
||||
setToken("");
|
||||
props.onToast(
|
||||
updated.listenbrainz_user
|
||||
? `Saved the token for ${updated.listenbrainz_user}`
|
||||
: "Removed the Listenbrainz token",
|
||||
);
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
void saveToken(token.trim());
|
||||
};
|
||||
|
||||
const logout = async () => {
|
||||
setBusy("logout");
|
||||
try {
|
||||
await authApi.logout();
|
||||
} catch {
|
||||
// the session is gone from this browser either way
|
||||
}
|
||||
props.onLogout();
|
||||
};
|
||||
|
||||
return (
|
||||
<article className="manage">
|
||||
<header className="manage-header">
|
||||
<p className="eyebrow">Account</p>
|
||||
<h1>{account.username}</h1>
|
||||
</header>
|
||||
|
||||
<section className="panel" aria-labelledby="lb-heading">
|
||||
<div className="panel-header">
|
||||
<div>
|
||||
<h2 id="lb-heading">Listenbrainz token</h2>
|
||||
<p className="hint">
|
||||
Lets playlistd find new songs for each mix's genres with LB Radio, on top of your
|
||||
recommendations. Find yours at{" "}
|
||||
<a href="https://listenbrainz.org/settings/" target="_blank" rel="noreferrer">
|
||||
listenbrainz.org/settings <Icon.External size={12} />
|
||||
</a>
|
||||
. New songs are picked up the next time your mixes are rebuilt.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="token-status">
|
||||
{account.has_listenbrainz_token ? (
|
||||
<>
|
||||
<span className="status-dot ok" aria-hidden="true" />
|
||||
Saved, for Listenbrainz user <strong>{account.listenbrainz_user}</strong>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="status-dot" aria-hidden="true" />
|
||||
No token saved
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
|
||||
<form className="form" onSubmit={submit} aria-label="Listenbrainz token">
|
||||
<label className="field">
|
||||
<span>{account.has_listenbrainz_token ? "Replace token" : "Token"}</span>
|
||||
<input
|
||||
className="mono"
|
||||
type="password"
|
||||
required
|
||||
value={token}
|
||||
onChange={(e) => setToken(e.target.value)}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
|
||||
/>
|
||||
</label>
|
||||
{error && <p className="form-error" role="alert">{error}</p>}
|
||||
<div className="form-actions">
|
||||
{account.has_listenbrainz_token && (
|
||||
<button type="button" className="btn" disabled={!!busy} onClick={() => saveToken("")}>
|
||||
{busy === "remove" && <span className="spinner" />}
|
||||
Remove token
|
||||
</button>
|
||||
)}
|
||||
<button type="submit" className="btn primary" disabled={!!busy || !token.trim()}>
|
||||
{busy === "save" && <span className="spinner light" />}
|
||||
{busy === "save" ? "Checking…" : "Save token"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section className="panel" aria-labelledby="session-heading">
|
||||
<div className="panel-header">
|
||||
<div>
|
||||
<h2 id="session-heading">Session</h2>
|
||||
<p className="hint">Logged in as {account.username} in this browser.</p>
|
||||
</div>
|
||||
<button className="btn" onClick={logout} disabled={!!busy}>
|
||||
{busy === "logout" && <span className="spinner" />}
|
||||
Log out
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
+26
-8
@@ -1,17 +1,18 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { api, MixDetail, MixSummary, mixTitle, Rule, Suggestion, SuggestionStatus } from "./api";
|
||||
import { Account, api, MixDetail, MixSummary, mixTitle, Rule, Suggestion, SuggestionStatus } from "./api";
|
||||
import { usePlayer } from "./usePlayer";
|
||||
import { MixView, hue } from "./MixView";
|
||||
import { LikedView } from "./LikedView";
|
||||
import { TrackedView } from "./TrackedView";
|
||||
import { AccountView } from "./AccountView";
|
||||
import { PlayerBar } from "./PlayerBar";
|
||||
import * as Icon from "./icons";
|
||||
|
||||
type Route = { view: "mix"; id?: string } | { view: "liked" } | { view: "tracked" };
|
||||
type Route = { view: "mix"; id?: string } | { view: "liked" } | { view: "tracked" } | { view: "account" };
|
||||
|
||||
function parseHash(): Route {
|
||||
const [, view, id] = window.location.hash.split("/");
|
||||
if (view === "liked" || view === "tracked") return { view };
|
||||
if (view === "liked" || view === "tracked" || view === "account") return { view };
|
||||
return { view: "mix", id: id || undefined };
|
||||
}
|
||||
|
||||
@@ -25,7 +26,11 @@ function storedRule() {
|
||||
}
|
||||
}
|
||||
|
||||
export function App() {
|
||||
export function App(props: {
|
||||
account: Account;
|
||||
onAccountChange: (account: Account) => void;
|
||||
onLogout: () => void;
|
||||
}) {
|
||||
const [rules, setRules] = useState<Rule[] | null>(null);
|
||||
const [ruleId, setRuleId] = useState<string | null>(storedRule);
|
||||
const [mixes, setMixes] = useState<MixSummary[] | null>(null);
|
||||
@@ -201,22 +206,35 @@ export function App() {
|
||||
<span className="mix-name">Tracked playlists</span>
|
||||
</a>
|
||||
</li>
|
||||
<li className="account-link">
|
||||
<a href="#/account" className={route.view === "account" ? "selected" : ""} style={{ ["--hue" as string]: 220 }}>
|
||||
<span className="mix-dot heart" aria-hidden="true"><Icon.User size={14} /></span>
|
||||
<span className="mix-name">{props.account.username}</span>
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<main className="content">
|
||||
{error && <div className="notice error">{error}</div>}
|
||||
{route.view !== "tracked" && rules && rules.length === 0 && (
|
||||
{(route.view === "mix" || route.view === "liked") && rules && rules.length === 0 && (
|
||||
<div className="notice">
|
||||
<h1>No mix rules yet</h1>
|
||||
<p>Create one, and playlistd will cluster your listens into genre mixes:</p>
|
||||
<pre>{`curl -X POST /api/playlist/mix -H 'Content-Type: application/json' \\\n -d '{"tracking_user": "your-listenbrainz-name"}'`}</pre>
|
||||
<pre>{`curl -c cookies -X POST ${location.origin}/api/auth/login -H 'Content-Type: application/json' \\\n -d '{"username": "${props.account.username}", "password": "…"}'\ncurl -b cookies -X POST ${location.origin}/api/playlist/mix -H 'Content-Type: application/json' \\\n -d '{"tracking_user": "your-listenbrainz-name"}'`}</pre>
|
||||
</div>
|
||||
)}
|
||||
{route.view !== "tracked" && pending && mixes?.length === 0 && (
|
||||
{(route.view === "mix" || route.view === "liked") && pending && mixes?.length === 0 && (
|
||||
<div className="notice"><span className="spinner" /> Building mixes from your recent listens…</div>
|
||||
)}
|
||||
{route.view === "tracked" ? (
|
||||
{route.view === "account" ? (
|
||||
<AccountView
|
||||
account={props.account}
|
||||
onChange={props.onAccountChange}
|
||||
onLogout={props.onLogout}
|
||||
onToast={(message) => setToast({ message })}
|
||||
/>
|
||||
) : route.view === "tracked" ? (
|
||||
<TrackedView defaultUser={rule?.tracking_user} onToast={(message) => setToast({ message })} />
|
||||
) : route.view === "liked" ? (
|
||||
<LikedView liked={liked} player={player} onStatus={onStatus} />
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import { FormEvent, useCallback, useEffect, useState } from "react";
|
||||
import { Account, authApi, UNAUTHORIZED_EVENT } from "./api";
|
||||
import { App } from "./App";
|
||||
import * as Icon from "./icons";
|
||||
|
||||
type State =
|
||||
| { kind: "loading" }
|
||||
| { kind: "unreachable"; message: string }
|
||||
| { kind: "setup" }
|
||||
| { kind: "login"; expired?: boolean }
|
||||
| { kind: "ready"; account: Account };
|
||||
|
||||
/** Shows the app once logged in. The first visit creates the account instead. */
|
||||
export function AuthGate() {
|
||||
const [state, setState] = useState<State>({ kind: "loading" });
|
||||
|
||||
const check = useCallback(() => {
|
||||
authApi.status().then(
|
||||
(s) =>
|
||||
setState(
|
||||
s.account
|
||||
? { kind: "ready", account: s.account }
|
||||
: s.setup_required
|
||||
? { kind: "setup" }
|
||||
: { kind: "login" },
|
||||
),
|
||||
(e) => setState({ kind: "unreachable", message: e.message }),
|
||||
);
|
||||
}, []);
|
||||
useEffect(check, [check]);
|
||||
|
||||
// the session ran out (or was logged out elsewhere) while using the app
|
||||
useEffect(() => {
|
||||
const onUnauthorized = () =>
|
||||
setState((s) => (s.kind === "ready" ? { kind: "login", expired: true } : s));
|
||||
window.addEventListener(UNAUTHORIZED_EVENT, onUnauthorized);
|
||||
return () => window.removeEventListener(UNAUTHORIZED_EVENT, onUnauthorized);
|
||||
}, []);
|
||||
|
||||
switch (state.kind) {
|
||||
case "loading":
|
||||
return <div className="auth-page"><span className="spinner" aria-label="Loading" /></div>;
|
||||
case "unreachable":
|
||||
return (
|
||||
<div className="auth-page">
|
||||
<div className="notice error" role="alert">
|
||||
Couldn't reach playlistd ({state.message})
|
||||
<button className="btn" onClick={check}>Try again</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
case "setup":
|
||||
case "login":
|
||||
return (
|
||||
<CredentialsForm
|
||||
setup={state.kind === "setup"}
|
||||
expired={state.kind === "login" && state.expired}
|
||||
onDone={(account) => setState({ kind: "ready", account })}
|
||||
// someone else finished setting up first
|
||||
onRecheck={check}
|
||||
/>
|
||||
);
|
||||
case "ready":
|
||||
return (
|
||||
<App
|
||||
account={state.account}
|
||||
onAccountChange={(account) => setState({ kind: "ready", account })}
|
||||
onLogout={() => setState({ kind: "login" })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function CredentialsForm(props: {
|
||||
setup: boolean;
|
||||
expired?: boolean;
|
||||
onDone: (account: Account) => void;
|
||||
onRecheck: () => void;
|
||||
}) {
|
||||
const { setup } = props;
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [confirm, setConfirm] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (setup && password !== confirm) {
|
||||
setError("The passwords don't match");
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
props.onDone(setup ? await authApi.setup(username, password) : await authApi.login(username, password));
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
setBusy(false);
|
||||
if (setup) props.onRecheck();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="auth-page">
|
||||
<form className="auth-card" onSubmit={submit} aria-labelledby="auth-heading">
|
||||
<div className="brand">
|
||||
<span className="brand-mark"><Icon.Sparkle size={16} /></span>
|
||||
playlistd
|
||||
</div>
|
||||
<div>
|
||||
<h1 id="auth-heading">{setup ? "Create your account" : "Log in"}</h1>
|
||||
<p className="hint">
|
||||
{setup
|
||||
? "Choose the username and password you'll use to log in to playlistd from now on."
|
||||
: props.expired
|
||||
? "Your session has ended. Log in again to continue."
|
||||
: "Log in to continue."}
|
||||
</p>
|
||||
</div>
|
||||
<label className="field">
|
||||
<span>Username</span>
|
||||
<input
|
||||
required
|
||||
autoFocus
|
||||
maxLength={64}
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
autoComplete="username"
|
||||
autoCapitalize="none"
|
||||
spellCheck={false}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Password</span>
|
||||
<input
|
||||
required
|
||||
type="password"
|
||||
minLength={setup ? 8 : undefined}
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete={setup ? "new-password" : "current-password"}
|
||||
/>
|
||||
{setup && <span className="hint">At least 8 characters</span>}
|
||||
</label>
|
||||
{setup && (
|
||||
<label className="field">
|
||||
<span>Confirm password</span>
|
||||
<input
|
||||
required
|
||||
type="password"
|
||||
value={confirm}
|
||||
onChange={(e) => setConfirm(e.target.value)}
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
{error && <p className="form-error" role="alert">{error}</p>}
|
||||
<button className="btn primary" type="submit" disabled={busy}>
|
||||
{busy && <span className="spinner light" />}
|
||||
{setup ? "Create account" : "Log in"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+36
-3
@@ -49,14 +49,22 @@ export type MixDetail = MixSummary & {
|
||||
suggestions: Suggestion[];
|
||||
};
|
||||
|
||||
/** Fired when the API says the session has ended, so the app can ask to log in again */
|
||||
export const UNAUTHORIZED_EVENT = "playlistd:unauthorized";
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit, base = "/api/discover"): Promise<T> {
|
||||
const response = await fetch(`${base}${path}`, init);
|
||||
if (!response.ok) {
|
||||
// (a failed login is just a wrong password)
|
||||
if (response.status === 401 && `${base}${path}` !== "/api/auth/login") {
|
||||
window.dispatchEvent(new Event(UNAUTHORIZED_EVENT));
|
||||
}
|
||||
// the API explains what went wrong where it can
|
||||
const body = await response.json().catch(() => null);
|
||||
throw new Error(body?.error ?? `${response.status} ${response.statusText}`);
|
||||
}
|
||||
return response.status === 204 ? (undefined as T) : response.json();
|
||||
const text = await response.text();
|
||||
return text ? JSON.parse(text) : (undefined as T);
|
||||
}
|
||||
|
||||
const json = (method: string, body: unknown): RequestInit => ({
|
||||
@@ -76,8 +84,7 @@ export const api = {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ status }),
|
||||
}),
|
||||
rebuild: (ruleId: string) =>
|
||||
fetch(`/api/discover/rules/${ruleId}/rebuild`, { method: "POST" }),
|
||||
rebuild: (ruleId: string) => request<void>(`/rules/${ruleId}/rebuild`, { method: "POST" }),
|
||||
};
|
||||
|
||||
export const coverUrl = (coverArt: string, size = 120) =>
|
||||
@@ -149,3 +156,29 @@ export const trackedApi = {
|
||||
previewName: (template: string) =>
|
||||
tracked<{ name: string }>(`/preview-name?template=${encodeURIComponent(template)}`),
|
||||
};
|
||||
|
||||
// ---------- account ----------
|
||||
|
||||
export type Account = {
|
||||
username: string;
|
||||
/** The Listenbrainz user the saved token belongs to */
|
||||
listenbrainz_user: string | null;
|
||||
has_listenbrainz_token: boolean;
|
||||
};
|
||||
|
||||
export type AuthStatus = {
|
||||
/** No account exists yet: the first visit creates it */
|
||||
setup_required: boolean;
|
||||
account: Account | null;
|
||||
};
|
||||
|
||||
const auth = <T>(path: string, init?: RequestInit) => request<T>(path, init, "/api/auth");
|
||||
|
||||
export const authApi = {
|
||||
status: () => auth<AuthStatus>("/status"),
|
||||
setup: (username: string, password: string) => auth<Account>("/setup", json("POST", { username, password })),
|
||||
login: (username: string, password: string) => auth<Account>("/login", json("POST", { username, password })),
|
||||
logout: () => auth<void>("/logout", { method: "POST" }),
|
||||
/** An empty token removes the saved one */
|
||||
setListenbrainzToken: (token: string) => auth<Account>("/account/listenbrainz", json("PUT", { token })),
|
||||
};
|
||||
@@ -20,3 +20,4 @@ export const Trash = ({ size }: P) => svg(<><path d="M4 7h16" /><path d="M9 7V4h
|
||||
export const ListMusic = ({ size }: P) => svg(<><path d="M4 6h11M4 11h11M4 16h7" /><circle cx="17" cy="17" r="2.5" /><path d="M19.5 17V8l2-1" /></>, size);
|
||||
export const Calendar = ({ size }: P) => svg(<><rect x="4" y="5" width="16" height="15" rx="2" /><path d="M4 10h16M9 3v4M15 3v4" /></>, size);
|
||||
export const Warning = ({ size }: P) => svg(<><path d="M12 4l9 16H3z" /><path d="M12 10v4M12 17v.5" /></>, size);
|
||||
export const User = ({ size }: P) => svg(<><circle cx="12" cy="8" r="4" /><path d="M4 20c1.5-3.5 4.5-5 8-5s6.5 1.5 8 5" /></>, size);
|
||||
@@ -1,10 +1,10 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { App } from "./App";
|
||||
import { AuthGate } from "./Auth";
|
||||
import "./styles.css";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
<AuthGate />
|
||||
</StrictMode>,
|
||||
);
|
||||
+75
-1
@@ -1005,6 +1005,78 @@ h2 {
|
||||
color: var(--accent-text);
|
||||
}
|
||||
|
||||
/* ---------- login & account ---------- */
|
||||
|
||||
.auth-page {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-height: 100vh;
|
||||
padding: 24px 16px;
|
||||
}
|
||||
|
||||
.auth-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
width: 100%;
|
||||
max-width: 380px;
|
||||
padding: 28px 24px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--surface);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.auth-card .brand {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.auth-card h1 {
|
||||
margin: 0 0 4px;
|
||||
font-size: 1.4rem;
|
||||
}
|
||||
|
||||
.auth-card .btn {
|
||||
min-height: 40px;
|
||||
}
|
||||
|
||||
.auth-page .notice {
|
||||
align-items: flex-start;
|
||||
max-width: 480px;
|
||||
}
|
||||
|
||||
.account-link {
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.account-link .mix-dot {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.token-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 0 0 4px;
|
||||
font-size: 0.92rem;
|
||||
}
|
||||
|
||||
.status-dot {
|
||||
flex: none;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--muted);
|
||||
}
|
||||
|
||||
.status-dot.ok {
|
||||
background: var(--library);
|
||||
}
|
||||
|
||||
.hint a {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
/* ---------- small screens ---------- */
|
||||
|
||||
@media (max-width: 800px) {
|
||||
@@ -1048,7 +1120,9 @@ h2 {
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.liked-link {
|
||||
.liked-link,
|
||||
.manage-link,
|
||||
.account-link {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
|
||||
@@ -94,6 +94,18 @@ export function usePlayer(onError: (item: QueueItem) => void) {
|
||||
};
|
||||
}, [next]);
|
||||
|
||||
// stop playing when the app goes away (e.g. on logging out)
|
||||
useEffect(
|
||||
() => () => {
|
||||
const el = audio.current;
|
||||
if (!el) return;
|
||||
el.pause();
|
||||
el.removeAttribute("src");
|
||||
el.load();
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// OS media controls and keyboard
|
||||
useEffect(() => {
|
||||
if (!("mediaSession" in navigator) || !current) return;
|
||||
|
||||
Reference in new issue
Block a user