diff --git a/migrations/0003_admin.sql b/migrations/0003_admin.sql new file mode 100644 index 0000000..24e96ed --- /dev/null +++ b/migrations/0003_admin.sql @@ -0,0 +1,4 @@ +ALTER TABLE users ADD COLUMN is_admin INTEGER NOT NULL DEFAULT 0; + +-- The first account to register administers the others. +UPDATE users SET is_admin = 1 WHERE id = (SELECT MIN(id) FROM users); diff --git a/src/api.rs b/src/api.rs index 25c89d7..f775fb4 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1,7 +1,7 @@ use leptos::prelude::*; use leptos::server_fn::codec::Json; -use crate::model::{Item, ItemInput, ListColor, Member, ShoppingList, Suggestion, User}; +use crate::model::{Account, Item, ItemInput, ListColor, Member, ShoppingList, Suggestion, User}; pub const NOT_LOGGED_IN: &str = "Session expirée, reconnecte-toi."; @@ -29,6 +29,20 @@ mod server { .ok_or_else(|| ServerFnError::new(super::NOT_LOGGED_IN)) } + pub async fn require_admin(pool: &SqlitePool) -> Result { + let user = require_user(pool).await?; + if !user.is_admin { + return Err(ServerFnError::new("Réservé aux administrateurs.")); + } + Ok(user) + } + + /// Sign-ups follow `REGISTRATION_ENABLED`, but stay open until the first + /// account (the admin) exists. + pub async fn registration_open(pool: &SqlitePool) -> Result { + Ok(crate::auth::registration_enabled() || !crate::db::has_users(pool).await.map_err(db_err)?) + } + fn not_found() -> ServerFnError { ServerFnError::new("Liste introuvable.") } @@ -96,6 +110,29 @@ mod server { Ok(email) } + pub fn check_password(password: &str) -> Result<(), ServerFnError> { + if !(8..=128).contains(&password.chars().count()) { + return Err(ServerFnError::new("Le mot de passe doit faire au moins 8 caractères.")); + } + Ok(()) + } + + pub async fn hash(password: String) -> Result { + blocking(move || crate::auth::hash_password(&password)) + .await? + .map_err(|_| ServerFnError::new("Erreur interne")) + } + + /// Maps a duplicate email to a readable error. + pub fn email_err(err: sqlx::Error) -> ServerFnError { + match err { + sqlx::Error::Database(err) if err.is_unique_violation() => { + ServerFnError::new("Un compte existe déjà avec cet email.") + } + err => db_err(err), + } + } + pub async fn blocking(f: impl FnOnce() -> T + Send + 'static) -> Result { tokio::task::spawn_blocking(f) .await @@ -113,32 +150,23 @@ pub async fn get_me() -> Result, ServerFnError> { #[server] pub async fn registration_enabled() -> Result { - Ok(crate::auth::registration_enabled()) + use server::*; + registration_open(&pool()?).await } #[server] pub async fn register(name: String, email: String, password: String) -> Result<(), ServerFnError> { use server::*; - if !crate::auth::registration_enabled() { + let pool = pool()?; + if !registration_open(&pool).await? { return Err(ServerFnError::new("Les inscriptions sont fermées.")); } - let pool = pool()?; let name = clean_name(&name, 40)?; let email = clean_email(&email)?; - if !(8..=128).contains(&password.chars().count()) { - return Err(ServerFnError::new("Le mot de passe doit faire au moins 8 caractères.")); - } + check_password(&password)?; - let hash = blocking(move || crate::auth::hash_password(&password)) - .await? - .map_err(|_| ServerFnError::new("Erreur interne"))?; - let user_id = match crate::db::register(&pool, &email, &name, &hash).await { - Ok(id) => id, - Err(sqlx::Error::Database(err)) if err.is_unique_violation() => { - return Err(ServerFnError::new("Un compte existe déjà avec cet email.")); - } - Err(err) => return Err(db_err(err)), - }; + let hash = hash(password).await?; + let user_id = crate::db::register(&pool, &email, &name, &hash).await.map_err(email_err)?; crate::auth::start_session(&pool, user_id).await.map_err(db_err)?; leptos_axum::redirect("/"); Ok(()) @@ -170,6 +198,89 @@ pub async fn logout() -> Result<(), ServerFnError> { Ok(()) } +// --- Administration --------------------------------------------------------- + +#[server] +pub async fn get_accounts() -> Result, ServerFnError> { + use server::*; + let pool = pool()?; + require_admin(&pool).await?; + crate::db::accounts(&pool).await.map_err(db_err) +} + +/// Creates an account even when sign-ups are closed. +#[server] +pub async fn create_account(name: String, email: String, password: String, is_admin: bool) -> Result<(), ServerFnError> { + use server::*; + let pool = pool()?; + require_admin(&pool).await?; + let name = clean_name(&name, 40)?; + let email = clean_email(&email)?; + check_password(&password)?; + + let hash = hash(password).await?; + let id = crate::db::register(&pool, &email, &name, &hash).await.map_err(email_err)?; + if is_admin { + crate::db::update_user(&pool, id, &name, &email, true).await.map_err(db_err)?; + } + Ok(()) +} + +/// An empty `password` keeps the current one. +#[server] +pub async fn update_account( + id: i64, + name: String, + email: String, + password: String, + is_admin: bool, +) -> Result<(), ServerFnError> { + use server::*; + let pool = pool()?; + let admin = require_admin(&pool).await?; + if id == admin.id && !is_admin { + return Err(ServerFnError::new("Tu ne peux pas retirer tes propres droits d'administration.")); + } + let name = clean_name(&name, 40)?; + let email = clean_email(&email)?; + if !password.is_empty() { + check_password(&password)?; + } + + crate::db::update_user(&pool, id, &name, &email, is_admin).await.map_err(email_err)?; + if !password.is_empty() { + let hash = hash(password).await?; + crate::db::set_password(&pool, id, &hash).await.map_err(db_err)?; + if id == admin.id { + // set_password signed every session out, this one included. + crate::auth::start_session(&pool, id).await.map_err(db_err)?; + } + } + Ok(()) +} + +/// Deletes the account and the lists it owns. +#[server] +pub async fn delete_account(id: i64) -> Result<(), ServerFnError> { + use server::*; + let pool = pool()?; + let admin = require_admin(&pool).await?; + if id == admin.id { + return Err(ServerFnError::new("Tu ne peux pas supprimer ton propre compte.")); + } + + // Members of the lists it owns or shares see them change. + let mut users = Vec::new(); + for list in crate::db::lists(&pool, id).await.map_err(db_err)? { + users.extend(audience(&pool, list.id).await?); + } + crate::db::delete_user(&pool, id).await.map_err(db_err)?; + users.sort_unstable(); + users.dedup(); + notify(users); + Ok(()) +} + // --- Lists ------------------------------------------------------------------ #[server] diff --git a/src/app/account.rs b/src/app/account.rs index 46a02e2..810e860 100644 --- a/src/app/account.rs +++ b/src/app/account.rs @@ -97,7 +97,7 @@ fn AuthLayout(title: &'static str, children: Children) -> impl IntoView { } #[component] -fn FormError(#[prop(into)] error: Signal>) -> impl IntoView { +pub fn FormError(#[prop(into)] error: Signal>) -> impl IntoView { move || { error.get().map(|msg| { view! { @@ -207,7 +207,7 @@ pub fn RegisterPage() -> impl IntoView { } #[component] -fn Field(label: &'static str, children: Children) -> impl IntoView { +pub fn Field(label: &'static str, children: Children) -> impl IntoView { view! {