Ajoute un administrateur qui gère les comptes

Le premier compte inscrit devient administrateur. La page /admin lui
permet de lister, créer, modifier et supprimer les comptes, même quand
les inscriptions sont fermées.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Romulus21andClaude Opus 5.5 committed 2026-10-11 14:03:47 +02:00
1 parent 2ade50465e
commit f3f5f0cee1
7 files changed
+539 -34

No files matched your search

+4
View File
@@ -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);
+128 -17
View File
@@ -1,7 +1,7 @@
use leptos::prelude::*; use leptos::prelude::*;
use leptos::server_fn::codec::Json; 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."; 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)) .ok_or_else(|| ServerFnError::new(super::NOT_LOGGED_IN))
} }
pub async fn require_admin(pool: &SqlitePool) -> Result<User, ServerFnError> {
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<bool, ServerFnError> {
Ok(crate::auth::registration_enabled() || !crate::db::has_users(pool).await.map_err(db_err)?)
}
fn not_found() -> ServerFnError { fn not_found() -> ServerFnError {
ServerFnError::new("Liste introuvable.") ServerFnError::new("Liste introuvable.")
} }
@@ -96,6 +110,29 @@ mod server {
Ok(email) 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<String, ServerFnError> {
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<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> Result<T, ServerFnError> { pub async fn blocking<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> Result<T, ServerFnError> {
tokio::task::spawn_blocking(f) tokio::task::spawn_blocking(f)
.await .await
@@ -113,32 +150,23 @@ pub async fn get_me() -> Result<Option<User>, ServerFnError> {
#[server] #[server]
pub async fn registration_enabled() -> Result<bool, ServerFnError> { pub async fn registration_enabled() -> Result<bool, ServerFnError> {
Ok(crate::auth::registration_enabled()) use server::*;
registration_open(&pool()?).await
} }
#[server] #[server]
pub async fn register(name: String, email: String, password: String) -> Result<(), ServerFnError> { pub async fn register(name: String, email: String, password: String) -> Result<(), ServerFnError> {
use server::*; use server::*;
if !crate::auth::registration_enabled() { let pool = pool()?;
if !registration_open(&pool).await? {
return Err(ServerFnError::new("Les inscriptions sont fermées.")); return Err(ServerFnError::new("Les inscriptions sont fermées."));
} }
let pool = pool()?;
let name = clean_name(&name, 40)?; let name = clean_name(&name, 40)?;
let email = clean_email(&email)?; let email = clean_email(&email)?;
if !(8..=128).contains(&password.chars().count()) { check_password(&password)?;
return Err(ServerFnError::new("Le mot de passe doit faire au moins 8 caractères."));
}
let hash = blocking(move || crate::auth::hash_password(&password)) let hash = hash(password).await?;
.await? let user_id = crate::db::register(&pool, &email, &name, &hash).await.map_err(email_err)?;
.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)),
};
crate::auth::start_session(&pool, user_id).await.map_err(db_err)?; crate::auth::start_session(&pool, user_id).await.map_err(db_err)?;
leptos_axum::redirect("/"); leptos_axum::redirect("/");
Ok(()) Ok(())
@@ -170,6 +198,89 @@ pub async fn logout() -> Result<(), ServerFnError> {
Ok(()) Ok(())
} }
// --- Administration ---------------------------------------------------------
#[server]
pub async fn get_accounts() -> Result<Vec<Account>, 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 ------------------------------------------------------------------ // --- Lists ------------------------------------------------------------------
#[server] #[server]
+15 -3
View File
@@ -97,7 +97,7 @@ fn AuthLayout(title: &'static str, children: Children) -> impl IntoView {
} }
#[component] #[component]
fn FormError(#[prop(into)] error: Signal<Option<String>>) -> impl IntoView { pub fn FormError(#[prop(into)] error: Signal<Option<String>>) -> impl IntoView {
move || { move || {
error.get().map(|msg| { error.get().map(|msg| {
view! { view! {
@@ -207,7 +207,7 @@ pub fn RegisterPage() -> impl IntoView {
} }
#[component] #[component]
fn Field(label: &'static str, children: Children) -> impl IntoView { pub fn Field(label: &'static str, children: Children) -> impl IntoView {
view! { view! {
<label class="flex flex-col gap-1.5"> <label class="flex flex-col gap-1.5">
<span class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">{label}</span> <span class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">{label}</span>
@@ -241,7 +241,19 @@ pub fn AccountSheet(user: User) -> impl IntoView {
<Show when=move || ctx.account_open.get()> <Show when=move || ctx.account_open.get()>
<Sheet title=user.with_value(|u| u.name.clone()) on_close=close> <Sheet title=user.with_value(|u| u.name.clone()) on_close=close>
<p class="mt-1 text-ink/70">{user.with_value(|u| u.email.clone())}</p> <p class="mt-1 text-ink/70">{user.with_value(|u| u.email.clone())}</p>
<ActionForm action=auth.logout attr:class="mt-6"> {user
.with_value(|u| u.is_admin)
.then(|| {
view! {
<A
href="/admin"
attr:class="mt-6 block w-full rounded-2xl border-2 border-ink bg-lime px-4 py-3 text-center font-semibold"
>
"Gérer les utilisateurs"
</A>
}
})}
<ActionForm action=auth.logout attr:class="mt-3">
<button <button
type="submit" type="submit"
class="w-full rounded-2xl border-2 border-ink px-4 py-3 font-semibold" class="w-full rounded-2xl border-2 border-ink px-4 py-3 font-semibold"
+310
View File
@@ -0,0 +1,310 @@
use leptos::ev;
use leptos::prelude::*;
use leptos::task::spawn_local;
use leptos_router::components::A;
use super::account::{Auth, Field, FormError, RequireUser};
use super::error_message;
use super::sheets::Sheet;
use crate::api::{create_account, delete_account, get_accounts, update_account};
use crate::model::{Account, User};
#[derive(Clone, Debug, PartialEq)]
enum AccountEditor {
New,
Edit(User),
}
#[component]
pub fn AdminPage() -> impl IntoView {
view! { <RequireUser render=|user| view! { <AdminView me=user /> } /> }
}
#[component]
fn AdminView(me: User) -> impl IntoView {
if !me.is_admin {
return view! {
<AdminLayout>
<section class="ticket relative mt-6 bg-paper px-5 pt-6 pb-8">
<p class="text-lg text-ink/70">"Cette page est réservée aux administrateurs."</p>
</section>
</AdminLayout>
}
.into_any();
}
let version = RwSignal::new(0);
let editor = RwSignal::new(None::<AccountEditor>);
let accounts = Resource::new(move || version.get(), |_| get_accounts());
let me_id = me.id;
view! {
<AdminLayout>
<section class="ticket relative mt-6 bg-paper px-5 pt-6 pb-8">
<p class="font-mono text-sm tracking-[0.2em] text-ink/60 uppercase">"Lisette · Comptes"</p>
<h2 class="mt-1 font-display text-[1.7rem] leading-tight font-bold tracking-tight">
"Utilisateurs"
</h2>
<Transition fallback=|| view! { <p class="mt-4 text-ink/50">"…"</p> }>
{move || Suspend::new(async move {
match accounts.await {
Ok(accounts) => view! { <AccountRows accounts me_id editor /> }.into_any(),
Err(err) => {
view! { <p class="mt-4 font-medium">{error_message(err)}</p> }.into_any()
}
}
})}
</Transition>
</section>
<button
class="tile-shadow fixed right-[max(1rem,calc(50vw-14rem+1rem))] bottom-[max(1.25rem,env(safe-area-inset-bottom))] z-10 rounded-2xl border-2 border-ink bg-pink px-6 py-4 font-display text-xl font-bold active:translate-y-1 active:shadow-none"
on:click=move |_| editor.set(Some(AccountEditor::New))
>
"+ compte"
</button>
</AdminLayout>
{move || {
editor
.get()
.map(|current| {
view! {
<AccountForm
editor=current
me_id
on_close=move || editor.set(None)
on_saved=move || version.update(|v| *v += 1)
/>
}
})
}}
}
.into_any()
}
#[component]
fn AdminLayout(children: Children) -> impl IntoView {
view! {
<main class="mx-auto flex min-h-dvh max-w-md flex-col px-4 pt-[max(1.5rem,env(safe-area-inset-top))] pb-32">
<header class="flex items-start justify-between gap-4">
<h1 class="font-display text-5xl leading-[0.9] font-extrabold tracking-tight">"admin"</h1>
<A
href="/"
attr:class="shrink-0 rounded-2xl border-2 border-ink bg-paper px-4 py-3 font-semibold"
>
"← mes listes"
</A>
</header>
{children()}
</main>
}
}
#[component]
fn AccountRows(
accounts: Vec<Account>,
me_id: i64,
editor: RwSignal<Option<AccountEditor>>,
) -> impl IntoView {
view! {
<p class="mt-1 text-lg text-ink/70">
{match accounts.len() {
1 => "1 compte.".to_owned(),
n => format!("{n} comptes."),
}}
</p>
<ul class="mt-5 flex flex-col gap-2">
{accounts
.into_iter()
.map(|Account { user, created_at }| {
let is_me = user.id == me_id;
let edited = user.clone();
view! {
<li>
<button
class="flex w-full items-center justify-between gap-3 rounded-xl bg-mist px-3 py-2 text-left active:bg-ink/10"
on:click=move |_| editor.set(Some(AccountEditor::Edit(edited.clone())))
>
<div class="min-w-0">
<p class="truncate font-semibold">
{user.name.clone()}
{is_me.then_some(" (toi)")}
</p>
<p class="truncate text-sm text-ink/60">{user.email.clone()}</p>
<p class="text-sm text-ink/50">{format!("Inscrit·e le {}", french_date(&created_at))}</p>
</div>
{user
.is_admin
.then(|| {
view! {
<span class="shrink-0 rounded-lg border-2 border-ink bg-lime px-2 py-0.5 font-mono text-xs uppercase">
"admin"
</span>
}
})}
</button>
</li>
}
})
.collect_view()}
</ul>
}
}
#[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::<Auth>();
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::<String>);
let pending = RwSignal::new(false);
let run = move |call: std::pin::Pin<Box<dyn Future<Output = Result<(), ServerFnError>>>>| {
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! {
<Sheet title=title.to_owned() on_close>
<form class="mt-4 flex flex-col gap-4" on:submit=submit>
<FormError error=error />
<Field label="Prénom ou pseudo">
<input class="field" required maxlength="40" autocomplete="off" bind:value=name />
</Field>
<Field label="Email">
<input class="field" type="email" required autocomplete="off" bind:value=email />
</Field>
<Field label=password_label>
<input
class="field"
type="password"
required=user_id.is_none()
minlength="8"
maxlength="128"
autocomplete="new-password"
bind:value=password
/>
</Field>
<label class="flex items-center gap-3 font-medium">
<input
type="checkbox"
class="size-6 accent-ink"
disabled=is_me
bind:checked=is_admin
/>
"Administrateur"
</label>
<div class="mt-2 flex gap-3">
{(user_id.is_some() && !is_me)
.then(|| {
view! {
<button
type="button"
class="rounded-2xl border-2 border-ink px-4 py-3 font-semibold"
disabled=move || pending.get()
on:click=delete
>
"Supprimer"
</button>
}
})}
<button
type="submit"
class="tile-shadow flex-1 rounded-2xl border-2 border-ink bg-pink px-4 py-3 font-display text-lg font-bold active:translate-y-1 active:shadow-none disabled:opacity-60"
disabled=move || pending.get()
>
{if user_id.is_some() { "Enregistrer" } else { "Créer" }}
</button>
</div>
</form>
</Sheet>
}
}
/// "2026-10-07" → "07/10/2026".
fn french_date(iso: &str) -> String {
match iso.split('-').collect::<Vec<_>>().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");
}
}
+3
View File
@@ -1,4 +1,5 @@
mod account; mod account;
mod admin;
mod icons; mod icons;
mod live; mod live;
mod sheets; mod sheets;
@@ -17,6 +18,7 @@ use leptos_router::path;
use crate::api::{get_items, get_lists, get_suggestions}; use crate::api::{get_items, get_lists, get_suggestions};
use crate::model::{Item, ShoppingList, Suggestion, User}; use crate::model::{Item, ShoppingList, Suggestion, User};
use account::{AccountSheet, Auth, LoginPage, RegisterPage, RequireUser}; use account::{AccountSheet, Auth, LoginPage, RegisterPage, RequireUser};
use admin::AdminPage;
use sheets::{ItemEditor, ItemSheet, ListEditor, ListSheet}; use sheets::{ItemEditor, ItemSheet, ListEditor, ListSheet};
use tiles::{BasketTile, ItemTile, SuggestionTile}; use tiles::{BasketTile, ItemTile, SuggestionTile};
@@ -72,6 +74,7 @@ pub fn App() -> impl IntoView {
<Route path=path!("/l/:id") view=ListsPage /> <Route path=path!("/l/:id") view=ListsPage />
<Route path=path!("/connexion") view=LoginPage /> <Route path=path!("/connexion") view=LoginPage />
<Route path=path!("/inscription") view=RegisterPage /> <Route path=path!("/inscription") view=RegisterPage />
<Route path=path!("/admin") view=AdminPage />
</Routes> </Routes>
</Router> </Router>
} }
+68 -13
View File
@@ -3,7 +3,7 @@ use sqlx::{Row, SqliteConnection};
use std::str::FromStr; use std::str::FromStr;
use crate::model::{ 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<SqlitePool, sqlx::Error> { pub async fn connect(url: &str) -> Result<SqlitePool, sqlx::Error> {
@@ -61,6 +61,7 @@ fn user_from_row(row: &SqliteRow) -> Result<User, sqlx::Error> {
id: row.try_get("id")?, id: row.try_get("id")?,
name: row.try_get("name")?, name: row.try_get("name")?,
email: row.try_get("email")?, 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), ("Café en grains", Icon::Coffee, Category::Epicerie),
]; ];
/// Creates the account with a first list and starter suggestions. /// Creates the account with a first list and starter suggestions; the very
/// Fails with a unique violation if the email is taken. /// 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<i64, sqlx::Error> { pub async fn register(pool: &SqlitePool, email: &str, name: &str, password_hash: &str) -> Result<i64, sqlx::Error> {
let mut tx = pool.begin().await?; let mut tx = pool.begin().await?;
let user_id: i64 = sqlx::query("INSERT INTO users (email, name, password_hash) VALUES (?, ?, ?) RETURNING id") let user_id: i64 = sqlx::query(
.bind(email) "INSERT INTO users (email, name, password_hash, is_admin)
.bind(name) VALUES (?, ?, ?, NOT EXISTS (SELECT 1 FROM users)) RETURNING id",
.bind(password_hash) )
.fetch_one(&mut *tx) .bind(email)
.await? .bind(name)
.try_get("id")?; .bind(password_hash)
.fetch_one(&mut *tx)
.await?
.try_get("id")?;
// Lists created before accounts existed go to the first user. // Lists created before accounts existed go to the first user.
let claimed = sqlx::query("UPDATE lists SET owner_id = ? WHERE owner_id IS NULL") 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. /// The user and their password hash.
pub async fn user_by_email(pool: &SqlitePool, email: &str) -> Result<Option<(User, String)>, sqlx::Error> { pub async fn user_by_email(pool: &SqlitePool, email: &str) -> Result<Option<(User, String)>, 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) .bind(email)
.fetch_optional(pool) .fetch_optional(pool)
.await? .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<Option<User>, sqlx::Error> { pub async fn user_by_session(pool: &SqlitePool, token_hash: &str) -> Result<Option<User>, sqlx::Error> {
sqlx::query( 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')", WHERE s.token_hash = ? AND s.expires_at > datetime('now')",
) )
.bind(token_hash) .bind(token_hash)
@@ -155,6 +159,57 @@ pub async fn delete_session(pool: &SqlitePool, token_hash: &str) -> Result<(), s
Ok(()) Ok(())
} }
// --- Administration ---------------------------------------------------------
pub async fn has_users(pool: &SqlitePool) -> Result<bool, sqlx::Error> {
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<Vec<Account>, 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 -------------------------------------------------------- // --- Lists & sharing --------------------------------------------------------
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[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<Vec<Member>, sqlx::Error> { pub async fn members(pool: &SqlitePool, list_id: i64) -> Result<Vec<Member>, sqlx::Error> {
sqlx::query( 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", WHERE m.list_id = ? ORDER BY u.name",
) )
.bind(list_id) .bind(list_id)
+11 -1
View File
@@ -38,6 +38,8 @@ pub struct User {
pub id: i64, pub id: i64,
pub name: String, pub name: String,
pub email: String, pub email: String,
/// Can see and manage every account.
pub is_admin: bool,
} }
impl User { 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. /// Someone a list is shared with.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Member { pub struct Member {
@@ -293,7 +303,7 @@ mod tests {
#[test] #[test]
fn initials() { 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("Camille Lefèvre").initials(), "CL");
assert_eq!(user("romain").initials(), "RO"); assert_eq!(user("romain").initials(), "RO");
assert_eq!(user("élise").initials(), "ÉL"); assert_eq!(user("élise").initials(), "ÉL");