From 53c1bffa6d9083266a0b50149561e72a73370cb9 Mon Sep 17 00:00:00 2001 From: jude Date: Mon, 16 Nov 2026 19:24:09 +0000 Subject: [PATCH] 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 --- .env.example | 7 +- ...de39ef9883b134c4f1ad97d55ad7c9bead982.json | 16 + ...79512502acdd22d64bd65b540294306fd2bd0.json | 16 + ...6b5bf77a3540a3b46bcc3051ae2d3c5a0e17d.json | 16 + ...8a04c9b2f4ed00929c30bdd723cfe16103332.json | 12 + ...19b8a225ef01ac92825065860cb868b04cbd9.json | 20 + ...834d0a41c153ceba338b00ff52f3e1ae39fe4.json | 34 ++ ...a5be640c1e868bb5815d81302dbf8423b069d.json | 12 + ...b09f91845d1c9a54e785bbd6596c59450d635.json | 22 + ...819d9e5fed89d01e301a736a4f654c8a0bfd3.json | 20 + ...eed0de8f47901a1c9dcdf9544196b9b175916.json | 14 + ...4769b1372979f76c52fb97bc9827cc86abe1b.json | 28 ++ Cargo.lock | 34 ++ Cargo.toml | 2 + README.md | 53 ++- compose.yaml | 2 +- discover/src/AccountView.tsx | 130 ++++++ discover/src/App.tsx | 34 +- discover/src/Auth.tsx | 166 ++++++++ discover/src/api.ts | 39 +- discover/src/icons.tsx | 1 + discover/src/main.tsx | 4 +- discover/src/styles.css | 76 +++- discover/src/usePlayer.ts | 12 + etc/playlistd/playlistd.toml | 3 +- migrations/20261116120000_users.sql | 21 + src/auth.rs | 396 ++++++++++++++++++ src/daemon/cluster_mixes.rs | 1 + src/discover.rs | 6 +- src/listenbrainz.rs | 35 +- src/main.rs | 12 +- src/tracked.rs | 30 +- src/web.rs | 14 +- 33 files changed, 1249 insertions(+), 39 deletions(-) create mode 100644 .sqlx/query-1664ef4607bff9355a30d553780de39ef9883b134c4f1ad97d55ad7c9bead982.json create mode 100644 .sqlx/query-75d690ffc887165aba3ac37072679512502acdd22d64bd65b540294306fd2bd0.json create mode 100644 .sqlx/query-79e547f7fb9bf3c629d349dfc4c6b5bf77a3540a3b46bcc3051ae2d3c5a0e17d.json create mode 100644 .sqlx/query-a3e08cec820c4f37a3461e7e7a88a04c9b2f4ed00929c30bdd723cfe16103332.json create mode 100644 .sqlx/query-a4d51df9526259bd7f3341afe8319b8a225ef01ac92825065860cb868b04cbd9.json create mode 100644 .sqlx/query-a8a3265d8f0f08b56916fe819a3834d0a41c153ceba338b00ff52f3e1ae39fe4.json create mode 100644 .sqlx/query-ac37067164bcfe2ea8c63cc99b3a5be640c1e868bb5815d81302dbf8423b069d.json create mode 100644 .sqlx/query-d0171f1d23c5841e10273ec5682b09f91845d1c9a54e785bbd6596c59450d635.json create mode 100644 .sqlx/query-ec78315cfbf742b58210c77586c819d9e5fed89d01e301a736a4f654c8a0bfd3.json create mode 100644 .sqlx/query-f4112415eb717ca8f6a558430d8eed0de8f47901a1c9dcdf9544196b9b175916.json create mode 100644 .sqlx/query-fb7dbbd693490f4e7ecdcdb85e14769b1372979f76c52fb97bc9827cc86abe1b.json create mode 100644 discover/src/AccountView.tsx create mode 100644 discover/src/Auth.tsx create mode 100644 migrations/20261116120000_users.sql create mode 100644 src/auth.rs diff --git a/.env.example b/.env.example index 65c18e6..8b97e2f 100644 --- a/.env.example +++ b/.env.example @@ -10,11 +10,12 @@ SUBSONIC_PASSWORD= POSTGRES_PASSWORD= # Optional: your Listenbrainz user token (listenbrainz.org/settings), to find new songs for each -# genre mix with LB Radio +# genre mix with LB Radio. You can also save it to your account in the web UI, which takes priority. LISTENBRAINZ_TOKEN= -# Where to serve playlistd. It has no login, so it only listens on this machine by default; set -# PLAYLISTD_BIND=0.0.0.0 to make it reachable from your network. +# Where to serve playlistd. The first visit to the web UI creates the login, and anyone who gets +# there first can, so it only listens on this machine by default. Once you've created your account, +# set PLAYLISTD_BIND=0.0.0.0 to make it reachable from your network. PLAYLISTD_BIND=127.0.0.1 PLAYLISTD_PORT=8000 diff --git a/.sqlx/query-1664ef4607bff9355a30d553780de39ef9883b134c4f1ad97d55ad7c9bead982.json b/.sqlx/query-1664ef4607bff9355a30d553780de39ef9883b134c4f1ad97d55ad7c9bead982.json new file mode 100644 index 0000000..f88b3ec --- /dev/null +++ b/.sqlx/query-1664ef4607bff9355a30d553780de39ef9883b134c4f1ad97d55ad7c9bead982.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE \"app_user\" SET listenbrainz_token = $1, listenbrainz_user = $2 WHERE id = $3", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Varchar", + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "1664ef4607bff9355a30d553780de39ef9883b134c4f1ad97d55ad7c9bead982" +} diff --git a/.sqlx/query-75d690ffc887165aba3ac37072679512502acdd22d64bd65b540294306fd2bd0.json b/.sqlx/query-75d690ffc887165aba3ac37072679512502acdd22d64bd65b540294306fd2bd0.json new file mode 100644 index 0000000..77cd188 --- /dev/null +++ b/.sqlx/query-75d690ffc887165aba3ac37072679512502acdd22d64bd65b540294306fd2bd0.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO \"app_user\" (id, username, password_hash) VALUES ($1, $2, $3)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Varchar", + "Text" + ] + }, + "nullable": [] + }, + "hash": "75d690ffc887165aba3ac37072679512502acdd22d64bd65b540294306fd2bd0" +} diff --git a/.sqlx/query-79e547f7fb9bf3c629d349dfc4c6b5bf77a3540a3b46bcc3051ae2d3c5a0e17d.json b/.sqlx/query-79e547f7fb9bf3c629d349dfc4c6b5bf77a3540a3b46bcc3051ae2d3c5a0e17d.json new file mode 100644 index 0000000..a66d279 --- /dev/null +++ b/.sqlx/query-79e547f7fb9bf3c629d349dfc4c6b5bf77a3540a3b46bcc3051ae2d3c5a0e17d.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO \"user_session\" (token_hash, user_id, expires_at)\n VALUES ($1, $2, NOW() + make_interval(days => $3))\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Bytea", + "Uuid", + "Int4" + ] + }, + "nullable": [] + }, + "hash": "79e547f7fb9bf3c629d349dfc4c6b5bf77a3540a3b46bcc3051ae2d3c5a0e17d" +} diff --git a/.sqlx/query-a3e08cec820c4f37a3461e7e7a88a04c9b2f4ed00929c30bdd723cfe16103332.json b/.sqlx/query-a3e08cec820c4f37a3461e7e7a88a04c9b2f4ed00929c30bdd723cfe16103332.json new file mode 100644 index 0000000..5137664 --- /dev/null +++ b/.sqlx/query-a3e08cec820c4f37a3461e7e7a88a04c9b2f4ed00929c30bdd723cfe16103332.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM \"user_session\" WHERE expires_at <= NOW()", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "a3e08cec820c4f37a3461e7e7a88a04c9b2f4ed00929c30bdd723cfe16103332" +} diff --git a/.sqlx/query-a4d51df9526259bd7f3341afe8319b8a225ef01ac92825065860cb868b04cbd9.json b/.sqlx/query-a4d51df9526259bd7f3341afe8319b8a225ef01ac92825065860cb868b04cbd9.json new file mode 100644 index 0000000..57a8942 --- /dev/null +++ b/.sqlx/query-a4d51df9526259bd7f3341afe8319b8a225ef01ac92825065860cb868b04cbd9.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT listenbrainz_token AS \"token!\" FROM \"app_user\"\n WHERE listenbrainz_token IS NOT NULL\n ORDER BY created_at\n LIMIT 1\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "token!", + "type_info": "Text" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + true + ] + }, + "hash": "a4d51df9526259bd7f3341afe8319b8a225ef01ac92825065860cb868b04cbd9" +} diff --git a/.sqlx/query-a8a3265d8f0f08b56916fe819a3834d0a41c153ceba338b00ff52f3e1ae39fe4.json b/.sqlx/query-a8a3265d8f0f08b56916fe819a3834d0a41c153ceba338b00ff52f3e1ae39fe4.json new file mode 100644 index 0000000..63c13a3 --- /dev/null +++ b/.sqlx/query-a8a3265d8f0f08b56916fe819a3834d0a41c153ceba338b00ff52f3e1ae39fe4.json @@ -0,0 +1,34 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT username, listenbrainz_user, listenbrainz_token IS NOT NULL AS \"has_listenbrainz_token!\"\n FROM \"app_user\" WHERE id = $1\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "username", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "listenbrainz_user", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "has_listenbrainz_token!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + true, + null + ] + }, + "hash": "a8a3265d8f0f08b56916fe819a3834d0a41c153ceba338b00ff52f3e1ae39fe4" +} diff --git a/.sqlx/query-ac37067164bcfe2ea8c63cc99b3a5be640c1e868bb5815d81302dbf8423b069d.json b/.sqlx/query-ac37067164bcfe2ea8c63cc99b3a5be640c1e868bb5815d81302dbf8423b069d.json new file mode 100644 index 0000000..c74ef51 --- /dev/null +++ b/.sqlx/query-ac37067164bcfe2ea8c63cc99b3a5be640c1e868bb5815d81302dbf8423b069d.json @@ -0,0 +1,12 @@ +{ + "db_name": "PostgreSQL", + "query": "LOCK TABLE \"app_user\" IN SHARE ROW EXCLUSIVE MODE", + "describe": { + "columns": [], + "parameters": { + "Left": [] + }, + "nullable": [] + }, + "hash": "ac37067164bcfe2ea8c63cc99b3a5be640c1e868bb5815d81302dbf8423b069d" +} diff --git a/.sqlx/query-d0171f1d23c5841e10273ec5682b09f91845d1c9a54e785bbd6596c59450d635.json b/.sqlx/query-d0171f1d23c5841e10273ec5682b09f91845d1c9a54e785bbd6596c59450d635.json new file mode 100644 index 0000000..1e833bd --- /dev/null +++ b/.sqlx/query-d0171f1d23c5841e10273ec5682b09f91845d1c9a54e785bbd6596c59450d635.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT user_id FROM \"user_session\" WHERE token_hash = $1 AND expires_at > NOW()", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "user_id", + "type_info": "Uuid" + } + ], + "parameters": { + "Left": [ + "Bytea" + ] + }, + "nullable": [ + false + ] + }, + "hash": "d0171f1d23c5841e10273ec5682b09f91845d1c9a54e785bbd6596c59450d635" +} diff --git a/.sqlx/query-ec78315cfbf742b58210c77586c819d9e5fed89d01e301a736a4f654c8a0bfd3.json b/.sqlx/query-ec78315cfbf742b58210c77586c819d9e5fed89d01e301a736a4f654c8a0bfd3.json new file mode 100644 index 0000000..9b8ecb4 --- /dev/null +++ b/.sqlx/query-ec78315cfbf742b58210c77586c819d9e5fed89d01e301a736a4f654c8a0bfd3.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (SELECT 1 FROM \"app_user\") AS \"e!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "e!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null + ] + }, + "hash": "ec78315cfbf742b58210c77586c819d9e5fed89d01e301a736a4f654c8a0bfd3" +} diff --git a/.sqlx/query-f4112415eb717ca8f6a558430d8eed0de8f47901a1c9dcdf9544196b9b175916.json b/.sqlx/query-f4112415eb717ca8f6a558430d8eed0de8f47901a1c9dcdf9544196b9b175916.json new file mode 100644 index 0000000..88a0bca --- /dev/null +++ b/.sqlx/query-f4112415eb717ca8f6a558430d8eed0de8f47901a1c9dcdf9544196b9b175916.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM \"user_session\" WHERE token_hash = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Bytea" + ] + }, + "nullable": [] + }, + "hash": "f4112415eb717ca8f6a558430d8eed0de8f47901a1c9dcdf9544196b9b175916" +} diff --git a/.sqlx/query-fb7dbbd693490f4e7ecdcdb85e14769b1372979f76c52fb97bc9827cc86abe1b.json b/.sqlx/query-fb7dbbd693490f4e7ecdcdb85e14769b1372979f76c52fb97bc9827cc86abe1b.json new file mode 100644 index 0000000..4996e27 --- /dev/null +++ b/.sqlx/query-fb7dbbd693490f4e7ecdcdb85e14769b1372979f76c52fb97bc9827cc86abe1b.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id, password_hash FROM \"app_user\" WHERE username = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "password_hash", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "fb7dbbd693490f4e7ecdcdb85e14769b1372979f76c52fb97bc9827cc86abe1b" +} diff --git a/Cargo.lock b/Cargo.lock index 299423d..153e507 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -97,6 +97,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures", + "password-hash", +] + [[package]] name = "arraydeque" version = "0.5.1" @@ -220,6 +232,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -1471,6 +1492,17 @@ dependencies = [ "windows-targets 0.48.5", ] +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core", + "subtle", +] + [[package]] name = "pathdiff" version = "0.2.3" @@ -1603,6 +1635,7 @@ checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" name = "playlistd" version = "0.2.6" dependencies = [ + "argon2", "chrono", "config", "env_logger", @@ -1614,6 +1647,7 @@ dependencies = [ "rocket", "serde", "serde_json", + "sha2", "sqlx", "thiserror 2.0.17", "tokio", diff --git a/Cargo.toml b/Cargo.toml index 5b6d060..2f90b3e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,8 @@ rand = "0.8" serde_json = "1.0" futures-util = "0.3" tokio-util = { version = "0.7", features = ["io"] } +argon2 = "0.5" +sha2 = "0.10" [package.metadata.deb] depends = "$auto" diff --git a/README.md b/README.md index 52e2344..dc3b0a4 100644 --- a/README.md +++ b/README.md @@ -32,8 +32,10 @@ cp .env.example .env # then fill in your Subsonic server and a database passw docker compose up -d --build ``` -The web UI is then at http://localhost:8000. playlistd has no login, so it only listens on the -Docker host by default; set `PLAYLISTD_BIND=0.0.0.0` in `.env` to open it to your network. If your +The web UI is then at http://localhost:8000. The first visit asks you to create an account (see +[Logging in](#logging-in)), and anyone who reaches it first can, so it only listens on the Docker +host by default: create your account, then set `PLAYLISTD_BIND=0.0.0.0` in `.env` to open it to +your network. If your Subsonic server runs on the Docker host, use `http://host.docker.internal:4533/rest` as `SUBSONIC_BASE`. @@ -136,10 +138,10 @@ Mixes are rebuilt every `refresh_hours`. On a rebuild, existing mix playlists ar new cluster with the most similar genres (and renamed), new playlists are created for new clusters, and playlists for clusters that no longer appear are deleted. -Create a rule through the API: +Create a rule through the API (after logging in, see [Logging in](#logging-in)): ```sh -curl -X POST localhost:8000/api/playlist/mix -H 'Content-Type: application/json' \ +curl -b cookies -X POST localhost:8000/api/playlist/mix -H 'Content-Type: application/json' \ -d '{"tracking_user": "jellywx", "months": 3, "playlist_size": 50}' ``` @@ -170,7 +172,8 @@ your library yet. Each time the mixes are rebuilt, playlistd also looks for new songs for each mix: * your Listenbrainz recommendations, keeping only recordings you've never listened to, and -* if `listenbrainz.token` is set, an LB Radio playlist for each mix's top genres. +* if a Listenbrainz token is saved to your account (or `listenbrainz.token` is set), an LB Radio + playlist for each mix's top genres. Every candidate's MusicBrainz genres are compared with each mix's, and it's suggested in the mix it fits best (if it fits well enough), skipping songs already in your library. @@ -197,6 +200,46 @@ and set `discover.ui` (or `DISCOVER_UI`) to the `discover/dist` directory to ser playlistd at `/`. For development, `npm run dev` serves the UI with hot reload and forwards API requests to playlistd on `localhost:8000` (or `PLAYLISTD_URL`). +### Logging in + +The web UI and every API endpoint need you to log in. There's no default account: the first time +anyone opens the UI, it asks for a username and password, and creates the account with them. After +that, the UI shows a login page instead, and new accounts can't be created. Passwords are stored as +Argon2id hashes in the `app_user` table, and logging in sets a session cookie that lasts 30 days. + +To start over (e.g. if you forget your password), delete the account, and the next visit to the UI +will set it up again: + +```sql +DELETE FROM app_user; +``` + +Under the account page in the UI (your username, in the sidebar), you can save your Listenbrainz +user token to your account. It's checked with Listenbrainz first, and is then used instead of +`listenbrainz.token` from the config. + +To use the API from a script, log in with a cookie jar and pass it with each request: + +```sh +curl -c cookies -X POST localhost:8000/api/auth/login -H 'Content-Type: application/json' \ + -d '{"username": "you", "password": "your password"}' +curl -b cookies localhost:8000/api/tracked/playlists +``` + +Requests without a valid session get `401 {"error": "Log in to continue"}`. These endpoints are +under `/api/auth`: + +| Endpoint | Purpose | +|------------------------------|---------------------------------------------------------------| +| `GET /status` | Whether the account still has to be set up, and who's logged in | +| `POST /setup` | Create the account (`username`, `password`), only if there isn't one | +| `POST /login` | Log in (`username`, `password`) | +| `POST /logout` | Log out | +| `GET /account` | The logged in account | +| `PUT /account/listenbrainz` | Save a Listenbrainz `token` to the account (empty removes it) | + +### Endpoints + The UI uses these endpoints under `/api/discover`: | Endpoint | Purpose | diff --git a/compose.yaml b/compose.yaml index 2810b43..832d9c0 100644 --- a/compose.yaml +++ b/compose.yaml @@ -14,7 +14,7 @@ services: db: condition: service_healthy ports: - # playlistd has no login, so by default it's only reachable from this machine + # the first visit creates the login, so by default it's only reachable from this machine - "${PLAYLISTD_BIND:-127.0.0.1}:${PLAYLISTD_PORT:-8000}:8000" environment: DATABASE_URL: postgres://playlistd:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}@db/playlistd diff --git a/discover/src/AccountView.tsx b/discover/src/AccountView.tsx new file mode 100644 index 0000000..350a36c --- /dev/null +++ b/discover/src/AccountView.tsx @@ -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(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 ( +
+
+

Account

+

{account.username}

+
+ +
+
+
+

Listenbrainz token

+

+ Lets playlistd find new songs for each mix's genres with LB Radio, on top of your + recommendations. Find yours at{" "} + + listenbrainz.org/settings + + . New songs are picked up the next time your mixes are rebuilt. +

+
+
+ +

+ {account.has_listenbrainz_token ? ( + <> +

+ +
+ + {error &&

{error}

} +
+ {account.has_listenbrainz_token && ( + + )} + +
+
+
+ +
+
+
+

Session

+

Logged in as {account.username} in this browser.

+
+ +
+
+
+ ); +} diff --git a/discover/src/App.tsx b/discover/src/App.tsx index ca9268e..a359c48 100644 --- a/discover/src/App.tsx +++ b/discover/src/App.tsx @@ -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(null); const [ruleId, setRuleId] = useState(storedRule); const [mixes, setMixes] = useState(null); @@ -201,22 +206,35 @@ export function App() { Tracked playlists +
  • + + + {props.account.username} + +
  • {error &&
    {error}
    } - {route.view !== "tracked" && rules && rules.length === 0 && ( + {(route.view === "mix" || route.view === "liked") && rules && rules.length === 0 && (

    No mix rules yet

    Create one, and playlistd will cluster your listens into genre mixes:

    -
    {`curl -X POST /api/playlist/mix -H 'Content-Type: application/json' \\\n  -d '{"tracking_user": "your-listenbrainz-name"}'`}
    +
    {`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"}'`}
    )} - {route.view !== "tracked" && pending && mixes?.length === 0 && ( + {(route.view === "mix" || route.view === "liked") && pending && mixes?.length === 0 && (
    Building mixes from your recent listens…
    )} - {route.view === "tracked" ? ( + {route.view === "account" ? ( + setToast({ message })} + /> + ) : route.view === "tracked" ? ( setToast({ message })} /> ) : route.view === "liked" ? ( diff --git a/discover/src/Auth.tsx b/discover/src/Auth.tsx new file mode 100644 index 0000000..2adcbae --- /dev/null +++ b/discover/src/Auth.tsx @@ -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({ 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
    ; + case "unreachable": + return ( +
    +
    + Couldn't reach playlistd ({state.message}) + +
    +
    + ); + case "setup": + case "login": + return ( + setState({ kind: "ready", account })} + // someone else finished setting up first + onRecheck={check} + /> + ); + case "ready": + return ( + 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(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 ( +
    +
    +
    + + playlistd +
    +
    +

    {setup ? "Create your account" : "Log in"}

    +

    + {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."} +

    +
    + + + {setup && ( + + )} + {error &&

    {error}

    } + +
    +
    + ); +} diff --git a/discover/src/api.ts b/discover/src/api.ts index ccd6270..d7cc81c 100644 --- a/discover/src/api.ts +++ b/discover/src/api.ts @@ -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(path: string, init?: RequestInit, base = "/api/discover"): Promise { 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(`/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 = (path: string, init?: RequestInit) => request(path, init, "/api/auth"); + +export const authApi = { + status: () => auth("/status"), + setup: (username: string, password: string) => auth("/setup", json("POST", { username, password })), + login: (username: string, password: string) => auth("/login", json("POST", { username, password })), + logout: () => auth("/logout", { method: "POST" }), + /** An empty token removes the saved one */ + setListenbrainzToken: (token: string) => auth("/account/listenbrainz", json("PUT", { token })), +}; diff --git a/discover/src/icons.tsx b/discover/src/icons.tsx index 03a0756..7370538 100644 --- a/discover/src/icons.tsx +++ b/discover/src/icons.tsx @@ -20,3 +20,4 @@ export const Trash = ({ size }: P) => svg(<>, size); export const Calendar = ({ size }: P) => svg(<>, size); export const Warning = ({ size }: P) => svg(<>, size); +export const User = ({ size }: P) => svg(<>, size); diff --git a/discover/src/main.tsx b/discover/src/main.tsx index 71c1087..bff1f88 100644 --- a/discover/src/main.tsx +++ b/discover/src/main.tsx @@ -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( - + , ); diff --git a/discover/src/styles.css b/discover/src/styles.css index 0f53006..c45c47f 100644 --- a/discover/src/styles.css +++ b/discover/src/styles.css @@ -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; diff --git a/discover/src/usePlayer.ts b/discover/src/usePlayer.ts index efb5ead..e04da4e 100644 --- a/discover/src/usePlayer.ts +++ b/discover/src/usePlayer.ts @@ -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; diff --git a/etc/playlistd/playlistd.toml b/etc/playlistd/playlistd.toml index 94bfc6a..cf4a0b3 100644 --- a/etc/playlistd/playlistd.toml +++ b/etc/playlistd/playlistd.toml @@ -21,7 +21,8 @@ url = "postgres:///navidrome-playlists" [listenbrainz] # Your Listenbrainz user token (listenbrainz.org/settings). Optional: lets the discover UI -# find new songs for each mix's genres with LB Radio, on top of your recommendations +# find new songs for each mix's genres with LB Radio, on top of your recommendations. +# A token saved to your account in the web UI takes priority over this one # token = "" [discover] diff --git a/migrations/20261116120000_users.sql b/migrations/20261116120000_users.sql new file mode 100644 index 0000000..a96d8be --- /dev/null +++ b/migrations/20261116120000_users.sql @@ -0,0 +1,21 @@ +-- The account that logs in to the web UI. The first visit to the UI creates it. +CREATE TABLE "app_user" +( + id UUID NOT NULL PRIMARY KEY, + username VARCHAR(64) NOT NULL UNIQUE, + password_hash TEXT NOT NULL, -- Argon2id, in PHC string format + listenbrainz_token TEXT, -- Used for Listenbrainz endpoints that need one (e.g. LB Radio) + listenbrainz_user VARCHAR(250), -- The Listenbrainz user the token belongs to + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +-- Logged in browsers. Only a hash of the session token is stored. +CREATE TABLE "user_session" +( + token_hash BYTEA NOT NULL PRIMARY KEY, -- SHA-256 of the token in the session cookie + user_id UUID NOT NULL REFERENCES "app_user" (id) ON DELETE CASCADE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + expires_at TIMESTAMPTZ NOT NULL +); + +CREATE INDEX "user_session_expires_at" ON "user_session" (expires_at); diff --git a/src/auth.rs b/src/auth.rs new file mode 100644 index 0000000..0599a30 --- /dev/null +++ b/src/auth.rs @@ -0,0 +1,396 @@ +//! Login for the web UI and its API. +//! +//! The first visit to the UI creates the account (there's no default one); after that, every API +//! request needs a session cookie from logging in. Passwords are hashed with Argon2id, and only a +//! SHA-256 hash of each session token is stored, so the database alone can't be used to log in. + +use crate::listenbrainz; +use argon2::password_hash::{ + rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString, +}; +use argon2::Argon2; +use rand::RngCore; +use rocket::http::{Cookie, CookieJar, SameSite, Status}; +use rocket::request::{FromRequest, Outcome}; +use rocket::response::status::Custom; +use rocket::serde::json::Json; +use rocket::{catch, get, post, put, routes, Request, Route, State}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use sqlx::postgres::PgPool; +use std::sync::OnceLock; +use uuid::Uuid; + +pub const COOKIE: &str = "playlistd_session"; +const SESSION_DAYS: i64 = 30; +const MIN_PASSWORD: usize = 8; +const MAX_USERNAME: usize = 64; + +pub fn routes() -> Vec { + routes![ + status, + setup, + login, + logout, + account, + set_listenbrainz_token + ] +} + +#[derive(Serialize)] +pub struct ApiError { + error: String, +} + +type ApiResult = Result, Custom>>; + +fn error(status: Status, message: impl Into) -> Custom> { + Custom( + status, + Json(ApiError { + error: message.into(), + }), + ) +} + +fn db_error(e: sqlx::Error) -> Custom> { + log::error!("Database error: {}", e); + error(Status::InternalServerError, "Database error") +} + +/// API requests without a valid session get this instead of Rocket's HTML page +#[catch(401)] +pub fn unauthorized() -> Json { + Json(ApiError { + error: "Log in to continue".to_string(), + }) +} + +/// The logged in user. Add it as a request guard to a route to require logging in: requests +/// without a valid session fail with 401. +pub struct User { + pub id: Uuid, +} + +#[rocket::async_trait] +impl<'r> FromRequest<'r> for User { + type Error = (); + + async fn from_request(request: &'r Request<'_>) -> Outcome { + let Some(token) = request.cookies().get(COOKIE).map(|c| c.value().to_string()) else { + return Outcome::Error((Status::Unauthorized, ())); + }; + let pool = match request.guard::<&State>().await { + Outcome::Success(pool) => pool, + _ => return Outcome::Error((Status::InternalServerError, ())), + }; + match sqlx::query_scalar!( + r#"SELECT user_id FROM "user_session" WHERE token_hash = $1 AND expires_at > NOW()"#, + &hash_token(&token)[..] + ) + .fetch_optional(pool.inner()) + .await + { + Ok(Some(id)) => Outcome::Success(User { id }), + Ok(None) => Outcome::Error((Status::Unauthorized, ())), + Err(e) => { + log::error!("Database error checking session: {}", e); + Outcome::Error((Status::InternalServerError, ())) + } + } + } +} + +fn hash_token(token: &str) -> Vec { + Sha256::digest(token.as_bytes()).to_vec() +} + +/// Argon2 is deliberately slow, so it runs off the async workers +async fn hash_password(password: String) -> Result>> { + tokio::task::spawn_blocking(move || { + let salt = SaltString::generate(&mut OsRng); + Argon2::default() + .hash_password(password.as_bytes(), &salt) + .map(|h| h.to_string()) + }) + .await + .ok() + .and_then(Result::ok) + .ok_or_else(|| error(Status::InternalServerError, "Couldn't hash the password")) +} + +async fn verify_password(password: String, hash: String) -> bool { + tokio::task::spawn_blocking(move || { + PasswordHash::new(&hash) + .map(|parsed| { + Argon2::default() + .verify_password(password.as_bytes(), &parsed) + .is_ok() + }) + .unwrap_or(false) + }) + .await + .unwrap_or(false) +} + +/// A hash to check passwords against when the username doesn't exist, so that a wrong username +/// takes as long as a wrong password +fn dummy_hash() -> &'static str { + static HASH: OnceLock = OnceLock::new(); + HASH.get_or_init(|| { + Argon2::default() + .hash_password(b"not a password", &SaltString::generate(&mut OsRng)) + .map(|h| h.to_string()) + .unwrap_or_default() + }) +} + +/// Start a session for a user and give the browser its cookie +async fn start_session( + pool: &PgPool, + cookies: &CookieJar<'_>, + user_id: Uuid, +) -> Result<(), Custom>> { + let mut bytes = [0u8; 32]; + rand::rngs::OsRng.fill_bytes(&mut bytes); + let token: String = bytes.iter().map(|b| format!("{:02x}", b)).collect(); + + sqlx::query!(r#"DELETE FROM "user_session" WHERE expires_at <= NOW()"#) + .execute(pool) + .await + .map_err(db_error)?; + sqlx::query!( + r#" + INSERT INTO "user_session" (token_hash, user_id, expires_at) + VALUES ($1, $2, NOW() + make_interval(days => $3)) + "#, + &hash_token(&token)[..], + user_id, + SESSION_DAYS as i32 + ) + .execute(pool) + .await + .map_err(db_error)?; + + cookies.add( + Cookie::build((COOKIE, token)) + .path("/") + .http_only(true) + .same_site(SameSite::Strict) + .max_age(rocket::time::Duration::days(SESSION_DAYS)), + ); + Ok(()) +} + +#[derive(Serialize)] +struct Account { + username: String, + /// The Listenbrainz user the saved token belongs to. The token itself is never sent back. + listenbrainz_user: Option, + has_listenbrainz_token: bool, +} + +async fn load_account(pool: &PgPool, id: Uuid) -> Result>> { + sqlx::query_as!( + Account, + r#" + SELECT username, listenbrainz_user, listenbrainz_token IS NOT NULL AS "has_listenbrainz_token!" + FROM "app_user" WHERE id = $1 + "#, + id + ) + .fetch_one(pool) + .await + .map_err(db_error) +} + +#[derive(Serialize)] +struct AuthStatus { + /// No account exists yet, so the UI should ask for a username and password to create one + setup_required: bool, + /// The logged in account, if any + account: Option, +} + +#[get("/status")] +async fn status(pool: &State, user: Option) -> ApiResult { + let setup_required = + !sqlx::query_scalar!(r#"SELECT EXISTS (SELECT 1 FROM "app_user") AS "e!""#) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + let account = match user { + Some(user) => Some(load_account(pool.inner(), user.id).await?), + None => None, + }; + Ok(Json(AuthStatus { + setup_required, + account, + })) +} + +#[derive(Deserialize)] +struct Credentials { + username: String, + password: String, +} + +/// Create the account. Only works while there isn't one yet. +#[post("/setup", data = "")] +async fn setup( + pool: &State, + cookies: &CookieJar<'_>, + credentials: Json, +) -> ApiResult { + let username = credentials.username.trim().to_string(); + if username.is_empty() || username.chars().count() > MAX_USERNAME { + return Err(error( + Status::UnprocessableEntity, + format!("Choose a username of 1 to {} characters", MAX_USERNAME), + )); + } + if credentials.password.chars().count() < MIN_PASSWORD { + return Err(error( + Status::UnprocessableEntity, + format!("Use a password of at least {} characters", MIN_PASSWORD), + )); + } + let password_hash = hash_password(credentials.password.clone()).await?; + + // the lock makes concurrent setups wait, so only the first one creates an account + let mut tx = pool.begin().await.map_err(db_error)?; + sqlx::query!(r#"LOCK TABLE "app_user" IN SHARE ROW EXCLUSIVE MODE"#) + .execute(&mut *tx) + .await + .map_err(db_error)?; + let exists = sqlx::query_scalar!(r#"SELECT EXISTS (SELECT 1 FROM "app_user") AS "e!""#) + .fetch_one(&mut *tx) + .await + .map_err(db_error)?; + if exists { + return Err(error( + Status::Conflict, + "The account has already been set up", + )); + } + let id = Uuid::new_v4(); + sqlx::query!( + r#"INSERT INTO "app_user" (id, username, password_hash) VALUES ($1, $2, $3)"#, + id, + username, + password_hash + ) + .execute(&mut *tx) + .await + .map_err(db_error)?; + tx.commit().await.map_err(db_error)?; + log::info!("Created account {}", username); + + start_session(pool.inner(), cookies, id).await?; + load_account(pool.inner(), id).await.map(Json) +} + +#[post("/login", data = "")] +async fn login( + pool: &State, + cookies: &CookieJar<'_>, + credentials: Json, +) -> ApiResult { + let user = sqlx::query!( + r#"SELECT id, password_hash FROM "app_user" WHERE username = $1"#, + credentials.username.trim() + ) + .fetch_optional(pool.inner()) + .await + .map_err(db_error)?; + + let hash = user + .as_ref() + .map(|u| u.password_hash.clone()) + .unwrap_or_else(|| dummy_hash().to_string()); + let valid = verify_password(credentials.password.clone(), hash).await; + match user { + Some(user) if valid => { + start_session(pool.inner(), cookies, user.id).await?; + load_account(pool.inner(), user.id).await.map(Json) + } + _ => { + log::warn!("Failed login for {:?}", credentials.username.trim()); + Err(error(Status::Unauthorized, "Wrong username or password")) + } + } +} + +#[post("/logout")] +async fn logout( + pool: &State, + cookies: &CookieJar<'_>, +) -> Result>> { + if let Some(cookie) = cookies.get(COOKIE) { + sqlx::query!( + r#"DELETE FROM "user_session" WHERE token_hash = $1"#, + &hash_token(cookie.value())[..] + ) + .execute(pool.inner()) + .await + .map_err(db_error)?; + } + cookies.remove(Cookie::build(COOKIE).path("/")); + Ok(Status::NoContent) +} + +#[get("/account")] +async fn account(pool: &State, user: User) -> ApiResult { + load_account(pool.inner(), user.id).await.map(Json) +} + +#[derive(Deserialize)] +struct ListenbrainzToken { + /// Empty or missing removes the saved token + token: Option, +} + +/// Save a Listenbrainz user token to the account, after checking it with Listenbrainz +#[put("/account/listenbrainz", data = "")] +async fn set_listenbrainz_token( + pool: &State, + user: User, + body: Json, +) -> ApiResult { + let token = body + .token + .as_deref() + .map(str::trim) + .filter(|t| !t.is_empty()); + + let listenbrainz_user = match token { + Some(token) => match listenbrainz::validate_token(token).await { + Ok(Some(name)) => Some(name), + Ok(None) => { + return Err(error( + Status::UnprocessableEntity, + "Listenbrainz says that token isn't valid", + )) + } + Err(e) => { + log::warn!("Could not check Listenbrainz token: {}", e); + return Err(error( + Status::BadGateway, + "Couldn't reach Listenbrainz to check the token", + )); + } + }, + None => None, + }; + + sqlx::query!( + r#"UPDATE "app_user" SET listenbrainz_token = $1, listenbrainz_user = $2 WHERE id = $3"#, + token, + listenbrainz_user, + user.id + ) + .execute(pool.inner()) + .await + .map_err(db_error)?; + load_account(pool.inner(), user.id).await.map(Json) +} diff --git a/src/daemon/cluster_mixes.rs b/src/daemon/cluster_mixes.rs index d561fb6..cd3cf45 100644 --- a/src/daemon/cluster_mixes.rs +++ b/src/daemon/cluster_mixes.rs @@ -318,6 +318,7 @@ async fn save_suggestions( recently_played, &exclude, rule.discovery_count.max(0) as usize, + listenbrainz::token(database).await, ) .await?; diff --git a/src/discover.rs b/src/discover.rs index 1859a2d..0eb03a5 100644 --- a/src/discover.rs +++ b/src/discover.rs @@ -2,7 +2,7 @@ //! //! Candidates come from Listenbrainz's collaborative filtering recommendations //! for the user (filtered to recordings they've never listened to) and, if a -//! Listenbrainz token is configured, an LB Radio prompt built from each mix's +//! Listenbrainz token is saved to the account (or configured), an LB Radio prompt built from each mix's //! top genres. Every candidate's MusicBrainz genres are compared with each //! mix's genre profile (cosine similarity) and it's assigned to the mix it fits //! best. Songs already in the library, or played recently, are skipped. @@ -59,6 +59,8 @@ pub async fn suggest( // recordings that already have a suggestion the user acted on exclude: &HashSet, per_mix: usize, + // a Listenbrainz user token, to also ask LB Radio for candidates + token: Option, ) -> Result, Box> { if targets.is_empty() || per_mix == 0 { return Ok(vec![]); @@ -72,7 +74,7 @@ pub async fn suggest( .map(|r| r.recording_mbid) .collect(); - if let Some(token) = listenbrainz::token() { + if let Some(token) = token { for target in targets { let genres: Vec<&str> = target .profile diff --git a/src/listenbrainz.rs b/src/listenbrainz.rs index e808599..6325456 100644 --- a/src/listenbrainz.rs +++ b/src/listenbrainz.rs @@ -471,8 +471,24 @@ pub async fn recommendations( .mbids) } -/// The user token from the config, needed by some endpoints (e.g. LB Radio) -pub fn token() -> Option { +/// The user token needed by some endpoints (e.g. LB Radio): the one saved to the account in the +/// web UI, or otherwise `listenbrainz.token` from the config +pub async fn token(database: &sqlx::PgPool) -> Option { + match sqlx::query_scalar!( + r#" + SELECT listenbrainz_token AS "token!" FROM "app_user" + WHERE listenbrainz_token IS NOT NULL + ORDER BY created_at + LIMIT 1 + "# + ) + .fetch_optional(database) + .await + { + Ok(Some(token)) => return Some(token), + Ok(None) => {} + Err(e) => log::warn!("Could not load the account's Listenbrainz token: {}", e), + } crate::CONFIG .get()? .get::("listenbrainz.token") @@ -480,6 +496,21 @@ pub fn token() -> Option { .filter(|t| !t.is_empty()) } +#[derive(Deserialize)] +struct ValidateTokenResponse { + valid: bool, + user_name: Option, +} + +/// The name of the Listenbrainz user a token belongs to, or `None` if it isn't valid +pub async fn validate_token(token: &str) -> Result, reqwest::Error> { + let request = reqwest::Client::new() + .get(format!("{}/validate-token", BASE)) + .header(reqwest::header::AUTHORIZATION, format!("Token {}", token)); + let response = send_json::(request).await?; + Ok(response.user_name.filter(|_| response.valid)) +} + #[derive(Deserialize)] struct RadioResponse { payload: RadioPayload, diff --git a/src/main.rs b/src/main.rs index f9c531d..3cb42c1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,4 @@ +mod auth; mod cluster; mod daemon; mod discover; @@ -11,6 +12,7 @@ mod tracked; mod web; mod youtube; +use crate::auth::User; use crate::daemon::{cluster_mixes_daemon, create_playlists_daemon, update_playlists_daemon}; use crate::models::{ ClusterMixRule, CreateTrackedPlaylist, PartialClusterMixRule, PartialCreateTrackedPlaylist, @@ -95,6 +97,8 @@ async fn main() -> Result<(), Box> { .manage(media_client) .manage(database) .manage(youtube) + .mount("/api/auth", auth::routes()) + .register("/api", rocket::catchers![auth::unauthorized]) .mount("/api/discover", web::routes()) .mount("/api/tracked", tracked::routes()) .mount( @@ -214,6 +218,7 @@ pub struct CreatePlaylist { /// Create a new playlist and attach a tracker #[post("/rule", data = "")] async fn create_tracking_playlist_rule( + _user: User, pool: &State, create_playlist_rule: Json, ) -> Json> { @@ -226,6 +231,7 @@ async fn create_tracking_playlist_rule( /// Create a new playlist and attach a tracker #[post("/create", data = "")] async fn create_tracking_playlist( + _user: User, media_client: &State>, pool: &State, create_playlist: Json, @@ -257,6 +263,7 @@ async fn create_tracking_playlist( /// Add tracking to an existing playlist #[post("/track", data = "")] async fn add_tracking_playlist( + _user: User, pool: &State, playlist: Json, ) -> Json> { @@ -268,7 +275,7 @@ async fn add_tracking_playlist( /// Get all tracked playlists #[get("/")] -async fn all_playlists(pool: &State) -> JsonValue { +async fn all_playlists(_user: User, pool: &State) -> JsonValue { match TrackedPlaylist::all(pool.inner()).await { Ok(playlists) => json!(playlists), Err(_) => json!([]), @@ -278,6 +285,7 @@ async fn all_playlists(pool: &State) -> JsonValue { /// Create a rule that maintains genre mixes built from clustering a user's recent listens #[post("/mix", data = "")] async fn create_cluster_mix_rule( + _user: User, pool: &State, rule: Json, ) -> Json> { @@ -289,7 +297,7 @@ async fn create_cluster_mix_rule( /// Get all cluster mix rules #[get("/mix")] -async fn all_cluster_mix_rules(pool: &State) -> JsonValue { +async fn all_cluster_mix_rules(_user: User, pool: &State) -> JsonValue { match ClusterMixRule::all(pool.inner()).await { Ok(rules) => json!(rules), Err(_) => json!([]), diff --git a/src/tracked.rs b/src/tracked.rs index c16f687..8993a6a 100644 --- a/src/tracked.rs +++ b/src/tracked.rs @@ -1,6 +1,7 @@ //! API for managing tracked playlists (Subsonic playlists kept up to date with a Listenbrainz //! user's top songs) and the rules that create them on a schedule. +use crate::auth::User; use crate::daemon::update_playlists::update_playlist; use crate::listenbrainz::StatsRange; use crate::models::{CreateTrackedPlaylist, TrackedPlaylist}; @@ -159,6 +160,7 @@ async fn view( #[get("/playlists")] async fn playlists( + _user: User, pool: &State, media_client: &State>, ) -> ApiResult> { @@ -187,6 +189,7 @@ struct NewTrackedPlaylist { #[post("/playlists", data = "")] async fn create_playlist( + _user: User, body: Json, pool: &State, media_client: &State>, @@ -267,6 +270,7 @@ struct TrackedPlaylistUpdate { #[put("/playlists/", data = "")] async fn update_tracked_playlist( + _user: User, id: &str, body: Json, pool: &State, @@ -307,6 +311,7 @@ async fn update_tracked_playlist( /// Stop tracking a playlist, optionally deleting it from Subsonic too #[delete("/playlists/?")] async fn delete_tracked_playlist( + _user: User, id: &str, delete_playlist: Option, pool: &State, @@ -335,6 +340,7 @@ async fn delete_tracked_playlist( /// Update a tracked playlist's songs now, rather than on the next daemon tick #[post("/playlists//refresh")] async fn refresh( + _user: User, id: &str, pool: &State, media_client: &State>, @@ -379,6 +385,7 @@ async fn mix_playlist_ids(pool: &PgPool) -> Result, Custom, media_client: &State>, ) -> ApiResult> { @@ -426,7 +433,7 @@ fn rule_view(rule: CreateTrackedPlaylist) -> RuleView { } #[get("/rules")] -async fn rules(pool: &State) -> ApiResult> { +async fn rules(_user: User, pool: &State) -> ApiResult> { let mut rules = CreateTrackedPlaylist::all(pool.inner()) .await .map_err(db_error)?; @@ -442,7 +449,11 @@ struct RuleBody { } #[post("/rules", data = "")] -async fn create_rule(body: Json, pool: &State) -> ApiResult { +async fn create_rule( + _user: User, + body: Json, + pool: &State, +) -> ApiResult { body.tracking.validate()?; format_template(&body.name_template)?; @@ -467,7 +478,12 @@ async fn create_rule(body: Json, pool: &State) -> ApiResult", data = "")] -async fn update_rule(id: &str, body: Json, pool: &State) -> ApiResult { +async fn update_rule( + _user: User, + id: &str, + body: Json, + pool: &State, +) -> ApiResult { body.tracking.validate()?; format_template(&body.name_template)?; @@ -493,7 +509,11 @@ async fn update_rule(id: &str, body: Json, pool: &State) -> Ap /// Delete a rule. Playlists it already created keep being tracked. #[delete("/rules/")] -async fn delete_rule(id: &str, pool: &State) -> Result>> { +async fn delete_rule( + _user: User, + id: &str, + pool: &State, +) -> Result>> { let result = sqlx::query!( r#"DELETE FROM "create_tracked_playlist" WHERE id = $1"#, parse_id(id)? @@ -514,7 +534,7 @@ struct NamePreview { /// What a name template produces today #[get("/preview-name?