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
}>
+ {move || Suspend::new(async move {
+ match accounts.await {
+ Ok(accounts) => view! { }.into_any(),
+ Err(err) => {
+ view! { {error_message(err)}
}.into_any()
+ }
+ }
+ })}
+
+
+
+
+
+
+ {move || {
+ editor
+ .get()
+ .map(|current| {
+ view! {
+
+ }
+ })
+ }}
+ }
+ .into_any()
+}
+
+#[component]
+fn AdminLayout(children: Children) -> impl IntoView {
+ view! {
+
+
+ {children()}
+
+ }
+}
+
+#[component]
+fn AccountRows(
+ accounts: Vec,
+ me_id: i64,
+ editor: RwSignal>,
+) -> impl IntoView {
+ view! {
+
+ {match accounts.len() {
+ 1 => "1 compte.".to_owned(),
+ n => format!("{n} comptes."),
+ }}
+
+
+ {accounts
+ .into_iter()
+ .map(|Account { user, created_at }| {
+ let is_me = user.id == me_id;
+ let edited = user.clone();
+ view! {
+ -
+
+
+ }
+ })
+ .collect_view()}
+
+ }
+}
+
+#[component]
+fn AccountForm(
+ editor: AccountEditor,
+ me_id: i64,
+ on_close: impl Fn() + Copy + Send + Sync + 'static,
+ on_saved: impl Fn() + Copy + Send + Sync + 'static,
+) -> impl IntoView {
+ let auth = expect_context::();
+ let existing = match editor {
+ AccountEditor::Edit(user) => Some(user),
+ AccountEditor::New => None,
+ };
+ let user_id = existing.as_ref().map(|u| u.id);
+ let is_me = user_id == Some(me_id);
+ let name = RwSignal::new(
+ existing
+ .as_ref()
+ .map(|u| u.name.clone())
+ .unwrap_or_default(),
+ );
+ let email = RwSignal::new(
+ existing
+ .as_ref()
+ .map(|u| u.email.clone())
+ .unwrap_or_default(),
+ );
+ let password = RwSignal::new(String::new());
+ let is_admin = RwSignal::new(existing.as_ref().is_some_and(|u| u.is_admin));
+ let error = RwSignal::new(None::);
+ let pending = RwSignal::new(false);
+
+ let run = move |call: std::pin::Pin>>>| {
+ pending.set(true);
+ spawn_local(async move {
+ let result = call.await;
+ pending.set(false);
+ match result {
+ Ok(()) => {
+ if is_me {
+ // Name shown on the avatar.
+ auth.me.refetch();
+ }
+ on_saved();
+ on_close();
+ }
+ Err(err) => error.set(Some(error_message(err))),
+ }
+ });
+ };
+
+ let submit = move |ev: ev::SubmitEvent| {
+ ev.prevent_default();
+ let (name, email, password, is_admin) =
+ (name.get(), email.get(), password.get(), is_admin.get());
+ run(match user_id {
+ Some(id) => Box::pin(update_account(id, name, email, password, is_admin)),
+ None => Box::pin(create_account(name, email, password, is_admin)),
+ });
+ };
+ let delete = move |_| {
+ let Some(id) = user_id else { return };
+ let confirmed = window()
+ .confirm_with_message("Supprimer ce compte et toutes les listes qu'il possède ?")
+ .unwrap_or(false);
+ if confirmed {
+ run(Box::pin(delete_account(id)));
+ }
+ };
+
+ let title = if user_id.is_some() {
+ "Modifier le compte"
+ } else {
+ "Nouveau compte"
+ };
+ let password_label = if user_id.is_some() {
+ "Nouveau mot de passe (facultatif)"
+ } else {
+ "Mot de passe (8 caractères min.)"
+ };
+
+ view! {
+
+
+
+ }
+}
+
+/// "2026-10-07" → "07/10/2026".
+fn french_date(iso: &str) -> String {
+ match iso.split('-').collect::>().as_slice() {
+ [y, m, d] => format!("{d}/{m}/{y}"),
+ _ => iso.to_owned(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::french_date;
+
+ #[test]
+ fn formats_french_date() {
+ assert_eq!(french_date("2026-10-07"), "07/10/2026");
+ assert_eq!(french_date("garbage"), "garbage");
+ }
+}
diff --git a/src/app/mod.rs b/src/app/mod.rs
index 0910dc5..4051932 100644
--- a/src/app/mod.rs
+++ b/src/app/mod.rs
@@ -1,4 +1,5 @@
mod account;
+mod admin;
mod icons;
mod live;
mod sheets;
@@ -17,6 +18,7 @@ use leptos_router::path;
use crate::api::{get_items, get_lists, get_suggestions};
use crate::model::{Item, ShoppingList, Suggestion, User};
use account::{AccountSheet, Auth, LoginPage, RegisterPage, RequireUser};
+use admin::AdminPage;
use sheets::{ItemEditor, ItemSheet, ListEditor, ListSheet};
use tiles::{BasketTile, ItemTile, SuggestionTile};
@@ -72,6 +74,7 @@ pub fn App() -> impl IntoView {
+
}
diff --git a/src/db.rs b/src/db.rs
index 3ffe5c8..40d275e 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -3,7 +3,7 @@ use sqlx::{Row, SqliteConnection};
use std::str::FromStr;
use crate::model::{
- Category, Icon, Item, ItemInput, ListColor, Member, Quantity, ShoppingList, Suggestion, Unit, User,
+ Account, Category, Icon, Item, ItemInput, ListColor, Member, Quantity, ShoppingList, Suggestion, Unit, User,
};
pub async fn connect(url: &str) -> Result {
@@ -61,6 +61,7 @@ fn user_from_row(row: &SqliteRow) -> Result {
id: row.try_get("id")?,
name: row.try_get("name")?,
email: row.try_get("email")?,
+ is_admin: row.try_get("is_admin")?,
})
}
@@ -76,17 +77,20 @@ const STARTER_CATALOG: &[(&str, Icon, Category)] = &[
("Café en grains", Icon::Coffee, Category::Epicerie),
];
-/// Creates the account with a first list and starter suggestions.
-/// Fails with a unique violation if the email is taken.
+/// Creates the account with a first list and starter suggestions; the very
+/// first account is an admin. Fails with a unique violation if the email is taken.
pub async fn register(pool: &SqlitePool, email: &str, name: &str, password_hash: &str) -> Result {
let mut tx = pool.begin().await?;
- let user_id: i64 = sqlx::query("INSERT INTO users (email, name, password_hash) VALUES (?, ?, ?) RETURNING id")
- .bind(email)
- .bind(name)
- .bind(password_hash)
- .fetch_one(&mut *tx)
- .await?
- .try_get("id")?;
+ let user_id: i64 = sqlx::query(
+ "INSERT INTO users (email, name, password_hash, is_admin)
+ VALUES (?, ?, ?, NOT EXISTS (SELECT 1 FROM users)) RETURNING id",
+ )
+ .bind(email)
+ .bind(name)
+ .bind(password_hash)
+ .fetch_one(&mut *tx)
+ .await?
+ .try_get("id")?;
// Lists created before accounts existed go to the first user.
let claimed = sqlx::query("UPDATE lists SET owner_id = ? WHERE owner_id IS NULL")
@@ -113,7 +117,7 @@ pub async fn register(pool: &SqlitePool, email: &str, name: &str, password_hash:
/// The user and their password hash.
pub async fn user_by_email(pool: &SqlitePool, email: &str) -> Result, sqlx::Error> {
- sqlx::query("SELECT id, name, email, password_hash FROM users WHERE email = ?")
+ sqlx::query("SELECT id, name, email, is_admin, password_hash FROM users WHERE email = ?")
.bind(email)
.fetch_optional(pool)
.await?
@@ -136,7 +140,7 @@ pub async fn create_session(pool: &SqlitePool, token_hash: &str, user_id: i64, d
pub async fn user_by_session(pool: &SqlitePool, token_hash: &str) -> Result, sqlx::Error> {
sqlx::query(
- "SELECT u.id, u.name, u.email FROM sessions s JOIN users u ON u.id = s.user_id
+ "SELECT u.id, u.name, u.email, u.is_admin FROM sessions s JOIN users u ON u.id = s.user_id
WHERE s.token_hash = ? AND s.expires_at > datetime('now')",
)
.bind(token_hash)
@@ -155,6 +159,57 @@ pub async fn delete_session(pool: &SqlitePool, token_hash: &str) -> Result<(), s
Ok(())
}
+// --- Administration ---------------------------------------------------------
+
+pub async fn has_users(pool: &SqlitePool) -> Result {
+ sqlx::query("SELECT EXISTS (SELECT 1 FROM users) AS has_users")
+ .fetch_one(pool)
+ .await?
+ .try_get("has_users")
+}
+
+pub async fn accounts(pool: &SqlitePool) -> Result, sqlx::Error> {
+ sqlx::query("SELECT id, name, email, is_admin, date(created_at) AS created_at FROM users ORDER BY id")
+ .fetch_all(pool)
+ .await?
+ .iter()
+ .map(|row| Ok(Account { user: user_from_row(row)?, created_at: row.try_get("created_at")? }))
+ .collect()
+}
+
+/// Fails with a unique violation if the email is taken.
+pub async fn update_user(pool: &SqlitePool, id: i64, name: &str, email: &str, is_admin: bool) -> Result<(), sqlx::Error> {
+ sqlx::query("UPDATE users SET name = ?, email = ?, is_admin = ? WHERE id = ?")
+ .bind(name)
+ .bind(email)
+ .bind(is_admin)
+ .bind(id)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// Changes the password and signs the user out everywhere.
+pub async fn set_password(pool: &SqlitePool, id: i64, password_hash: &str) -> Result<(), sqlx::Error> {
+ let mut tx = pool.begin().await?;
+ sqlx::query("UPDATE users SET password_hash = ? WHERE id = ?")
+ .bind(password_hash)
+ .bind(id)
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query("DELETE FROM sessions WHERE user_id = ?")
+ .bind(id)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await
+}
+
+/// Deletes the account with its sessions, suggestions and the lists it owns.
+pub async fn delete_user(pool: &SqlitePool, id: i64) -> Result<(), sqlx::Error> {
+ sqlx::query("DELETE FROM users WHERE id = ?").bind(id).execute(pool).await?;
+ Ok(())
+}
+
// --- Lists & sharing --------------------------------------------------------
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -226,7 +281,7 @@ pub async fn delete_list(pool: &SqlitePool, id: i64) -> Result<(), sqlx::Error>
pub async fn members(pool: &SqlitePool, list_id: i64) -> Result, sqlx::Error> {
sqlx::query(
- "SELECT u.id, u.name, u.email FROM list_members m JOIN users u ON u.id = m.user_id
+ "SELECT u.id, u.name, u.email, u.is_admin FROM list_members m JOIN users u ON u.id = m.user_id
WHERE m.list_id = ? ORDER BY u.name",
)
.bind(list_id)
diff --git a/src/model.rs b/src/model.rs
index 4618351..089fc04 100644
--- a/src/model.rs
+++ b/src/model.rs
@@ -38,6 +38,8 @@ pub struct User {
pub id: i64,
pub name: String,
pub email: String,
+ /// Can see and manage every account.
+ pub is_admin: bool,
}
impl User {
@@ -53,6 +55,14 @@ impl User {
}
}
+/// An account as listed on the admin page.
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
+pub struct Account {
+ pub user: User,
+ /// "2026-10-07".
+ pub created_at: String,
+}
+
/// Someone a list is shared with.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Member {
@@ -293,7 +303,7 @@ mod tests {
#[test]
fn initials() {
- let user = |name: &str| User { id: 1, name: name.into(), email: String::new() };
+ let user = |name: &str| User { id: 1, name: name.into(), email: String::new(), is_admin: false };
assert_eq!(user("Camille Lefèvre").initials(), "CL");
assert_eq!(user("romain").initials(), "RO");
assert_eq!(user("élise").initials(), "ÉL");