diff --git a/.github/workflows/build-and-publish.yml b/.github/workflows/build-and-publish.yml index 5138b2d..662c093 100644 --- a/.github/workflows/build-and-publish.yml +++ b/.github/workflows/build-and-publish.yml @@ -48,4 +48,5 @@ jobs: push: ${{ github.event_name != 'pull_request' }} tags: ${{ steps.meta.outputs.docker_tags }} cache-from: type=registry,ref=${{ env.IMAGE_NAME }}:buildcache + # Export intermediate stages, including cargo-chef's compiled dependencies. cache-to: type=registry,ref=${{ env.IMAGE_NAME }}:buildcache,mode=max diff --git a/Cargo.toml b/Cargo.toml index 43f08fd..2de0e9f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "furumusic" -version = "0.12.3" +version = "0.12.4" edition = "2024" description = "Reusable web-app boilerplate: auth, OIDC/SSO, admin panel, user management, i18n, PostgreSQL" diff --git a/Dockerfile b/Dockerfile index 7de5191..e7d596f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,18 +1,31 @@ -FROM rust:1-bookworm AS builder +FROM rust:1.97.0-bookworm AS chef RUN apt-get update \ && apt-get install -y --no-install-recommends pkg-config libssl-dev ca-certificates \ && rm -rf /var/lib/apt/lists/* +RUN cargo install cargo-chef --version 0.1.74 --locked + WORKDIR /app -COPY Cargo.toml Cargo.lock* ./ +FROM chef AS planner +COPY Cargo.toml Cargo.lock ./ +COPY build.rs ./build.rs +COPY src ./src +RUN cargo chef prepare --recipe-path recipe.json + +FROM chef AS builder +COPY --from=planner /app/recipe.json ./recipe.json +# Keep compiled dependencies in an ordinary layer exported by CI's registry cache. +RUN cargo chef cook --release --locked --recipe-path recipe.json + +COPY Cargo.toml Cargo.lock ./ COPY build.rs ./build.rs COPY prompts ./prompts COPY src ./src COPY templates ./templates -RUN cargo build --release +RUN cargo build --release --locked --bin furumusic FROM denoland/deno:bin-2.8.3 AS deno diff --git a/README.md b/README.md index f4c0498..eefd1c9 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,8 @@ catalog and media files; the browser is only the player. - a responsive web player with artists, releases, search, queue, and playlists; - direct file uploads and imports from YouTube, torrent files, or magnet links; - optional AI-assisted recognition and normalization of metadata; -- password login or OIDC/SSO with group-based access control; +- password login or OIDC/SSO with group grants and local administrator approval; +- public track, release, and queue links with scoped guest playback and downloads; - optional federation without a central catalog or search service; - trusted-device pairing, playback handoff, and synchronization between Furumi players; @@ -32,6 +33,46 @@ catalog and media files; the browser is only the player. Furumusic does not include music. Import only media you are allowed to store and share. +## Access and public sharing + +OIDC identifies accounts by issuer and subject. Matching admin groups take +precedence over matching user groups, and either SSO grant takes precedence over +a local role. Without matching groups (including an empty group configuration), +a new account waits for approval in **Admin → Users**. Any instance administrator +can approve it as a user or administrator. The waiting page updates automatically. +On subsequent SSO logins the group grant is refreshed: if it disappears, only an +independently assigned local role preserves access. Existing password accounts +keep their local roles; existing OIDC-only accounts retain their last SSO grant +until the next login, without receiving an implicit local approval. + +Sharing creates an unguessable `/share/{token}` link to a snapshot of track IDs, +including their order and repetitions. Guests and accounts awaiting approval can +play and download only the tracks in that snapshot, using the regular player. +They cannot browse the library, search, use recommendations, or write personal +history. Signing in from a share returns to that share; signing in from the root +shows only the approval page until access is granted. Track info offers a browser +download of the original audio file. The old radio implementation is removed. + +Migration `m_0053_local_approval_and_public_shares` deletes the old share records. +Old track/release/playlist URL routes are removed, with no compatibility layer. +Link expiry, cleanup, and revocation are not part of this implementation. + +The access regression suite uses a disposable migrated database and a local OIDC +provider with signed tokens and PKCE: + +```bash +node --test tests/*.test.cjs +FURU_ACCESS_TEST_DATABASE_URL=postgresql://... cargo test postgres_approval_survives_sso_changes_without_implicit_grants -- --ignored +# Fresh disposable instance on :18048, media root /tmp/furumi-access-media, +# PostgreSQL container furumi-access-test-pg, database furumi_access_test: +node tests/browser-access-sharing.cjs +``` + +The browser test requires Playwright (`PLAYWRIGHT_MODULE`) and Chrome +(`CHROME_PATH`), and uses local port 18049 for its OIDC provider. It checks +approval, SSO precedence and group removal, guest playback and downloads, +unauthorized track substitution, and desktop/mobile player behavior. + ## Importing music Users can add audio files from the web interface or ask the server to download @@ -96,6 +137,13 @@ The repository also contains a multi-stage `Dockerfile` for building a small runtime image. A deployment must provide PostgreSQL plus persistent, writable volumes for the inbox and music library. +CI uses Rust 1.97.0 and cargo-chef 0.1.74 to cache compiled dependencies separately +from application sources. Buildx imports and exports intermediate layers through +`ultradesu/furumusic:buildcache` (`mode=max`). After the first build, changes to +source code, templates or prompts reuse the dependency layer when its recipe and +toolchain are unchanged. Both dependency and application builds use `--locked`. +Update the pinned build tools in `Dockerfile`; changing them rebuilds the cache. + ## Admin statistics The only admin interface is `/admin/v2`, also reachable from `/admin/`. diff --git a/src/admin/management.rs b/src/admin/management.rs index 4245f9a..ff0bd84 100644 --- a/src/admin/management.rs +++ b/src/admin/management.rs @@ -28,7 +28,18 @@ pub(super) async fn manage_user( Ok(u) => u, Err(r) => return Ok(r), }; - if body.action == "delete" { + if body.action == "approve" { + let Some(id) = body.id.filter(|id| *id > 0) else { + return Ok(json_error(StatusCode::BAD_REQUEST, "Invalid user")); + }; + if Role::from_code(&body.role).is_none() || (id == admin.id && body.role != "admin") { + return Ok(json_error(StatusCode::BAD_REQUEST, "Invalid role")); + } + let Some(mut user) = User::get_by_id(&db, id).await? else { + return Ok(json_error(StatusCode::NOT_FOUND, "User not found")); + }; + user.approve(&db, &body.role, admin.id).await?; + } else if body.action == "delete" { let Some(id) = body.id.filter(|id| *id > 0) else { return Ok(json_error(StatusCode::BAD_REQUEST, "Invalid user")); }; @@ -43,7 +54,8 @@ pub(super) async fn manage_user( if !["create", "update"].contains(&body.action.as_str()) || body.username.trim().is_empty() || body.username.chars().count() > 255 - || Role::from_code(&body.role).is_none() + || (Role::from_code(&body.role).is_none() + && !(body.action == "update" && body.role.is_empty())) || (body.action == "create" && body.password.is_empty()) { return Ok(json_error( @@ -74,15 +86,15 @@ pub(super) async fn manage_user( let Some(id) = body.id.filter(|id| *id > 0) else { return Ok(json_error(StatusCode::BAD_REQUEST, "Invalid user")); }; - if id == admin.id && body.role != "admin" { + let Some(mut user) = User::get_by_id(&db, id).await? else { + return Ok(json_error(StatusCode::NOT_FOUND, "User not found")); + }; + if id == admin.id && body.role != "admin" && !user.has_sso_admin_role() { return Ok(json_error( StatusCode::BAD_REQUEST, "You cannot remove your own administrator role", )); } - let Some(mut user) = User::get_by_id(&db, id).await? else { - return Ok(json_error(StatusCode::NOT_FOUND, "User not found")); - }; if User::get_by_username(&db, body.username.trim()) .await? .is_some_and(|u| u.id_val() != id) diff --git a/src/admin/v2.rs b/src/admin/v2.rs index 34b307e..72a4ebc 100644 --- a/src/admin/v2.rs +++ b/src/admin/v2.rs @@ -230,6 +230,8 @@ struct AdminUserRowDto { email: Option, role: String, is_active: bool, + local_role: Option, + sso_role: Option, is_online: bool, last_seen_ms: Option, plays: i64, @@ -2667,6 +2669,8 @@ struct AdminUserSqlRow { email: Option, role: String, is_active: bool, + local_role: Option, + sso_role: Option, plays: i64, listened_seconds: i64, last_play_ms: Option, @@ -2700,7 +2704,7 @@ async fn load_admin_users_page( let total: i64 = count_qb.build_query_scalar().fetch_one(pool).await?; let mut qb = QueryBuilder::::new( - "SELECT id, username::text, display_name, email, role::text, is_active, \ + "SELECT id, username::text, display_name, email, role::text, is_active, local_role, sso_role, \ (SELECT COUNT(*) FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id AND qualified) AS plays, \ (SELECT (COALESCE(SUM(listened_ms), 0) / 1000)::bigint FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id) AS listened_seconds, \ (SELECT MAX(started_at_ms) FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id AND qualified) AS last_play_ms \ @@ -2715,7 +2719,7 @@ async fn load_admin_users_page( qb.push_bind(pattern); qb.push(")"); } - qb.push(" ORDER BY username ASC LIMIT "); + qb.push(" ORDER BY is_active ASC, username ASC LIMIT "); qb.push_bind(limit); qb.push(" OFFSET "); qb.push_bind(offset); @@ -2747,7 +2751,7 @@ async fn load_admin_user_detail( user_id: i64, ) -> anyhow::Result> { let row = sqlx::query_as::<_, AdminUserSqlRow>( - "SELECT id, username::text, display_name, email, role::text, is_active, \ + "SELECT id, username::text, display_name, email, role::text, is_active, local_role, sso_role, \ (SELECT COUNT(*) FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id AND qualified) AS plays, \ (SELECT (COALESCE(SUM(listened_ms), 0) / 1000)::bigint FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id) AS listened_seconds, \ (SELECT MAX(started_at_ms) FROM furumusic__listen_event le WHERE le.user_id = furumusic__user.id AND qualified) AS last_play_ms \ @@ -2939,6 +2943,8 @@ fn admin_user_row( email: row.email, role: row.role, is_active: row.is_active, + local_role: row.local_role, + sso_role: row.sso_role, plays: row.plays, listened_seconds: row.listened_seconds, last_play_ms: row.last_play_ms, diff --git a/src/auth.rs b/src/auth.rs index 70557a5..12fd2d0 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -72,8 +72,13 @@ fn authenticated_user_from_user(user: User) -> Option { }) } -/// Read `user_id` from the session, fetch the `User` from DB, return -/// `AuthenticatedUser` if the user exists and is active. +/// Return the signed-in identity, including an account awaiting approval. +pub async fn get_session_identity(session: &Session, db: &Database) -> Option { + let user_id: i64 = session.get(SESSION_USER_ID).await.ok()??; + User::get_by_id(db, user_id).await.ok()? +} + +/// Return a session user only when access to the instance has been granted. pub async fn get_session_user(session: &Session, db: &Database) -> Option { let user_id: i64 = session.get(SESSION_USER_ID).await.ok()??; let user = User::get_by_id(db, user_id).await.ok()??; diff --git a/src/i18n/phrases.rs b/src/i18n/phrases.rs index 0763d69..777e2d1 100644 --- a/src/i18n/phrases.rs +++ b/src/i18n/phrases.rs @@ -1,6 +1,12 @@ use super::translations; translations! { + approval_heading: "Awaiting approval", "Ожидается одобрение"; + approval_message: "You are signed in. An instance administrator must approve your account before you can access the library.", "Вы вошли в аккаунт. Для доступа к библиотеке нужно одобрение администратора инстанса."; + guest_login: "Sign in / register", "Войти / зарегистрироваться"; + guest_label: "Shared music", "Музыка по ссылке"; + share_unavailable: "This link is unavailable or contains no playable tracks.", "Ссылка недоступна или не содержит доступных треков."; + track_download: "Download", "Скачать"; // Global site_name: "furumusic" , "furumusic"; @@ -71,7 +77,7 @@ translations! { settings_oidc_admin_groups: "Admin groups" , "Группы администраторов"; settings_oidc_admin_groups_help: "Comma-separated OIDC group names that grant admin role (e.g. /admin,/furumusic-admins)" , "OIDC группы через запятую, дающие роль администратора (напр. /admin,/furumusic-admins)"; settings_oidc_user_groups: "User groups" , "Группы пользователей"; - settings_oidc_user_groups_help: "Comma-separated OIDC group names allowed to access the service. If empty, any authenticated SSO user is allowed." , "OIDC группы через запятую, которым разрешён доступ к сервису. Если пусто, разрешён любой SSO пользователь."; + settings_oidc_user_groups_help: "Comma-separated OIDC groups granting automatic user access. Everyone else needs local administrator approval." , "OIDC группы через запятую, дающие автоматический доступ. Остальным нужно локальное одобрение администратора."; // User management nav_users: "Users" , "Пользователи"; @@ -360,8 +366,6 @@ translations! { player_play: "Play" , "Играть"; player_listen: "Listen" , "Слушать"; player_listen_artist: "Listen to artist" , "Слушать артиста"; - player_start_radio: "Start radio" , "Запустить радио"; - player_radio_failed: "Could not start radio" , "Не удалось запустить радио"; player_played_at: "Played" , "Прослушано"; player_like: "Like" , "Лайк"; player_add_to_queue: "Add to queue" , "Добавить в очередь"; diff --git a/src/main.rs b/src/main.rs index 004346a..d3a02c4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -70,59 +70,64 @@ fn build_registry() -> Arc { // Handlers // --------------------------------------------------------------------------- -#[derive(Deserialize)] -struct IndexQuery { - track: Option, - release: Option, - playlist_share: Option, +async fn index(session: Session, db: Database, i18n: I18n) -> cot::Result { + render_player(session, db, i18n, String::new()).await } -async fn index( +async fn render_player( session: Session, db: Database, i18n: I18n, - UrlQuery(query): UrlQuery, + share_token: String, ) -> cot::Result { - let _user = match auth::get_session_user(&session, &db).await { - Some(u) => u, - None => { - if let Some(location) = share_query_redirect(&query) { - auth::remember_post_login_redirect(&session, &location).await?; - } - return Ok(auth::redirect("/login")); + let guest = auth::get_session_user(&session, &db).await.is_none(); + if guest && share_token.is_empty() { + if auth::get_session_identity(&session, &db).await.is_some() { + return Html::new(PendingTemplate { t: i18n.t }.render()?).into_response(); } - }; + return Ok(auth::redirect("/login")); + } let (config, _) = AppConfig::load_with_db(&db).await; - let template = player::PlayerPageTemplate { - t: i18n.t, - downloads_enabled: config.downloads_enabled, - torrent_downloads_enabled: config.downloads_enabled && config.torrent_downloads_enabled, - youtube_downloads_enabled: config.downloads_enabled && config.youtube_downloads_enabled, - }; - Html::new(template.render()?).into_response() + Html::new( + player::PlayerPageTemplate { + t: i18n.t, + guest, + share_token, + downloads_enabled: !guest && config.downloads_enabled, + torrent_downloads_enabled: !guest + && config.downloads_enabled + && config.torrent_downloads_enabled, + youtube_downloads_enabled: !guest + && config.downloads_enabled + && config.youtube_downloads_enabled, + } + .render()?, + ) + .into_response() } -fn share_query_redirect(query: &IndexQuery) -> Option { - if let Some(track_id) = query.track.filter(|id| *id > 0) { - return Some(format!("/?track={track_id}")); - } - if let Some(release_id) = query.release.filter(|id| *id > 0) { - return Some(format!("/?release={release_id}")); - } - let token = query.playlist_share.as_deref()?.trim(); - if is_share_token(token) { - Some(format!("/?playlist_share={token}")) - } else { - None - } +#[derive(Debug, Template)] +#[template(path = "pending.html")] +struct PendingTemplate { + t: &'static Translations, +} + +async fn access_status(session: Session, db: Database) -> cot::Result { + let identity = auth::get_session_identity(&session, &db).await; + let status = match identity { + Some(user) if user.is_active() => "active", + Some(_) => "pending", + None => "anonymous", + }; + let mut response = cot::json::Json(serde_json::json!({"status": status})).into_response()?; + response + .headers_mut() + .insert("Cache-Control", "private, no-store".parse().unwrap()); + Ok(response) } fn is_share_token(token: &str) -> bool { - !token.is_empty() - && token.len() <= 64 - && token - .bytes() - .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_')) + token.len() == 32 && token.bytes().all(|b| b.is_ascii_hexdigit()) } #[derive(Deserialize)] @@ -187,11 +192,7 @@ struct LoginForm { #[derive(Deserialize)] struct LoginQuery { error: Option, -} - -#[derive(Deserialize)] -struct SharePathId { - id: i64, + next: Option, } #[derive(Deserialize)] @@ -236,56 +237,26 @@ async fn metrics_handler( .expect("valid response")) } -async fn share_track_handler( - session: Session, - db: Database, - Path(path): Path, -) -> cot::Result { - let location = if path.id > 0 { - format!("/?track={}", path.id) - } else { - "/".to_string() - }; - if auth::get_session_user(&session, &db).await.is_none() { - auth::remember_post_login_redirect(&session, &location).await?; - return Ok(auth::redirect("/login")); - } - Ok(auth::redirect(&location)) -} - -async fn share_release_handler( - session: Session, - db: Database, - Path(path): Path, -) -> cot::Result { - let location = if path.id > 0 { - format!("/?release={}", path.id) - } else { - "/".to_string() - }; - if auth::get_session_user(&session, &db).await.is_none() { - auth::remember_post_login_redirect(&session, &location).await?; - return Ok(auth::redirect("/login")); - } - Ok(auth::redirect(&location)) -} - -async fn share_playlist_handler( +async fn share_handler( session: Session, db: Database, + i18n: I18n, Path(path): Path, ) -> cot::Result { - let token = path.token.trim(); - let location = if is_share_token(token) { - format!("/?playlist_share={token}") - } else { - "/".to_string() - }; - if auth::get_session_user(&session, &db).await.is_none() { - auth::remember_post_login_redirect(&session, &location).await?; - return Ok(auth::redirect("/login")); + if !is_share_token(&path.token) { + return Ok(cot::http::Response::builder() + .status(cot::http::StatusCode::NOT_FOUND) + .body(Body::fixed("Shared music not found")) + .expect("valid response")); } - Ok(auth::redirect(&location)) + let mut response = render_player(session, db, i18n, path.token).await?; + response + .headers_mut() + .insert("Referrer-Policy", "no-referrer".parse().unwrap()); + response + .headers_mut() + .insert("Cache-Control", "private, no-store".parse().unwrap()); + Ok(response) } // --------------------------------------------------------------------------- @@ -316,26 +287,13 @@ impl App for FuruApp { ), Route::with_handler_and_name( "/", - |session: Session, db: Database, i18n: I18n, query: UrlQuery| async move { - index(session, db, i18n, query).await + |session: Session, db: Database, i18n: I18n| async move { + index(session, db, i18n).await }, "index", ), - Route::with_handler_and_name( - "/share/track/{id}", - get(share_track_handler), - "share_track", - ), - Route::with_handler_and_name( - "/share/release/{id}", - get(share_release_handler), - "share_release", - ), - Route::with_handler_and_name( - "/share/playlist/{token}", - get(share_playlist_handler), - "share_playlist", - ), + Route::with_handler_and_name("/share/{token}", get(share_handler), "share"), + Route::with_handler_and_name("/auth/status", get(access_status), "access_status"), Route::with_handler_and_name( "/metrics", get({ @@ -353,13 +311,29 @@ impl App for FuruApp { "/login", get({ let config = Arc::clone(&self.config); - move |i18n: I18n, db: Database, query: UrlQuery| { + move |i18n: I18n, + db: Database, + session: Session, + query: UrlQuery| { let config = Arc::clone(&config); async move { // No users at all → redirect to first-run setup if User::count_all(&db).await.unwrap_or(0) == 0 { return Ok(auth::redirect("/admin/setup")); } + if let Some(next) = query.0.next.as_deref() { + if next.strip_prefix("/share/").is_some_and(is_share_token) { + auth::remember_post_login_redirect(&session, next).await?; + } + } else { + auth::clear_post_login_redirect(&session).await?; + } + if auth::get_session_identity(&session, &db).await.is_some() { + let destination = auth::get_post_login_redirect(&session) + .await? + .unwrap_or_else(|| "/".into()); + return Ok(auth::redirect(&destination)); + } let message = query.0.error.unwrap_or_default(); login_page_handler(i18n, &config, db, message) .await? diff --git a/src/metrics.rs b/src/metrics.rs index a3cbeb5..13b68a5 100644 --- a/src/metrics.rs +++ b/src/metrics.rs @@ -808,9 +808,8 @@ const KNOWN_HTTP_ROUTES: &[&str] = &[ "/admin", "/swagger", "/swagger/openapi.json", - "/share/track/{id}", - "/share/release/{id}", - "/share/playlist/{token}", + "/share/{token}", + "/auth/status", "/metrics", "/login", "/logout", @@ -880,10 +879,11 @@ const KNOWN_HTTP_ROUTES: &[&str] = &[ "/api/player/artists", "/api/player/artists/{id}", "/api/player/releases/{id}", - "/api/player/radio/{kind}/{id}", "/api/player/playlists", - "/api/player/share-playlist", - "/api/player/share-playlist/{id}", + "/api/player/shares", + "/api/player/shares/{id}", + "/api/player/shares/{token}/{action}/{track_id}", + "/api/player/download/{track_id}", "/api/player/playlists/{id}", "/api/player/playlists/{id}/tracks", "/api/player/likes", @@ -928,13 +928,10 @@ mod tests { known_http_route("/admin/v2/api/jobs/metadata_backfill/runs/123"), Some("/admin/v2/api/jobs/{name}/runs/{run_id}") ); + assert_eq!(known_http_route("/share/abcDEF123"), Some("/share/{token}")); assert_eq!( - known_http_route("/share/playlist/abcDEF123"), - Some("/share/playlist/{token}") - ); - assert_eq!( - known_http_route("/share/release/42"), - Some("/share/release/{id}") + known_http_route("/api/player/shares/abcDEF123/stream/42"), + Some("/api/player/shares/{token}/{action}/{track_id}") ); assert_eq!( known_http_route("/api/player/youtube/start"), diff --git a/src/oidc.rs b/src/oidc.rs index c98835e..e3c80f1 100644 --- a/src/oidc.rs +++ b/src/oidc.rs @@ -418,16 +418,6 @@ pub async fn oidc_callback_handler( config.oidc_user_groups, ); - if !is_allowed_by_groups(&groups, &config.oidc_user_groups, &config.oidc_admin_groups) { - tracing::warn!( - "OIDC login denied by group allowlist: sub={sub}, groups={groups:?}, user_groups={:?}, admin_groups={:?}", - config.oidc_user_groups, - config.oidc_admin_groups, - ); - crate::metrics::record_auth_attempt("oidc", "failure", "not_in_group"); - return redirect_login_with_error(i18n.t.login_access_denied); - } - // User provisioning logic. let user = match provision_user( &db, @@ -437,6 +427,7 @@ pub async fn oidc_callback_handler( name.as_deref(), &groups, &config.oidc_admin_groups, + &config.oidc_user_groups, ) .await { @@ -728,17 +719,6 @@ pub async fn oidc_mobile_callback_handler( .map(|n| n.to_string()); let groups = extract_groups_from_jwt(&id_token.to_string()); - if !is_allowed_by_groups(&groups, &config.oidc_user_groups, &config.oidc_admin_groups) { - tracing::warn!( - "Mobile OIDC login denied by group allowlist: sub={sub}, groups={groups:?}, user_groups={:?}, admin_groups={:?}", - config.oidc_user_groups, - config.oidc_admin_groups, - ); - crate::metrics::record_auth_attempt("mobile_oidc", "failure", "not_in_group"); - clear_mobile_oidc_session(&session).await?; - return Ok(mobile_redirect_error(&app_redirect_uri, "access_denied")); - } - let user = match provision_user( &db, &issuer, @@ -747,6 +727,7 @@ pub async fn oidc_mobile_callback_handler( name.as_deref(), &groups, &config.oidc_admin_groups, + &config.oidc_user_groups, ) .await { @@ -759,6 +740,11 @@ pub async fn oidc_mobile_callback_handler( } }; + if !user.is_active() { + clear_mobile_oidc_session(&session).await?; + return Ok(mobile_redirect_error(&app_redirect_uri, "approval_pending")); + } + let exchange_code = auth::create_mobile_exchange_code(&db, user.id_val()) .await .map_err(|e| cot::Error::internal(e.to_string()))?; @@ -773,48 +759,26 @@ pub async fn oidc_mobile_callback_handler( // User provisioning // --------------------------------------------------------------------------- -/// Resolve the role based on OIDC group membership. -/// If `admin_groups` is non-empty and any user group matches, return "admin"; -/// otherwise return "user". -fn resolve_role(groups: &[String], admin_groups: &str) -> &'static str { - if admin_groups.is_empty() { - return auth::Role::User.code(); +/// Group-derived access always takes precedence over local approval. +fn resolve_sso_role( + groups: &[String], + admin_groups: &str, + user_groups: &str, +) -> Option<&'static str> { + let matches = |configured: &str| { + configured + .split(',') + .map(str::trim) + .filter(|group| !group.is_empty()) + .any(|group| groups.iter().any(|g| g == group)) + }; + if matches(admin_groups) { + Some("admin") + } else if matches(user_groups) { + Some("user") + } else { + None } - let admin_set: std::collections::HashSet<&str> = admin_groups - .split(',') - .map(|s| s.trim()) - .filter(|s| !s.is_empty()) - .collect(); - if admin_set.is_empty() { - return auth::Role::User.code(); - } - for g in groups { - if admin_set.contains(g.as_str()) { - return auth::Role::Admin.code(); - } - } - auth::Role::User.code() -} - -fn parse_group_set(groups: &str) -> std::collections::HashSet<&str> { - groups - .split(',') - .map(str::trim) - .filter(|s| !s.is_empty()) - .collect() -} - -fn has_any_group(groups: &[String], allowed: &std::collections::HashSet<&str>) -> bool { - groups.iter().any(|g| allowed.contains(g.as_str())) -} - -fn is_allowed_by_groups(groups: &[String], user_groups: &str, admin_groups: &str) -> bool { - let user_set = parse_group_set(user_groups); - if user_set.is_empty() { - return true; - } - let admin_set = parse_group_set(admin_groups); - has_any_group(groups, &user_set) || has_any_group(groups, &admin_set) } async fn provision_user( @@ -825,8 +789,9 @@ async fn provision_user( name: Option<&str>, groups: &[String], admin_groups: &str, + user_groups: &str, ) -> Result { - let role = resolve_role(groups, admin_groups); + let role = resolve_sso_role(groups, admin_groups, user_groups); // 1. Check for existing OIDC link. if let Some(mut link) = OidcLink::find_by_issuer_sub(db, issuer, sub) @@ -841,8 +806,8 @@ async fn provision_user( .await .map_err(|e| format!("DB error updating OIDC link: {e}"))?; - // Always update role on login. - user.update_role(db, role) + // Refresh only the SSO grant; preserve independent local approval. + user.sync_sso_role(db, role) .await .map_err(|e| format!("DB error updating user role: {e}"))?; @@ -863,25 +828,6 @@ async fn provision_user( } } - // 2. No existing link — try to find a user by email. - if let Some(email_str) = email { - if let Some(mut user) = User::get_by_email(db, email_str) - .await - .map_err(|e| format!("DB error finding user by email: {e}"))? - { - // Create OIDC link for existing user. - OidcLink::create_link(db, user.id_val(), issuer, sub, email, name) - .await - .map_err(|e| format!("DB error creating OIDC link: {e}"))?; - - user.update_role(db, role) - .await - .map_err(|e| format!("DB error updating user role: {e}"))?; - - return Ok(user); - } - } - // 3. Create a brand-new user + OIDC link. // Generate a unique username from the sub or email. let username = if let Some(email_str) = email { @@ -1300,3 +1246,108 @@ mod tests { assert!(safe_mobile_redirect_uri(Some("http://127.0.0.1:notaport/x")).is_none()); } } + +#[cfg(test)] +mod approval_tests { + use super::*; + + #[test] + fn matching_groups_are_required_and_admin_wins() { + let groups = vec!["listeners".into(), "admins".into()]; + assert_eq!( + resolve_sso_role(&groups, " admins ", "listeners"), + Some("admin") + ); + assert_eq!( + resolve_sso_role(&groups, "other", "listeners"), + Some("user") + ); + assert_eq!(resolve_sso_role(&groups, "other", ""), None); + assert_eq!(resolve_sso_role(&[], "", ""), None); + } + + #[tokio::test] + #[ignore = "requires a migrated disposable database in FURU_ACCESS_TEST_DATABASE_URL"] + async fn postgres_approval_survives_sso_changes_without_implicit_grants() { + let db = Database::new(std::env::var("FURU_ACCESS_TEST_DATABASE_URL").unwrap()) + .await + .unwrap(); + let subject = format!("approval-test-{}", uuid::Uuid::new_v4()); + let provision = |groups: Vec| { + let db = &db; + let subject = &subject; + async move { + provision_user( + db, + "https://test.example", + subject, + None, + Some("Test pending user"), + &groups, + "admins", + "listeners", + ) + .await + .unwrap() + } + }; + let first = provision(vec![]).await; + assert!(!first.is_active()); + let mut again = provision(vec![]).await; + assert_eq!(again.id_val(), first.id_val()); + again.approve(&db, "admin", 1).await.unwrap(); + assert_eq!(provision(vec![]).await.role(), auth::Role::Admin); + assert_eq!( + provision(vec!["listeners".into()]).await.role(), + auth::Role::User + ); + assert_eq!( + provision(vec!["admins".into()]).await.role(), + auth::Role::Admin + ); + assert_eq!(provision(vec![]).await.role(), auth::Role::Admin); + + let auto_sub = format!("auto-{subject}"); + let automatic = provision_user( + &db, + "https://test.example", + &auto_sub, + None, + None, + &["listeners".into()], + "admins", + "listeners", + ) + .await + .unwrap(); + assert!(automatic.is_active()); + let removed = provision_user( + &db, + "https://test.example", + &auto_sub, + None, + None, + &[], + "admins", + "listeners", + ) + .await + .unwrap(); + assert!(!removed.is_active()); + assert_eq!(automatic.id_val(), removed.id_val()); + // A stale User held by an OIDC callback must retain a newer local grant. + let mut stale = removed.clone(); + let mut approving = removed.clone(); + approving.approve(&db, "admin", 1).await.unwrap(); + stale.sync_sso_role(&db, Some("user")).await.unwrap(); + stale.sync_sso_role(&db, None).await.unwrap(); + assert!(stale.is_active()); + assert_eq!(stale.role(), auth::Role::Admin); + let username = stale.username_str().to_owned(); + stale + .update_fields(&db, &username, None, Some("Renamed"), None, "") + .await + .unwrap(); + assert!(!stale.is_active()); + } +} diff --git a/src/player/dto.rs b/src/player/dto.rs index 15c9dc6..3c68d40 100644 --- a/src/player/dto.rs +++ b/src/player/dto.rs @@ -324,7 +324,7 @@ pub(super) struct ShareLinkResponse { } #[derive(Debug, Serialize, JsonSchema)] -pub(super) struct PlaylistShareDetail { +pub(super) struct ShareDetail { pub(super) token: String, pub(super) title: String, pub(super) tracks: Vec, diff --git a/src/player/mod.rs b/src/player/mod.rs index 5121b51..ac6e0bd 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -30,6 +30,7 @@ mod dto; mod helpers; mod queries; mod rows; +mod sharing; use dto::*; use helpers::{cover_variant_url, load_release_uploaders, track_cover_variant_url}; @@ -114,9 +115,6 @@ const PLAYER_DEVICE_COMMAND_TTL_MS: i64 = 20_000; const PLAYER_DEVICE_MAX_COMMANDS: usize = 32; const PLAYER_JAM_IDLE_TTL_MS: i64 = 4 * 60 * 60 * 1000; const PLAYER_JAM_MAX_INVITEES: usize = 25; -const PLAYER_RADIO_TRACK_LIMIT: usize = 40; -const PLAYER_RADIO_CANDIDATE_LIMIT: i64 = 220; -const PLAYER_RADIO_RELEASE_SEED_TRACKS: i64 = 4; const FED_DEVICE_PREFIX: &str = "fed:"; #[derive(Debug, Clone)] @@ -1641,6 +1639,8 @@ struct LastfmCallbackQuery { #[template(path = "player.html")] pub struct PlayerPageTemplate { pub t: &'static Translations, + pub guest: bool, + pub share_token: String, pub downloads_enabled: bool, pub torrent_downloads_enabled: bool, pub youtube_downloads_enabled: bool, @@ -1655,6 +1655,8 @@ mod page_template_tests { fn download_manager_button_follows_the_global_switch() { let disabled = PlayerPageTemplate { t: Translations::for_lang(Lang::En), + guest: false, + share_token: String::new(), downloads_enabled: false, torrent_downloads_enabled: false, youtube_downloads_enabled: false, @@ -1666,6 +1668,8 @@ mod page_template_tests { let enabled = PlayerPageTemplate { t: Translations::for_lang(Lang::En), + guest: false, + share_token: String::new(), downloads_enabled: true, torrent_downloads_enabled: true, youtube_downloads_enabled: true, @@ -4770,15 +4774,15 @@ async fn similarity_search_handler( } // --------------------------------------------------------------------------- -// POST /api/player/share-playlist +// POST /api/player/shares // --------------------------------------------------------------------------- -async fn create_playlist_share_handler( +async fn create_share_handler( auth_ctx: auth::AuthContext, session: Session, db: Database, pool: &sqlx::PgPool, - Json(body): Json, + Json(body): Json, ) -> cot::Result { let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else { return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated")); @@ -4818,7 +4822,7 @@ async fn create_playlist_share_handler( let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(); sqlx::query( - r#"INSERT INTO furumusic__playlist_share_link + r#"INSERT INTO furumusic__share_link (token, creator_user_id, title, track_ids_json, created_at) VALUES ($1, $2, $3, $4, $5)"#, ) @@ -4833,51 +4837,7 @@ async fn create_playlist_share_handler( Json(ShareLinkResponse { token: token.clone(), - url: format!("/share/playlist/{token}"), - }) - .into_response() -} - -// --------------------------------------------------------------------------- -// GET /api/player/share-playlist/{id} -// --------------------------------------------------------------------------- - -async fn playlist_share_detail_handler( - auth_ctx: auth::AuthContext, - session: Session, - db: Database, - pool: &sqlx::PgPool, - path: Path, -) -> cot::Result { - let Some(_user) = auth::get_request_user(&auth_ctx, &session, &db).await else { - return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated")); - }; - - let token = path.0.id.trim().to_string(); - let share: Option<(String, String)> = sqlx::query_as( - r#"SELECT title::text, track_ids_json::text - FROM furumusic__playlist_share_link - WHERE token = $1"#, - ) - .bind(&token) - .fetch_optional(pool) - .await - .map_err(|e| cot::Error::internal(e.to_string()))?; - - let Some((title, track_ids_json)) = share else { - return Ok(json_error( - StatusCode::NOT_FOUND, - "shared playlist not found", - )); - }; - - let ids: Vec = serde_json::from_str(&track_ids_json).unwrap_or_default(); - let tracks = load_track_items_by_ids(pool, &ids).await?; - - Json(PlaylistShareDetail { - token, - title, - tracks, + url: format!("/share/{token}"), }) .into_response() } @@ -4993,11 +4953,20 @@ async fn stream_handler( return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated")); }; - let track_id = path.0.track_id; + audio_response(pool, config, request, path.0.track_id, false).await +} +async fn audio_response( + pool: &sqlx::PgPool, + config: &AppConfig, + request: &cot::http::Request, + track_id: i64, + download: bool, +) -> cot::Result> { // Look up track → audio_file_id → MediaFile let media = sqlx::query_as::<_, MediaFileRow>( r#"SELECT mf.file_path, + mf.original_filename::text AS original_filename, mf.mime_type::text as mime_type, mf.file_size_bytes, mf.sha256_hash::text AS sha256_hash, @@ -5025,7 +4994,29 @@ async fn stream_handler( )); } - let file_size = media.file_size_bytes as u64; + let file_size = tokio::fs::metadata(&full_path) + .await + .map_err(|e| cot::Error::internal(e.to_string()))? + .len(); + let filename = media + .original_filename + .rsplit(['/', '\\']) + .next() + .filter(|name| !name.is_empty()) + .unwrap_or("track"); + let disposition = if download { + format!( + "attachment; filename=\"track-{}\"; filename*=UTF-8''{}", + track_id, + filename + .as_bytes() + .iter() + .map(|b| format!("%{b:02X}")) + .collect::() + ) + } else { + "inline".to_owned() + }; let etag = media_etag("audio", track_id, &media.sha256_hash, None); // Parse Range header @@ -5037,40 +5028,61 @@ async fn stream_handler( let (start, end) = range; let chunk_size = end - start + 1; - let data = read_file_range(&full_path, start, chunk_size).await?; + use futures_util::TryStreamExt; + use tokio::io::{AsyncReadExt, AsyncSeekExt}; + let mut file = tokio::fs::File::open(&full_path) + .await + .map_err(|e| cot::Error::internal(e.to_string()))?; + file.seek(std::io::SeekFrom::Start(start)) + .await + .map_err(|e| cot::Error::internal(e.to_string()))?; + let data = tokio_util::io::ReaderStream::new(file.take(chunk_size)) + .map_err(|e| cot::Error::internal(e.to_string())); crate::metrics::record_stream_request(true, chunk_size); let response = cot::http::Response::builder() .status(StatusCode::PARTIAL_CONTENT) .header(CONTENT_TYPE, media.mime_type.as_str()) .header(ACCEPT_RANGES, "bytes") + .header("Content-Disposition", disposition.as_str()) + .header("Cache-Control", "private, no-store") .header(CONTENT_RANGE, format!("bytes {start}-{end}/{file_size}")) .header(CONTENT_LENGTH, chunk_size.to_string()) .header("ETag", etag.as_str()) .header("X-Furumi-Content-Sha256", media.sha256_hash.as_str()) .header("X-Furumi-Content-Updated-At", media.created_at.as_str()) - .body(Body::fixed(data)) + .body(Body::streaming(data)) .expect("valid response"); return Ok(response); } + return Ok(cot::http::Response::builder() + .status(StatusCode::RANGE_NOT_SATISFIABLE) + .header(CONTENT_RANGE, format!("bytes */{file_size}")) + .body(Body::fixed("")) + .expect("valid response")); } - // No Range or invalid range: return full file - let data = tokio::fs::read(&full_path) + // No Range: stream the full file. + let file = tokio::fs::File::open(&full_path) .await .map_err(|e| cot::Error::internal(e.to_string()))?; + use futures_util::TryStreamExt; + let data = + tokio_util::io::ReaderStream::new(file).map_err(|e| cot::Error::internal(e.to_string())); crate::metrics::record_stream_request(false, file_size); let response = cot::http::Response::builder() .status(StatusCode::OK) .header(CONTENT_TYPE, media.mime_type.as_str()) .header(ACCEPT_RANGES, "bytes") + .header("Content-Disposition", disposition.as_str()) + .header("Cache-Control", "private, no-store") .header(CONTENT_LENGTH, file_size.to_string()) .header("ETag", etag.as_str()) .header("X-Furumi-Content-Sha256", media.sha256_hash.as_str()) .header("X-Furumi-Content-Updated-At", media.created_at.as_str()) - .body(Body::fixed(data)) + .body(Body::streaming(data)) .expect("valid response"); Ok(response) @@ -5167,7 +5179,10 @@ async fn local_upload_handler( { Some(id) => Some(id), None => { - return Ok(json_error(StatusCode::BAD_REQUEST, "invalid target playlist ID")); + return Ok(json_error( + StatusCode::BAD_REQUEST, + "invalid target playlist ID", + )); } }, }; @@ -5319,7 +5334,8 @@ async fn local_upload_handler( use sha2::{Digest, Sha256}; let sha256 = format!("{:x}", Sha256::digest(&bytes)); if let Err(error) = - crate::import_playlists::register(pool, user.id, playlist_id, &inbox_path, &sha256).await + crate::import_playlists::register(pool, user.id, playlist_id, &inbox_path, &sha256) + .await { return Ok(json_error(StatusCode::BAD_REQUEST, &error.to_string())); } @@ -5452,6 +5468,9 @@ fn hex_value(byte: u8) -> Option { } fn parse_range(header: &str, file_size: u64) -> Option<(u64, u64)> { + if file_size == 0 { + return None; + } let bytes_prefix = "bytes="; if !header.starts_with(bytes_prefix) { return None; @@ -5559,8 +5578,18 @@ async fn cover_response( return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated")); }; + cover_file_response(pool, config, media_file_id, variant_name).await +} + +async fn cover_file_response( + pool: &sqlx::PgPool, + config: &AppConfig, + media_file_id: i64, + variant_name: Option<&str>, +) -> cot::Result> { let media = sqlx::query_as::<_, MediaFileRow>( r#"SELECT file_path, + original_filename::text AS original_filename, mime_type::text as mime_type, file_size_bytes, sha256_hash::text AS sha256_hash, @@ -8085,474 +8114,6 @@ async fn toggle_follow_artist_handler( } } -// --------------------------------------------------------------------------- -// GET /api/player/radio/{kind}/{id} -// --------------------------------------------------------------------------- - -fn append_unique_track_ids(track_ids: &mut Vec, candidates: Vec, limit: usize) { - let mut seen: HashSet = track_ids.iter().copied().collect(); - for candidate in candidates { - if track_ids.len() >= limit { - break; - } - if seen.insert(candidate) { - track_ids.push(candidate); - } - } -} - -async fn track_primary_artist_ids(pool: &sqlx::PgPool, track_id: i64) -> cot::Result> { - sqlx::query_scalar::<_, i64>( - r#"SELECT artist_id - FROM furumusic__track_artist - WHERE track_id = $1 AND role <> 'featuring' - ORDER BY position, artist_id"#, - ) - .bind(track_id) - .fetch_all(pool) - .await - .map_err(|e| cot::Error::internal(e.to_string())) -} - -async fn release_primary_artist_ids(pool: &sqlx::PgPool, release_id: i64) -> cot::Result> { - sqlx::query_scalar::<_, i64>( - r#"SELECT artist_id - FROM furumusic__release_artist - WHERE release_id = $1 - ORDER BY position, artist_id"#, - ) - .bind(release_id) - .fetch_all(pool) - .await - .map_err(|e| cot::Error::internal(e.to_string())) -} - -async fn fallback_radio_track_ids( - pool: &sqlx::PgPool, - user_id: i64, - artist_ids: &[i64], - excluded_ids: &[i64], - limit: i64, -) -> cot::Result> { - if limit <= 0 { - return Ok(Vec::new()); - } - - sqlx::query_scalar::<_, i64>( - r#"SELECT t.id - FROM furumusic__track t - JOIN furumusic__release r ON r.id = t.release_id - WHERE t.is_hidden = false - AND r.is_hidden = false - AND NOT (t.id = ANY($3::bigint[])) - ORDER BY ( - CASE WHEN EXISTS ( - SELECT 1 FROM furumusic__user_liked_track ult - WHERE ult.user_id = $1 AND ult.track_id = t.id - ) THEN 9.0 ELSE 0.0 END - + CASE WHEN EXISTS ( - SELECT 1 FROM furumusic__track_artist ta - WHERE ta.track_id = t.id - AND ta.role <> 'featuring' - AND ta.artist_id = ANY($2::bigint[]) - ) THEN 5.0 ELSE 0.0 END - + COALESCE(t.lastfm_rating, 0.0) * 0.7 - + ln(COALESCE(t.lastfm_playcount, 0)::double precision + 1.0) * 0.04 - + ln(COALESCE(t.lastfm_listeners, 0)::double precision + 1.0) * 0.03 - + random() * 2.0 - ) DESC, t.id - LIMIT $4"#, - ) - .bind(user_id) - .bind(artist_ids) - .bind(excluded_ids) - .bind(limit) - .fetch_all(pool) - .await - .map_err(|e| cot::Error::internal(e.to_string())) -} - -async fn track_radio_candidate_ids( - pool: &sqlx::PgPool, - user_id: i64, - track_id: i64, - limit: i64, -) -> cot::Result> { - sqlx::query_scalar::<_, i64>( - r#"WITH seed_track AS ( - SELECT t.id, t.release_id - FROM furumusic__track t - JOIN furumusic__release r ON r.id = t.release_id - WHERE t.id = $1 AND t.is_hidden = false AND r.is_hidden = false - ), - seed_artists AS ( - SELECT ta.artist_id - FROM furumusic__track_artist ta - JOIN seed_track st ON st.id = ta.track_id - WHERE ta.role <> 'featuring' - ), - seed_tag_sources AS ( - SELECT egt.genre_id, - ln(greatest(COALESCE(egt.weight, 1.0), 1.0) + 1.0) AS weight - FROM furumusic__entity_genre_tag egt - JOIN seed_track st ON egt.entity_kind = 'track' AND egt.entity_id = st.id - UNION ALL - SELECT tg.genre_id, 1.0 AS weight - FROM furumusic__track_genre tg - JOIN seed_track st ON st.id = tg.track_id - UNION ALL - SELECT egt.genre_id, - ln(greatest(COALESCE(egt.weight, 1.0), 1.0) + 1.0) AS weight - FROM furumusic__entity_genre_tag egt - JOIN seed_track st ON egt.entity_kind = 'release' AND egt.entity_id = st.release_id - ), - seed_tags AS ( - SELECT genre_id, max(weight) AS seed_weight - FROM seed_tag_sources - GROUP BY genre_id - ), - candidate_tag_sources AS ( - SELECT egt.entity_id AS track_id, - egt.genre_id, - ln(greatest(COALESCE(egt.weight, 1.0), 1.0) + 1.0) AS weight - FROM furumusic__entity_genre_tag egt - WHERE egt.entity_kind = 'track' - UNION ALL - SELECT tg.track_id, tg.genre_id, 1.0 AS weight - FROM furumusic__track_genre tg - UNION ALL - SELECT t.id AS track_id, - egt.genre_id, - ln(greatest(COALESCE(egt.weight, 1.0), 1.0) + 1.0) AS weight - FROM furumusic__track t - JOIN furumusic__entity_genre_tag egt - ON egt.entity_kind = 'release' AND egt.entity_id = t.release_id - ), - candidate_tags AS ( - SELECT track_id, genre_id, max(weight) AS weight - FROM candidate_tag_sources - GROUP BY track_id, genre_id - ), - tag_scores AS ( - SELECT ct.track_id, sum(st.seed_weight * ct.weight) AS tag_score - FROM candidate_tags ct - JOIN seed_tags st ON st.genre_id = ct.genre_id - GROUP BY ct.track_id - ) - SELECT t.id - FROM furumusic__track t - JOIN furumusic__release r ON r.id = t.release_id - LEFT JOIN tag_scores score ON score.track_id = t.id - WHERE t.is_hidden = false - AND r.is_hidden = false - AND t.id <> $1 - AND ( - COALESCE(score.tag_score, 0.0) > 0.0 - OR EXISTS ( - SELECT 1 - FROM furumusic__track_artist ta - JOIN seed_artists sa ON sa.artist_id = ta.artist_id - WHERE ta.track_id = t.id AND ta.role <> 'featuring' - ) - OR EXISTS ( - SELECT 1 FROM furumusic__user_liked_track ult - WHERE ult.user_id = $2 AND ult.track_id = t.id - ) - ) - ORDER BY ( - COALESCE(score.tag_score, 0.0) * 12.0 - + CASE - WHEN EXISTS ( - SELECT 1 FROM furumusic__user_liked_track ult - WHERE ult.user_id = $2 AND ult.track_id = t.id - ) AND COALESCE(score.tag_score, 0.0) > 0.0 THEN 12.0 - WHEN EXISTS ( - SELECT 1 FROM furumusic__user_liked_track ult - WHERE ult.user_id = $2 AND ult.track_id = t.id - ) THEN 3.0 - ELSE 0.0 - END - + CASE WHEN EXISTS ( - SELECT 1 - FROM furumusic__track_artist ta - JOIN seed_artists sa ON sa.artist_id = ta.artist_id - WHERE ta.track_id = t.id AND ta.role <> 'featuring' - ) THEN 4.0 ELSE 0.0 END - + COALESCE(t.lastfm_rating, 0.0) * 0.65 - + ln(COALESCE(t.lastfm_playcount, 0)::double precision + 1.0) * 0.04 - + ln(COALESCE(t.lastfm_listeners, 0)::double precision + 1.0) * 0.03 - + random() * 1.6 - ) DESC, t.id - LIMIT $3"#, - ) - .bind(track_id) - .bind(user_id) - .bind(limit) - .fetch_all(pool) - .await - .map_err(|e| cot::Error::internal(e.to_string())) -} - -async fn release_radio_candidate_ids( - pool: &sqlx::PgPool, - user_id: i64, - release_id: i64, - excluded_ids: &[i64], - limit: i64, -) -> cot::Result> { - sqlx::query_scalar::<_, i64>( - r#"WITH seed_release AS ( - SELECT id - FROM furumusic__release - WHERE id = $1 AND is_hidden = false - ), - seed_artists AS ( - SELECT ra.artist_id - FROM furumusic__release_artist ra - JOIN seed_release sr ON sr.id = ra.release_id - ), - seed_tag_sources AS ( - SELECT egt.genre_id, - ln(greatest(COALESCE(egt.weight, 1.0), 1.0) + 1.0) AS weight - FROM furumusic__entity_genre_tag egt - JOIN seed_release sr ON egt.entity_kind = 'release' AND egt.entity_id = sr.id - UNION ALL - SELECT egt.genre_id, - ln(greatest(COALESCE(egt.weight, 1.0), 1.0) + 1.0) AS weight - FROM furumusic__track t - JOIN seed_release sr ON sr.id = t.release_id - JOIN furumusic__entity_genre_tag egt - ON egt.entity_kind = 'track' AND egt.entity_id = t.id - UNION ALL - SELECT tg.genre_id, 1.0 AS weight - FROM furumusic__track t - JOIN seed_release sr ON sr.id = t.release_id - JOIN furumusic__track_genre tg ON tg.track_id = t.id - ), - seed_tags AS ( - SELECT genre_id, max(weight) AS seed_weight - FROM seed_tag_sources - GROUP BY genre_id - ), - candidate_release_tag_sources AS ( - SELECT egt.entity_id AS release_id, - egt.genre_id, - ln(greatest(COALESCE(egt.weight, 1.0), 1.0) + 1.0) AS weight - FROM furumusic__entity_genre_tag egt - WHERE egt.entity_kind = 'release' - UNION ALL - SELECT t.release_id, - egt.genre_id, - ln(greatest(COALESCE(egt.weight, 1.0), 1.0) + 1.0) AS weight - FROM furumusic__track t - JOIN furumusic__entity_genre_tag egt - ON egt.entity_kind = 'track' AND egt.entity_id = t.id - UNION ALL - SELECT t.release_id, tg.genre_id, 1.0 AS weight - FROM furumusic__track t - JOIN furumusic__track_genre tg ON tg.track_id = t.id - ), - candidate_release_tags AS ( - SELECT release_id, genre_id, max(weight) AS weight - FROM candidate_release_tag_sources - GROUP BY release_id, genre_id - ), - release_scores AS ( - SELECT crt.release_id, sum(st.seed_weight * crt.weight) AS tag_score - FROM candidate_release_tags crt - JOIN seed_tags st ON st.genre_id = crt.genre_id - GROUP BY crt.release_id - ), - candidate_tracks AS ( - SELECT t.id, - t.release_id, - COALESCE(score.tag_score, 0.0) AS tag_score, - EXISTS ( - SELECT 1 FROM furumusic__user_liked_track ult - WHERE ult.user_id = $2 AND ult.track_id = t.id - ) AS liked, - EXISTS ( - SELECT 1 - FROM furumusic__release_artist ra - JOIN seed_artists sa ON sa.artist_id = ra.artist_id - WHERE ra.release_id = t.release_id - ) AS same_artist, - COALESCE(t.lastfm_rating, 0.0) AS rating, - COALESCE(t.lastfm_playcount, 0)::double precision AS playcount, - COALESCE(t.lastfm_listeners, 0)::double precision AS listeners - FROM furumusic__track t - JOIN furumusic__release r ON r.id = t.release_id - LEFT JOIN release_scores score ON score.release_id = t.release_id - WHERE t.is_hidden = false - AND r.is_hidden = false - AND t.release_id <> $1 - AND NOT (t.id = ANY($3::bigint[])) - AND ( - COALESCE(score.tag_score, 0.0) > 0.0 - OR EXISTS ( - SELECT 1 - FROM furumusic__release_artist ra - JOIN seed_artists sa ON sa.artist_id = ra.artist_id - WHERE ra.release_id = t.release_id - ) - OR EXISTS ( - SELECT 1 FROM furumusic__user_liked_track ult - WHERE ult.user_id = $2 AND ult.track_id = t.id - ) - ) - ), - ranked_tracks AS ( - SELECT *, - row_number() OVER ( - PARTITION BY release_id - ORDER BY rating DESC, playcount DESC, listeners DESC, random() DESC, id - ) AS release_rank - FROM candidate_tracks - ) - SELECT id - FROM ranked_tracks - WHERE release_rank <= 4 - ORDER BY ( - tag_score * 12.0 - + CASE - WHEN liked AND tag_score > 0.0 THEN 11.0 - WHEN liked THEN 3.0 - ELSE 0.0 - END - + CASE WHEN same_artist THEN 3.5 ELSE 0.0 END - + rating * 0.65 - + ln(playcount + 1.0) * 0.04 - + ln(listeners + 1.0) * 0.03 - + random() * 1.6 - ) DESC, id - LIMIT $4"#, - ) - .bind(release_id) - .bind(user_id) - .bind(excluded_ids) - .bind(limit) - .fetch_all(pool) - .await - .map_err(|e| cot::Error::internal(e.to_string())) -} - -async fn build_track_radio_ids( - pool: &sqlx::PgPool, - user_id: i64, - track_id: i64, -) -> cot::Result>> { - let seed_track = sqlx::query_scalar::<_, i64>( - r#"SELECT t.id - FROM furumusic__track t - JOIN furumusic__release r ON r.id = t.release_id - WHERE t.id = $1 AND t.is_hidden = false AND r.is_hidden = false"#, - ) - .bind(track_id) - .fetch_optional(pool) - .await - .map_err(|e| cot::Error::internal(e.to_string()))?; - - if seed_track.is_none() { - return Ok(None); - } - - let mut ids = vec![track_id]; - let candidate_ids = - track_radio_candidate_ids(pool, user_id, track_id, PLAYER_RADIO_CANDIDATE_LIMIT).await?; - append_unique_track_ids(&mut ids, candidate_ids, PLAYER_RADIO_TRACK_LIMIT); - - let artist_ids = track_primary_artist_ids(pool, track_id).await?; - let remaining = PLAYER_RADIO_TRACK_LIMIT.saturating_sub(ids.len()) as i64; - let fallback_ids = - fallback_radio_track_ids(pool, user_id, &artist_ids, &ids, remaining).await?; - append_unique_track_ids(&mut ids, fallback_ids, PLAYER_RADIO_TRACK_LIMIT); - - Ok(Some(ids)) -} - -async fn build_release_radio_ids( - pool: &sqlx::PgPool, - user_id: i64, - release_id: i64, -) -> cot::Result>> { - let seed_release = sqlx::query_scalar::<_, i64>( - r#"SELECT id FROM furumusic__release WHERE id = $1 AND is_hidden = false"#, - ) - .bind(release_id) - .fetch_optional(pool) - .await - .map_err(|e| cot::Error::internal(e.to_string()))?; - - if seed_release.is_none() { - return Ok(None); - } - - let mut ids = sqlx::query_scalar::<_, i64>( - r#"SELECT t.id - FROM furumusic__track t - JOIN furumusic__release r ON r.id = t.release_id - WHERE t.release_id = $1 - AND t.is_hidden = false - AND r.is_hidden = false - ORDER BY COALESCE(t.lastfm_rating, 0.0) DESC, - COALESCE(t.lastfm_playcount, 0) DESC, - COALESCE(t.lastfm_listeners, 0) DESC, - t.disc_number NULLS FIRST, - t.track_number NULLS LAST, - t.id - LIMIT $2"#, - ) - .bind(release_id) - .bind(PLAYER_RADIO_RELEASE_SEED_TRACKS) - .fetch_all(pool) - .await - .map_err(|e| cot::Error::internal(e.to_string()))?; - - let candidate_ids = release_radio_candidate_ids( - pool, - user_id, - release_id, - &ids, - PLAYER_RADIO_CANDIDATE_LIMIT, - ) - .await?; - append_unique_track_ids(&mut ids, candidate_ids, PLAYER_RADIO_TRACK_LIMIT); - - let artist_ids = release_primary_artist_ids(pool, release_id).await?; - let remaining = PLAYER_RADIO_TRACK_LIMIT.saturating_sub(ids.len()) as i64; - let fallback_ids = - fallback_radio_track_ids(pool, user_id, &artist_ids, &ids, remaining).await?; - append_unique_track_ids(&mut ids, fallback_ids, PLAYER_RADIO_TRACK_LIMIT); - - Ok(Some(ids)) -} - -async fn radio_handler( - auth_ctx: auth::AuthContext, - session: Session, - db: Database, - pool: &sqlx::PgPool, - path: Path, -) -> cot::Result { - let Some(user) = auth::get_request_user(&auth_ctx, &session, &db).await else { - return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated")); - }; - - let seed = path.0; - let ids = match seed.kind.as_str() { - "track" => build_track_radio_ids(pool, user.id, seed.id).await?, - "release" => build_release_radio_ids(pool, user.id, seed.id).await?, - _ => return Ok(json_error(StatusCode::BAD_REQUEST, "unknown radio seed")), - }; - - let Some(ids) = ids else { - return Ok(json_error(StatusCode::NOT_FOUND, "radio seed not found")); - }; - - let tracks = load_track_items_by_ids(pool, &ids).await?; - Json(tracks).into_response() -} - // --------------------------------------------------------------------------- // POST /api/player/tracks-by-ids // --------------------------------------------------------------------------- @@ -10017,35 +9578,6 @@ impl App for PlayerApp { }, "player_release_detail", ), - Route::with_handler_and_name( - "/radio/{kind}/{id}", - { - let pool = Arc::clone(&pool); - let pool_config = Arc::clone(&pool_config); - get( - move |auth_ctx: auth::AuthContext, - session: Session, - db: Database, - path: Path| { - let pool = Arc::clone(&pool); - let pool_config = Arc::clone(&pool_config); - async move { - let pg_pool = pool - .get_or_init(|| async { - sqlx::postgres::PgPoolOptions::new() - .max_connections(5) - .connect(&pool_config.database_url) - .await - .expect("player pool") - }) - .await; - radio_handler(auth_ctx, session, db, pg_pool, path).await - } - }, - ) - }, - "player_radio", - ), // -- Playlists (list + create) -- Route::with_handler_and_name( "/playlists", @@ -10096,14 +9628,14 @@ impl App for PlayerApp { ), // -- Shared playlist snapshots -- Route::with_handler_and_name( - "/share-playlist", + "/shares", post({ let pool = Arc::clone(&pool); let pool_config = Arc::clone(&pool_config); move |auth_ctx: auth::AuthContext, session: Session, db: Database, - json: Json| { + json: Json| { let pool = Arc::clone(&pool); let pool_config = Arc::clone(&pool_config); async move { @@ -10116,15 +9648,15 @@ impl App for PlayerApp { .expect("player pool") }) .await; - create_playlist_share_handler(auth_ctx, session, db, pg_pool, json) + create_share_handler(auth_ctx, session, db, pg_pool, json) .await } } }), - "player_share_playlist", + "player_create_share", ), Route::with_handler_and_name( - "/share-playlist/{id}", + "/shares/{id}", get({ let pool = Arc::clone(&pool); let pool_config = Arc::clone(&pool_config); @@ -10144,12 +9676,12 @@ impl App for PlayerApp { .expect("player pool") }) .await; - playlist_share_detail_handler(auth_ctx, session, db, pg_pool, path) + sharing::detail_handler(auth_ctx, session, db, pg_pool, path) .await } } }), - "player_share_playlist_detail", + "player_share_detail", ), // -- Playlist detail (get, update, delete) -- Route::with_handler_and_name( @@ -10447,6 +9979,42 @@ impl App for PlayerApp { }), "player_follow_toggle", ), + Route::with_handler_and_name( + "/shares/{token}/{action}/{track_id}", get({ + let pool = Arc::clone(&pool); + let pool_config = Arc::clone(&pool_config); + move |db: Database, path: Path, request: cot::request::Request| { + let pool = Arc::clone(&pool); + let pool_config = Arc::clone(&pool_config); + async move { + let pg_pool = pool.get_or_init(|| async { + sqlx::postgres::PgPoolOptions::new().max_connections(5) + .connect(&pool_config.database_url).await.expect("player pool") + }).await; + let (live_config, _) = AppConfig::load_with_db(&db).await; + sharing::media_handler(pg_pool, &live_config, &request, path).await + } + } + }), "player_shared_media", + ), + Route::with_handler_and_name( + "/download/{track_id}", get({ + let pool = Arc::clone(&pool); + let pool_config = Arc::clone(&pool_config); + move |db: Database, auth_ctx: auth::AuthContext, session: Session, path: Path, request: cot::request::Request| { + let pool = Arc::clone(&pool); + let pool_config = Arc::clone(&pool_config); + async move { + let pg_pool = pool.get_or_init(|| async { + sqlx::postgres::PgPoolOptions::new().max_connections(5) + .connect(&pool_config.database_url).await.expect("player pool") + }).await; + let (live_config, _) = AppConfig::load_with_db(&db).await; + sharing::download_handler(auth_ctx, session, db, pg_pool, &live_config, &request, path).await + } + } + }), "player_download", + ), // -- Audio stream -- Route::with_handler_and_name( "/stream/{track_id}", diff --git a/src/player/queries.rs b/src/player/queries.rs index a80edf2..7214774 100644 --- a/src/player/queries.rs +++ b/src/player/queries.rs @@ -54,7 +54,7 @@ pub(super) struct ReorderPlaylistRequest { } #[derive(Debug, Deserialize)] -pub(super) struct CreatePlaylistShareRequest { +pub(super) struct CreateShareRequest { pub(super) track_ids: Vec, pub(super) title: Option, } @@ -76,12 +76,6 @@ pub(super) struct PathStringId { pub(super) id: String, } -#[derive(Debug, Deserialize)] -pub(super) struct PathRadioSeed { - pub(super) kind: String, - pub(super) id: i64, -} - #[derive(Debug, Deserialize)] pub(super) struct SearchQuery { pub(super) q: String, diff --git a/src/player/rows.rs b/src/player/rows.rs index ad453ba..b016a4a 100644 --- a/src/player/rows.rs +++ b/src/player/rows.rs @@ -54,8 +54,8 @@ pub(super) struct ReleaseArtistRefRow { #[derive(sqlx::FromRow)] pub(super) struct MediaFileRow { pub(super) file_path: String, + pub(super) original_filename: String, pub(super) mime_type: String, - pub(super) file_size_bytes: i64, pub(super) sha256_hash: String, pub(super) created_at: String, } diff --git a/src/player/sharing.rs b/src/player/sharing.rs new file mode 100644 index 0000000..f393c2c --- /dev/null +++ b/src/player/sharing.rs @@ -0,0 +1,125 @@ +//! Public capabilities grant access only to a stored snapshot's visible tracks. +use super::*; + +#[derive(Deserialize)] +pub(super) struct MediaPath { + token: String, + action: String, + track_id: i64, +} + +async fn load_share(pool: &sqlx::PgPool, token: &str) -> cot::Result> { + if !crate::is_share_token(token) { + return Ok(None); + } + let row: Option<(String, String)> = + sqlx::query_as("SELECT title, track_ids_json FROM furumusic__share_link WHERE token = $1") + .bind(token) + .fetch_optional(pool) + .await + .map_err(|e| cot::Error::internal(e.to_string()))?; + let Some((title, json)) = row else { + return Ok(None); + }; + let ids: Vec = + serde_json::from_str(&json).map_err(|e| cot::Error::internal(e.to_string()))?; + let tracks = load_track_items_by_ids(pool, &ids).await?; + Ok(Some(ShareDetail { + token: token.to_owned(), + title, + tracks, + })) +} + +pub(super) async fn detail_handler( + auth_ctx: auth::AuthContext, + session: Session, + db: Database, + pool: &sqlx::PgPool, + path: Path, +) -> cot::Result { + let Some(mut share) = load_share(pool, &path.0.id).await? else { + return Ok(json_error(StatusCode::NOT_FOUND, "shared music not found")); + }; + if auth::get_request_user(&auth_ctx, &session, &db) + .await + .is_none() + { + for track in &mut share.tracks { + track.stream_url = format!("/api/player/shares/{}/stream/{}", share.token, track.id); + if track.cover_url.is_some() { + track.cover_url = Some(format!( + "/api/player/shares/{}/cover/{}", + share.token, track.id + )); + } + } + } + let mut response = Json(share).into_response()?; + response + .headers_mut() + .insert("Cache-Control", "private, no-store".parse().unwrap()); + Ok(response) +} + +pub(super) async fn media_handler( + pool: &sqlx::PgPool, + config: &AppConfig, + request: &cot::http::Request, + path: Path, +) -> cot::Result { + let p = path.0; + if !crate::is_share_token(&p.token) { + return Ok(json_error(StatusCode::NOT_FOUND, "shared music not found")); + } + // Media range requests need only a membership check, not the metadata and + // artist lists of every track in a potentially large shared queue. + let allowed: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM furumusic__share_link s + JOIN furumusic__track t ON t.id = $2 + JOIN furumusic__release r ON r.id = t.release_id + WHERE s.token = $1 AND s.track_ids_json::jsonb @> jsonb_build_array($2::bigint) + AND t.is_hidden = false AND r.is_hidden = false)", + ) + .bind(&p.token) + .bind(p.track_id) + .fetch_one(pool) + .await + .map_err(|e| cot::Error::internal(e.to_string()))?; + if !allowed { + return Ok(json_error(StatusCode::NOT_FOUND, "shared track not found")); + } + match p.action.as_str() { + "stream" | "download" => { + audio_response(pool, config, request, p.track_id, p.action == "download").await + } + "cover" => { + let cover: Option = sqlx::query_scalar( + "SELECT COALESCE(t.cover_file_id, r.cover_file_id) FROM furumusic__track t JOIN furumusic__release r ON r.id = t.release_id WHERE t.id = $1") + .bind(p.track_id).fetch_one(pool).await.map_err(|e| cot::Error::internal(e.to_string()))?; + match cover { + Some(id) => cover_file_response(pool, config, id, Some("card")).await, + None => Ok(json_error(StatusCode::NOT_FOUND, "cover not found")), + } + } + _ => Ok(json_error(StatusCode::NOT_FOUND, "not found")), + } +} + +pub(super) async fn download_handler( + auth_ctx: auth::AuthContext, + session: Session, + db: Database, + pool: &sqlx::PgPool, + config: &AppConfig, + request: &cot::http::Request, + path: Path, +) -> cot::Result { + if auth::get_request_user(&auth_ctx, &session, &db) + .await + .is_none() + { + return Ok(json_error(StatusCode::UNAUTHORIZED, "not authenticated")); + } + audio_response(pool, config, request, path.0.track_id, true).await +} diff --git a/src/user.rs b/src/user.rs index f528d9c..e222887 100644 --- a/src/user.rs +++ b/src/user.rs @@ -19,6 +19,10 @@ pub struct User { avatar_url: Option, role: LimitedString<32>, is_active: bool, + local_role: Option, + sso_role: Option, + approved_by: Option, + approved_at: Option, } // --------------------------------------------------------------------------- @@ -50,6 +54,10 @@ impl User { avatar_url: None, role: LimitedString::new(role).unwrap(), is_active: true, + local_role: Some(role.to_owned()), + sso_role: None, + approved_by: None, + approved_at: None, }; user.insert(db).await?; Ok(user) @@ -72,8 +80,13 @@ impl User { if let Some(pw) = new_password { self.password = Some(PasswordHash::from_password(&Password::new(pw)).into_string()); } - self.role = LimitedString::new(role).unwrap(); - self.save(db).await + let local_role = (!role.is_empty()).then(|| role.to_owned()); + db.raw_with("UPDATE furumusic__user SET username = $1, email = $2, display_name = $3, password = $4, local_role = $5, role = COALESCE(sso_role, $5, 'user'), is_active = (sso_role IS NOT NULL OR $5 IS NOT NULL) WHERE id = $6", + &[&username.to_owned(), &self.email, &self.display_name, &self.password, &local_role, &self.id_val()]).await?; + if let Some(updated) = Self::get_by_id(db, self.id_val()).await? { + *self = updated; + } + Ok(()) } /// Look up a user by username. @@ -126,13 +139,17 @@ impl User { self.is_active } + pub fn has_sso_admin_role(&self) -> bool { + self.sso_role.as_deref() == Some("admin") + } + /// Create a user without a password (for OIDC-only accounts). pub async fn create_oidc( db: &Database, username: &str, email: Option<&str>, display_name: Option<&str>, - role: &str, + sso_role: Option<&str>, ) -> cot::db::Result { let mut user = Self { id: Auto::auto(), @@ -141,24 +158,44 @@ impl User { email: email.map(str::to_owned), display_name: display_name.map(str::to_owned), avatar_url: None, - role: LimitedString::new(role).unwrap(), - is_active: true, + role: LimitedString::new(sso_role.unwrap_or("user")).unwrap(), + is_active: sso_role.is_some(), + local_role: None, + sso_role: sso_role.map(str::to_owned), + approved_by: None, + approved_at: None, }; user.insert(db).await?; Ok(user) } - /// Update the user's role and persist the change. - pub async fn update_role(&mut self, db: &Database, role: &str) -> cot::db::Result<()> { - self.role = LimitedString::new(role).unwrap(); - self.save(db).await + pub async fn sync_sso_role( + &mut self, + db: &Database, + role: Option<&str>, + ) -> cot::db::Result<()> { + let role = role.map(str::to_owned); + // Change just this grant atomically: a concurrent administrator approval + // must not be overwritten by a stale User loaded before the OIDC callback. + db.raw_with("UPDATE furumusic__user SET sso_role = $1, role = COALESCE($1, local_role, 'user'), is_active = ($1 IS NOT NULL OR local_role IS NOT NULL) WHERE id = $2", &[&role, &self.id_val()]).await?; + if let Some(updated) = Self::get_by_id(db, self.id_val()).await? { + *self = updated; + } + Ok(()) } - /// Find a user by email address. - pub async fn get_by_email(db: &Database, email: &str) -> cot::db::Result> { - cot::db::query!(User, $email == Some(email.to_owned())) - .get(db) - .await + pub async fn approve( + &mut self, + db: &Database, + role: &str, + admin_id: i64, + ) -> cot::db::Result<()> { + db.raw_with("UPDATE furumusic__user SET local_role = $1, role = COALESCE(sso_role, $1), is_active = true, approved_by = $2, approved_at = $3 WHERE id = $4", + &[&role.to_owned(), &admin_id, &chrono::Utc::now().to_rfc3339(), &self.id_val()]).await?; + if let Some(updated) = Self::get_by_id(db, self.id_val()).await? { + *self = updated; + } + Ok(()) } } @@ -393,9 +430,38 @@ pub mod db_migrations { &[Operation::custom(create_oidc_link_indexes).build()]; } + #[cot::db::migrations::migration_op] + async fn add_local_approval(ctx: migrations::MigrationContext<'_>) -> cot::db::Result<()> { + ctx.db.raw("ALTER TABLE furumusic__user ADD COLUMN local_role text, ADD COLUMN sso_role text, ADD COLUMN approved_by bigint, ADD COLUMN approved_at text").await?; + // Existing password accounts retain local access. OIDC-only accounts retain + // their last SSO role until the next verified login refreshes group membership. + ctx.db.raw("UPDATE furumusic__user SET local_role = CASE WHEN password IS NOT NULL AND is_active THEN role ELSE NULL END, sso_role = CASE WHEN password IS NULL AND is_active THEN role ELSE NULL END").await?; + ctx.db + .raw("DROP TABLE furumusic__playlist_share_link") + .await?; + ctx.db.raw("CREATE TABLE furumusic__share_link (token text PRIMARY KEY, creator_user_id bigint NOT NULL, title text NOT NULL, track_ids_json text NOT NULL, created_at text NOT NULL)").await?; + Ok(()) + } + + #[derive(Debug, Copy, Clone)] + pub struct M0053LocalApprovalAndPublicShares; + impl migrations::Migration for M0053LocalApprovalAndPublicShares { + const APP_NAME: &'static str = "furumusic"; + const MIGRATION_NAME: &'static str = "m_0053_local_approval_and_public_shares"; + const DEPENDENCIES: &'static [migrations::MigrationDependency] = &[ + migrations::MigrationDependency::migration("furumusic", "m_0005_oidc_link_indexes"), + migrations::MigrationDependency::migration( + "furumusic", + "m_0037_create_playlist_share_links", + ), + ]; + const OPERATIONS: &'static [Operation] = &[Operation::custom(add_local_approval).build()]; + } + pub const MIGRATIONS: &[&SyncDynMigration] = &[ &M0003CreateUser, &M0004CreateOidcLink, &M0005OidcLinkIndexes, + &M0053LocalApprovalAndPublicShares, ]; } diff --git a/templates/admin/v2.html b/templates/admin/v2.html index 62e36a4..5021e14 100644 --- a/templates/admin/v2.html +++ b/templates/admin/v2.html @@ -2667,7 +2667,12 @@ tbody tr:hover { - + +
+ + +
+
@@ -3378,7 +3383,7 @@ tbody tr:hover { @@ -3412,7 +3417,7 @@ tbody tr:hover {
Account - +
Last.fm @@ -4137,7 +4142,7 @@ function adminV2() { scheduleDraft: '', editUser(user = null) { this.userModalOpen = false; - this.userDraft = {id:user?.id || null, username:user?.username || '', email:user?.email || '', display_name:user?.display_name || '', password:'', role:user?.role || 'user'}; + this.userDraft = {id:user?.id || null, username:user?.username || '', email:user?.email || '', display_name:user?.display_name || '', password:'', role:user ? (user.local_role || '') : 'user'}; this.userEditorOpen = true; }, async saveUser() { @@ -4824,6 +4829,13 @@ function adminV2() { } }, + async approveUser(user, role) { + try { + await this.request(`${this.apiBase}/users/manage`, {method:'POST', body:JSON.stringify({action:'approve', id:user.id, role})}); + await this.loadUsers(false); + } catch (error) { this.showToast(error.message); } + }, + async loadUsers(resetOffset = true) { if (this.activeView !== 'users' && resetOffset) return; if (resetOffset) this.users.offset = 0; diff --git a/templates/pending.html b/templates/pending.html new file mode 100644 index 0000000..de5de67 --- /dev/null +++ b/templates/pending.html @@ -0,0 +1,23 @@ +{% extends "base.html" %} +{% block title %}{{ t.approval_heading }} | {{ t.site_name }}{% endblock title %} +{% block head_extra %} + +{% endblock head_extra %} +{% block body %} +

{{ t.approval_heading }}

{{ t.approval_message }}

{{ t.player_log_out }}
+ +{% endblock body %} diff --git a/templates/player/scripts.html b/templates/player/scripts.html index 501821e..c754b49 100644 --- a/templates/player/scripts.html +++ b/templates/player/scripts.html @@ -1,9 +1,11 @@