Ajoute l'authentification et le partage de listes

- Inscription / connexion par email + mot de passe (argon2), prénom ou
  pseudo enregistré ; session par cookie HttpOnly, jeton haché en base.
- Listes privées par propriétaire, partageables par email ; les membres
  peuvent gérer les articles et quitter la liste.
- Contrôle d'accès dans chaque server function.
- Suggestions propres à chaque utilisateur.
- Avatar avec initiales et feuille de compte (déconnexion).
- La page 404 reçoit le pool SQLite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Romulus21andClaude Opus 5.5 committed 2026-10-09 12:47:09 +02:00
1 parent 9536cf0dbe
commit cbda09ed40
12 files changed
+1078 -55

No files matched your search

Generated
+36
View File
@@ -35,6 +35,18 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "argon2"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
dependencies = [
"base64ct",
"blake2",
"cpufeatures",
"password-hash",
]
[[package]] [[package]]
name = "async-lock" name = "async-lock"
version = "3.4.2" version = "3.4.2"
@@ -196,6 +208,15 @@ dependencies = [
"serde_core", "serde_core",
] ]
[[package]]
name = "blake2"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
dependencies = [
"digest",
]
[[package]] [[package]]
name = "block-buffer" name = "block-buffer"
version = "0.10.4" version = "0.10.4"
@@ -1371,13 +1392,17 @@ dependencies = [
name = "lisette" name = "lisette"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"argon2",
"axum", "axum",
"console_error_panic_hook", "console_error_panic_hook",
"hex",
"leptos", "leptos",
"leptos_axum", "leptos_axum",
"leptos_meta", "leptos_meta",
"leptos_router", "leptos_router",
"rand_core 0.6.4",
"serde", "serde",
"sha2",
"sqlx", "sqlx",
"tokio", "tokio",
"wasm-bindgen", "wasm-bindgen",
@@ -1601,6 +1626,17 @@ dependencies = [
"windows-link", "windows-link",
] ]
[[package]]
name = "password-hash"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
dependencies = [
"base64ct",
"rand_core 0.6.4",
"subtle",
]
[[package]] [[package]]
name = "paste" name = "paste"
version = "1.0.15" version = "1.0.15"
+8
View File
@@ -14,6 +14,10 @@ leptos_axum = { version = "0.8", optional = true }
axum = { version = "0.8", optional = true } axum = { version = "0.8", optional = true }
tokio = { version = "1", features = ["rt-multi-thread", "macros"], optional = true } tokio = { version = "1", features = ["rt-multi-thread", "macros"], optional = true }
sqlx = { version = "0.8", default-features = false, features = ["sqlite", "runtime-tokio", "macros", "migrate"], optional = true } sqlx = { version = "0.8", default-features = false, features = ["sqlite", "runtime-tokio", "macros", "migrate"], optional = true }
argon2 = { version = "0.5", optional = true }
rand_core = { version = "0.6", features = ["getrandom"], optional = true }
sha2 = { version = "0.10", optional = true }
hex = { version = "0.4", optional = true }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
wasm-bindgen = { version = "=0.2.128", optional = true } wasm-bindgen = { version = "=0.2.128", optional = true }
console_error_panic_hook = { version = "0.1", optional = true } console_error_panic_hook = { version = "0.1", optional = true }
@@ -25,6 +29,10 @@ ssr = [
"dep:tokio", "dep:tokio",
"dep:sqlx", "dep:sqlx",
"dep:leptos_axum", "dep:leptos_axum",
"dep:argon2",
"dep:rand_core",
"dep:sha2",
"dep:hex",
"leptos/ssr", "leptos/ssr",
"leptos_meta/ssr", "leptos_meta/ssr",
"leptos_router/ssr", "leptos_router/ssr",
+41
View File
@@ -0,0 +1,41 @@
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
name TEXT NOT NULL,
password_hash TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
-- Only a SHA-256 of the cookie token is stored.
CREATE TABLE sessions (
token_hash TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at TEXT NOT NULL
);
CREATE INDEX sessions_user_id ON sessions(user_id);
-- NULL owner = list created before accounts existed; claimed by the first user to register.
ALTER TABLE lists ADD COLUMN owner_id INTEGER REFERENCES users(id) ON DELETE CASCADE;
CREATE INDEX lists_owner_id ON lists(owner_id);
CREATE TABLE list_members (
list_id INTEGER NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
PRIMARY KEY (list_id, user_id)
);
CREATE INDEX list_members_user_id ON list_members(user_id);
-- Suggestions become per user.
DROP TABLE catalog;
CREATE TABLE catalog (
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL COLLATE NOCASE,
icon TEXT NOT NULL,
category TEXT NOT NULL,
use_count INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (user_id, name)
);
+205 -18
View File
@@ -1,13 +1,18 @@
use leptos::prelude::*; use leptos::prelude::*;
use leptos::server_fn::codec::Json; use leptos::server_fn::codec::Json;
use crate::model::{Item, ItemInput, ListColor, ShoppingList, Suggestion}; use crate::model::{Item, ItemInput, ListColor, Member, ShoppingList, Suggestion, User};
pub const NOT_LOGGED_IN: &str = "Session expirée, reconnecte-toi.";
#[cfg(feature = "ssr")] #[cfg(feature = "ssr")]
mod server { mod server {
use leptos::prelude::*; use leptos::prelude::*;
use sqlx::SqlitePool; use sqlx::SqlitePool;
use crate::db::Role;
use crate::model::User;
pub fn pool() -> Result<SqlitePool, ServerFnError> { pub fn pool() -> Result<SqlitePool, ServerFnError> {
use_context::<SqlitePool>().ok_or_else(|| ServerFnError::new("database pool missing")) use_context::<SqlitePool>().ok_or_else(|| ServerFnError::new("database pool missing"))
} }
@@ -17,75 +22,257 @@ mod server {
ServerFnError::new("Erreur de base de données") ServerFnError::new("Erreur de base de données")
} }
pub fn clean_name(name: &str) -> Result<String, ServerFnError> { pub async fn require_user(pool: &SqlitePool) -> Result<User, ServerFnError> {
crate::auth::current_user(pool)
.await
.map_err(db_err)?
.ok_or_else(|| ServerFnError::new(super::NOT_LOGGED_IN))
}
fn not_found() -> ServerFnError {
ServerFnError::new("Liste introuvable.")
}
/// Fails unless the user owns the list or it is shared with them.
pub async fn require_list(pool: &SqlitePool, user: &User, list_id: i64) -> Result<Role, ServerFnError> {
crate::db::list_role(pool, user.id, list_id)
.await
.map_err(db_err)?
.ok_or_else(not_found)
}
pub async fn require_owner(pool: &SqlitePool, user: &User, list_id: i64) -> Result<(), ServerFnError> {
match require_list(pool, user, list_id).await? {
Role::Owner => Ok(()),
Role::Member => Err(ServerFnError::new("Seul le propriétaire de la liste peut faire ça.")),
}
}
/// Fails unless the item belongs to a list the user can access.
pub async fn require_item(pool: &SqlitePool, user: &User, item_id: i64) -> Result<(), ServerFnError> {
let list_id = crate::db::item_list_id(pool, item_id)
.await
.map_err(db_err)?
.ok_or_else(|| ServerFnError::new("Article introuvable."))?;
require_list(pool, user, list_id).await.map(|_| ())
}
pub fn clean_name(name: &str, max: usize) -> Result<String, ServerFnError> {
let name = name.trim(); let name = name.trim();
if name.is_empty() || name.chars().count() > 60 { if name.is_empty() || name.chars().count() > max {
return Err(ServerFnError::new("Le nom doit faire entre 1 et 60 caractères")); return Err(ServerFnError::new(format!("Le nom doit faire entre 1 et {max} caractères.")));
} }
Ok(name.to_owned()) Ok(name.to_owned())
} }
pub fn clean_email(email: &str) -> Result<String, ServerFnError> {
let email = email.trim().to_lowercase();
let valid = email.len() <= 254
&& email
.split_once('@')
.is_some_and(|(local, domain)| !local.is_empty() && domain.contains('.') && !domain.starts_with('.'));
if !valid {
return Err(ServerFnError::new("Adresse email invalide."));
} }
Ok(email)
}
pub async fn blocking<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> Result<T, ServerFnError> {
tokio::task::spawn_blocking(f)
.await
.map_err(|_| ServerFnError::new("Erreur interne"))
}
}
// --- Account ----------------------------------------------------------------
#[server]
pub async fn get_me() -> Result<Option<User>, ServerFnError> {
use server::*;
crate::auth::current_user(&pool()?).await.map_err(db_err)
}
#[server]
pub async fn register(name: String, email: String, password: String) -> Result<(), ServerFnError> {
use server::*;
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."));
}
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)),
};
crate::auth::start_session(&pool, user_id).await.map_err(db_err)?;
leptos_axum::redirect("/");
Ok(())
}
#[server]
pub async fn login(email: String, password: String) -> Result<(), ServerFnError> {
use server::*;
let pool = pool()?;
let found = crate::db::user_by_email(&pool, email.trim()).await.map_err(db_err)?;
let (user, hash) = match found {
Some((user, hash)) => (Some(user), hash),
None => (None, crate::auth::dummy_hash().to_owned()),
};
let valid = blocking(move || crate::auth::verify_password(&password, &hash)).await?;
let Some(user) = user.filter(|_| valid) else {
return Err(ServerFnError::new("Email ou mot de passe incorrect."));
};
crate::auth::start_session(&pool, user.id).await.map_err(db_err)?;
leptos_axum::redirect("/");
Ok(())
}
#[server]
pub async fn logout() -> Result<(), ServerFnError> {
use server::*;
crate::auth::end_session(&pool()?).await.map_err(db_err)?;
leptos_axum::redirect("/connexion");
Ok(())
}
// --- Lists ------------------------------------------------------------------
#[server] #[server]
pub async fn get_lists() -> Result<Vec<ShoppingList>, ServerFnError> { pub async fn get_lists() -> Result<Vec<ShoppingList>, ServerFnError> {
use server::*; use server::*;
crate::db::lists(&pool()?).await.map_err(db_err) let pool = pool()?;
let user = require_user(&pool).await?;
crate::db::lists(&pool, user.id).await.map_err(db_err)
} }
#[server] #[server]
pub async fn create_list(name: String, color: ListColor) -> Result<i64, ServerFnError> { pub async fn create_list(name: String, color: ListColor) -> Result<i64, ServerFnError> {
use server::*; use server::*;
let name = clean_name(&name)?; let pool = pool()?;
crate::db::create_list(&pool()?, &name, color).await.map_err(db_err) let user = require_user(&pool).await?;
let name = clean_name(&name, 60)?;
crate::db::create_list(&pool, user.id, &name, color).await.map_err(db_err)
} }
#[server] #[server]
pub async fn rename_list(id: i64, name: String) -> Result<(), ServerFnError> { pub async fn rename_list(id: i64, name: String) -> Result<(), ServerFnError> {
use server::*; use server::*;
let name = clean_name(&name)?; let pool = pool()?;
crate::db::rename_list(&pool()?, id, &name).await.map_err(db_err) let user = require_user(&pool).await?;
require_owner(&pool, &user, id).await?;
let name = clean_name(&name, 60)?;
crate::db::rename_list(&pool, id, &name).await.map_err(db_err)
} }
#[server] #[server]
pub async fn delete_list(id: i64) -> Result<(), ServerFnError> { pub async fn delete_list(id: i64) -> Result<(), ServerFnError> {
use server::*; use server::*;
crate::db::delete_list(&pool()?, id).await.map_err(db_err) let pool = pool()?;
let user = require_user(&pool).await?;
require_owner(&pool, &user, id).await?;
crate::db::delete_list(&pool, id).await.map_err(db_err)
} }
#[server]
pub async fn get_members(list_id: i64) -> Result<Vec<Member>, ServerFnError> {
use server::*;
let pool = pool()?;
let user = require_user(&pool).await?;
require_list(&pool, &user, list_id).await?;
crate::db::members(&pool, list_id).await.map_err(db_err)
}
#[server]
pub async fn share_list(list_id: i64, email: String) -> Result<(), ServerFnError> {
use server::*;
let pool = pool()?;
let user = require_user(&pool).await?;
require_owner(&pool, &user, list_id).await?;
let email = clean_email(&email)?;
let (friend, _) = crate::db::user_by_email(&pool, &email)
.await
.map_err(db_err)?
.ok_or_else(|| ServerFnError::new("Aucun compte avec cet email."))?;
if friend.id == user.id {
return Err(ServerFnError::new("Tu es déjà propriétaire de cette liste."));
}
crate::db::add_member(&pool, list_id, friend.id).await.map_err(db_err)
}
/// The owner removes someone, or a member leaves (`user_id` = themself).
#[server]
pub async fn remove_member(list_id: i64, user_id: i64) -> Result<(), ServerFnError> {
use server::*;
let pool = pool()?;
let user = require_user(&pool).await?;
if user_id != user.id {
require_owner(&pool, &user, list_id).await?;
}
crate::db::remove_member(&pool, list_id, user_id).await.map_err(db_err)
}
// --- Items ------------------------------------------------------------------
#[server] #[server]
pub async fn get_items(list_id: i64) -> Result<Vec<Item>, ServerFnError> { pub async fn get_items(list_id: i64) -> Result<Vec<Item>, ServerFnError> {
use server::*; use server::*;
crate::db::items(&pool()?, list_id).await.map_err(db_err) let pool = pool()?;
let user = require_user(&pool).await?;
require_list(&pool, &user, list_id).await?;
crate::db::items(&pool, list_id).await.map_err(db_err)
} }
#[server(input = Json)] #[server(input = Json)]
pub async fn add_item(list_id: i64, input: ItemInput) -> Result<i64, ServerFnError> { pub async fn add_item(list_id: i64, input: ItemInput) -> Result<i64, ServerFnError> {
use server::*; use server::*;
let input = ItemInput { name: clean_name(&input.name)?, ..input }; let pool = pool()?;
crate::db::add_item(&pool()?, list_id, &input).await.map_err(db_err) let user = require_user(&pool).await?;
require_list(&pool, &user, list_id).await?;
let input = ItemInput { name: clean_name(&input.name, 60)?, ..input };
crate::db::add_item(&pool, user.id, list_id, &input).await.map_err(db_err)
} }
#[server(input = Json)] #[server(input = Json)]
pub async fn update_item(id: i64, input: ItemInput) -> Result<(), ServerFnError> { pub async fn update_item(id: i64, input: ItemInput) -> Result<(), ServerFnError> {
use server::*; use server::*;
let input = ItemInput { name: clean_name(&input.name)?, ..input }; let pool = pool()?;
crate::db::update_item(&pool()?, id, &input).await.map_err(db_err) let user = require_user(&pool).await?;
require_item(&pool, &user, id).await?;
let input = ItemInput { name: clean_name(&input.name, 60)?, ..input };
crate::db::update_item(&pool, id, &input).await.map_err(db_err)
} }
#[server] #[server]
pub async fn delete_item(id: i64) -> Result<(), ServerFnError> { pub async fn delete_item(id: i64) -> Result<(), ServerFnError> {
use server::*; use server::*;
crate::db::delete_item(&pool()?, id).await.map_err(db_err) let pool = pool()?;
let user = require_user(&pool).await?;
require_item(&pool, &user, id).await?;
crate::db::delete_item(&pool, id).await.map_err(db_err)
} }
#[server] #[server]
pub async fn set_checked(id: i64, checked: bool) -> Result<(), ServerFnError> { pub async fn set_checked(id: i64, checked: bool) -> Result<(), ServerFnError> {
use server::*; use server::*;
crate::db::set_checked(&pool()?, id, checked).await.map_err(db_err) let pool = pool()?;
let user = require_user(&pool).await?;
require_item(&pool, &user, id).await?;
crate::db::set_checked(&pool, id, checked).await.map_err(db_err)
} }
#[server] #[server]
pub async fn get_suggestions(list_id: i64) -> Result<Vec<Suggestion>, ServerFnError> { pub async fn get_suggestions(list_id: i64) -> Result<Vec<Suggestion>, ServerFnError> {
use server::*; use server::*;
crate::db::suggestions(&pool()?, list_id, 3).await.map_err(db_err) let pool = pool()?;
let user = require_user(&pool).await?;
require_list(&pool, &user, list_id).await?;
crate::db::suggestions(&pool, user.id, list_id, 3).await.map_err(db_err)
} }
+216
View File
@@ -0,0 +1,216 @@
use leptos::prelude::*;
use leptos_router::components::{A, Redirect};
use super::sheets::Sheet;
use super::{Ctx, error_message};
use crate::api::{Login, Logout, Register, get_me};
use crate::model::User;
/// Session state shared by the whole app.
#[derive(Clone, Copy)]
pub struct Auth {
pub me: Resource<Result<Option<User>, ServerFnError>>,
pub login: ServerAction<Login>,
pub register: ServerAction<Register>,
pub logout: ServerAction<Logout>,
}
impl Auth {
pub fn provide() -> Self {
let login = ServerAction::<Login>::new();
let register = ServerAction::<Register>::new();
let logout = ServerAction::<Logout>::new();
let me = Resource::new(
move || (login.version().get(), register.version().get(), logout.version().get()),
|_| get_me(),
);
let auth = Auth { me, login, register, logout };
provide_context(auth);
auth
}
}
/// Renders `render` with the signed-in user, or redirects to the login page.
#[component]
pub fn RequireUser<F, V>(render: F) -> impl IntoView
where
F: Fn(User) -> V + Send + Sync + 'static,
V: IntoView + 'static,
{
let auth = expect_context::<Auth>();
let render = StoredValue::new(render);
view! {
<Transition>
{move || Suspend::new(async move {
match auth.me.await {
Ok(Some(user)) => render.with_value(|render| render(user)).into_any(),
_ => view! { <Redirect path="/connexion" /> }.into_any(),
}
})}
</Transition>
}
}
/// Sends a signed-in user away from the login and sign-up pages.
#[component]
fn RedirectIfSignedIn() -> impl IntoView {
let auth = expect_context::<Auth>();
view! {
<Transition>
{move || Suspend::new(async move {
matches!(auth.me.await, Ok(Some(_))).then(|| view! { <Redirect path="/" /> })
})}
</Transition>
}
}
#[component]
fn AuthLayout(title: &'static str, children: Children) -> impl IntoView {
view! {
<RedirectIfSignedIn />
<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-16">
<h1 class="font-display text-5xl leading-[0.9] font-extrabold tracking-tight">
"mes"<br />"listes"
</h1>
<section class="ticket relative mt-8 bg-paper px-5 pt-6 pb-8">
<p class="font-mono text-sm tracking-[0.2em] text-ink/60 uppercase">"Lisette · Courses"</p>
<h2 class="mt-1 font-display text-[1.7rem] leading-tight font-bold tracking-tight">{title}</h2>
{children()}
</section>
</main>
}
}
#[component]
fn FormError(#[prop(into)] error: Signal<Option<String>>) -> impl IntoView {
move || {
error.get().map(|msg| {
view! {
<p role="alert" class="rounded-xl border-2 border-ink bg-pink px-3 py-2 font-medium">
{msg}
</p>
}
})
}
}
#[component]
pub fn LoginPage() -> impl IntoView {
let auth = expect_context::<Auth>();
view! {
<AuthLayout title="Connexion">
<ActionForm action=auth.login attr:class="mt-5 flex flex-col gap-4">
<FormError error=Signal::derive(move || auth.login.value().get().and_then(Result::err).map(error_message)) />
<Field label="Email">
<input class="field" type="email" name="email" required autocomplete="email" />
</Field>
<Field label="Mot de passe">
<input
class="field"
type="password"
name="password"
required
autocomplete="current-password"
/>
</Field>
<SubmitButton pending=auth.login.pending() label="Se connecter" />
</ActionForm>
<p class="mt-6 text-center text-ink/70">
"Pas encore de compte ? "
<A href="/inscription" attr:class="font-semibold text-ink underline">
"Créer un compte"
</A>
</p>
</AuthLayout>
}
}
#[component]
pub fn RegisterPage() -> impl IntoView {
let auth = expect_context::<Auth>();
view! {
<AuthLayout title="Créer un compte">
<ActionForm action=auth.register attr:class="mt-5 flex flex-col gap-4">
<FormError error=Signal::derive(move || auth.register.value().get().and_then(Result::err).map(error_message)) />
<Field label="Prénom ou pseudo">
<input
class="field"
name="name"
required
maxlength="40"
autocomplete="given-name"
/>
</Field>
<Field label="Email">
<input class="field" type="email" name="email" required autocomplete="email" />
</Field>
<Field label="Mot de passe (8 caractères min.)">
<input
class="field"
type="password"
name="password"
required
minlength="8"
maxlength="128"
autocomplete="new-password"
/>
</Field>
<SubmitButton pending=auth.register.pending() label="Créer mon compte" />
</ActionForm>
<p class="mt-6 text-center text-ink/70">
"Déjà inscrit·e ? "
<A href="/connexion" attr:class="font-semibold text-ink underline">
"Se connecter"
</A>
</p>
</AuthLayout>
}
}
#[component]
fn Field(label: &'static str, children: Children) -> impl IntoView {
view! {
<label class="flex flex-col gap-1.5">
<span class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">{label}</span>
{children()}
</label>
}
}
#[component]
fn SubmitButton(#[prop(into)] pending: Signal<bool>, label: &'static str) -> impl IntoView {
view! {
<button
type="submit"
class="tile-shadow mt-2 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()
>
{label}
</button>
}
}
/// Avatar sheet: who is signed in, and sign out.
#[component]
pub fn AccountSheet(user: User) -> impl IntoView {
let auth = expect_context::<Auth>();
let ctx = expect_context::<Ctx>();
let close = move || ctx.account_open.set(false);
let user = StoredValue::new(user);
view! {
<Show when=move || ctx.account_open.get()>
<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>
<ActionForm action=auth.logout attr:class="mt-6">
<button
type="submit"
class="w-full rounded-2xl border-2 border-ink px-4 py-3 font-semibold"
>
"Se déconnecter"
</button>
</ActionForm>
</Sheet>
</Show>
}
}
+42 -7
View File
@@ -1,3 +1,4 @@
mod account;
mod icons; mod icons;
mod sheets; mod sheets;
mod tiles; mod tiles;
@@ -13,7 +14,8 @@ use leptos_router::hooks::use_params_map;
use leptos_router::path; 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}; use crate::model::{Item, ShoppingList, Suggestion, User};
use account::{AccountSheet, Auth, LoginPage, RegisterPage, RequireUser};
use sheets::{ItemEditor, ItemSheet, ListEditor, ListSheet}; use sheets::{ItemEditor, ItemSheet, ListEditor, ListSheet};
use tiles::{BasketTile, ItemTile, SuggestionTile}; use tiles::{BasketTile, ItemTile, SuggestionTile};
@@ -41,6 +43,7 @@ pub fn shell(options: LeptosOptions) -> impl IntoView {
#[component] #[component]
pub fn App() -> impl IntoView { pub fn App() -> impl IntoView {
provide_meta_context(); provide_meta_context();
Auth::provide();
view! { view! {
<Stylesheet id="leptos" href="/pkg/lisette.css" /> <Stylesheet id="leptos" href="/pkg/lisette.css" />
@@ -59,6 +62,8 @@ pub fn App() -> impl IntoView {
<Routes fallback=|| view! { <p class="p-4">"Page introuvable."</p> }> <Routes fallback=|| view! { <p class="p-4">"Page introuvable."</p> }>
<Route path=path!("/") view=ListsPage /> <Route path=path!("/") view=ListsPage />
<Route path=path!("/l/:id") view=ListsPage /> <Route path=path!("/l/:id") view=ListsPage />
<Route path=path!("/connexion") view=LoginPage />
<Route path=path!("/inscription") view=RegisterPage />
</Routes> </Routes>
</Router> </Router>
} }
@@ -74,6 +79,9 @@ pub struct Ctx {
optimistic: RwSignal<HashMap<i64, bool>>, optimistic: RwSignal<HashMap<i64, bool>>,
item_editor: RwSignal<Option<ItemEditor>>, item_editor: RwSignal<Option<ItemEditor>>,
list_editor: RwSignal<Option<ListEditor>>, list_editor: RwSignal<Option<ListEditor>>,
account_open: RwSignal<bool>,
user_id: i64,
auth: Auth,
} }
impl Ctx { impl Ctx {
@@ -89,11 +97,20 @@ impl Ctx {
on_ok(value); on_ok(value);
self.refresh.update(|n| *n += 1); self.refresh.update(|n| *n += 1);
} }
Err(err) => self.error.set(Some(error_message(err))), Err(err) => self.report(err),
} }
}); });
} }
fn report(self, err: ServerFnError) {
let msg = error_message(err);
if msg == crate::api::NOT_LOGGED_IN {
// The guard sends the user back to the login page.
self.auth.me.refetch();
}
self.error.set(Some(msg));
}
fn toggle(self, item: &Item) { fn toggle(self, item: &Item) {
let (id, checked) = (item.id, !item.checked); let (id, checked) = (item.id, !item.checked);
self.optimistic.update(|map| { self.optimistic.update(|map| {
@@ -104,7 +121,7 @@ impl Ctx {
self.optimistic.update(|map| { self.optimistic.update(|map| {
map.remove(&id); map.remove(&id);
}); });
self.error.set(Some(error_message(err))); self.report(err);
} }
}); });
} }
@@ -119,12 +136,20 @@ fn error_message(err: ServerFnError) -> String {
#[component] #[component]
fn ListsPage() -> impl IntoView { fn ListsPage() -> impl IntoView {
view! { <RequireUser render=|user| view! { <ListsView user /> } /> }
}
#[component]
fn ListsView(user: User) -> impl IntoView {
let ctx = Ctx { let ctx = Ctx {
refresh: RwSignal::new(0), refresh: RwSignal::new(0),
error: RwSignal::new(None), error: RwSignal::new(None),
optimistic: RwSignal::new(HashMap::new()), optimistic: RwSignal::new(HashMap::new()),
item_editor: RwSignal::new(None), item_editor: RwSignal::new(None),
list_editor: RwSignal::new(None), list_editor: RwSignal::new(None),
account_open: RwSignal::new(false),
user_id: user.id,
auth: expect_context::<Auth>(),
}; };
provide_context(ctx); provide_context(ctx);
@@ -157,12 +182,13 @@ fn ListsPage() -> impl IntoView {
<h1 class="font-display text-5xl leading-[0.9] font-extrabold tracking-tight"> <h1 class="font-display text-5xl leading-[0.9] font-extrabold tracking-tight">
"mes"<br />"listes" "mes"<br />"listes"
</h1> </h1>
<div <button
class="grid size-14 shrink-0 place-items-center rounded-2xl bg-ink font-display text-lg font-bold text-lime" class="grid size-14 shrink-0 place-items-center rounded-2xl bg-ink font-display text-lg font-bold text-lime"
aria-label="Profil" aria-label="Mon compte"
on:click=move |_| ctx.account_open.set(true)
> >
"CL" {user.initials()}
</div> </button>
</header> </header>
<ErrorBanner /> <ErrorBanner />
@@ -192,6 +218,7 @@ fn ListsPage() -> impl IntoView {
<ItemSheet list_id=active_id /> <ItemSheet list_id=active_id />
<ListSheet /> <ListSheet />
<AccountSheet user />
} }
} }
@@ -272,6 +299,14 @@ fn ListsContent(
<h2 class="mt-1 font-display text-[1.7rem] leading-tight font-bold tracking-tight"> <h2 class="mt-1 font-display text-[1.7rem] leading-tight font-bold tracking-tight">
{list.name.clone()} {list.name.clone()}
</h2> </h2>
{(!list.is_owner)
.then(|| {
view! {
<p class="mt-1 font-medium text-ink/60">
{format!("Partagée par {}", list.owner_name)}
</p>
}
})}
<p class="mt-1 text-lg text-ink/70">{move || remaining_text(remaining.get(), total())}</p> <p class="mt-1 text-lg text-ink/70">{move || remaining_text(remaining.get(), total())}</p>
<div class="mt-5 grid grid-cols-3 gap-3"> <div class="mt-5 grid grid-cols-3 gap-3">
+115 -2
View File
@@ -4,6 +4,7 @@ use leptos_router::hooks::use_navigate;
use super::Ctx; use super::Ctx;
use super::icons::{IconSvg, icon_label}; use super::icons::{IconSvg, icon_label};
use crate::api::get_members;
use crate::model::{Category, Icon, Item, ItemInput, ListColor, Quantity, ShoppingList, Unit}; use crate::model::{Category, Icon, Item, ItemInput, ListColor, Quantity, ShoppingList, Unit};
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
@@ -20,7 +21,7 @@ pub enum ListEditor {
/// Bottom sheet with a backdrop; `on_close` runs on backdrop tap or Escape. /// Bottom sheet with a backdrop; `on_close` runs on backdrop tap or Escape.
#[component] #[component]
fn Sheet(title: String, on_close: impl Fn() + Copy + Send + Sync + 'static, children: Children) -> impl IntoView { pub fn Sheet(title: String, on_close: impl Fn() + Copy + Send + Sync + 'static, children: Children) -> impl IntoView {
let handle = window_event_listener(ev::keydown, move |ev| { let handle = window_event_listener(ev::keydown, move |ev| {
if ev.key() == "Escape" { if ev.key() == "Escape" {
on_close(); on_close();
@@ -249,7 +250,12 @@ fn parse_amount(text: &str) -> Option<f64> {
#[component] #[component]
pub fn ListSheet() -> impl IntoView { pub fn ListSheet() -> impl IntoView {
let ctx = expect_context::<Ctx>(); let ctx = expect_context::<Ctx>();
move || ctx.list_editor.get().map(|editor| view! { <ListForm editor /> }) move || {
ctx.list_editor.get().map(|editor| match editor {
ListEditor::Edit(list) if !list.is_owner => view! { <SharedListInfo list /> }.into_any(),
editor => view! { <ListForm editor /> }.into_any(),
})
}
} }
#[component] #[component]
@@ -364,6 +370,113 @@ fn ListForm(editor: ListEditor) -> impl IntoView {
</button> </button>
</div> </div>
</form> </form>
{list_id.map(|list_id| view! { <SharePanel list_id /> })}
</Sheet>
}
}
/// Owner view: who the list is shared with, and share it by email.
#[component]
fn SharePanel(list_id: i64) -> impl IntoView {
let ctx = expect_context::<Ctx>();
let version = RwSignal::new(0);
let members = Resource::new(move || version.get(), move |_| get_members(list_id));
let email = RwSignal::new(String::new());
let bump = move || version.update(|v| *v += 1);
let share = move |ev: ev::SubmitEvent| {
ev.prevent_default();
ctx.mutate(crate::api::share_list(list_id, email.get()), move |_| {
email.set(String::new());
bump();
});
};
view! {
<section class="mt-6 border-t-2 border-dashed border-ink/15 pt-5">
<h3 class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">"Partagée avec"</h3>
<Transition fallback=|| view! { <p class="mt-2 text-ink/50">"…"</p> }>
{move || Suspend::new(async move {
let members = members.await.unwrap_or_default();
if members.is_empty() {
return view! { <p class="mt-2 text-ink/60">"Personne pour l'instant."</p> }.into_any();
}
view! {
<ul class="mt-2 flex flex-col gap-2">
{members
.into_iter()
.map(|member| {
let user_id = member.user_id;
view! {
<li class="flex items-center justify-between gap-3 rounded-xl bg-mist px-3 py-2">
<div class="min-w-0">
<p class="truncate font-semibold">{member.name}</p>
<p class="truncate text-sm text-ink/60">{member.email}</p>
</div>
<button
type="button"
class="shrink-0 rounded-lg px-2 py-1 text-sm font-semibold underline"
on:click=move |_| {
ctx.mutate(crate::api::remove_member(list_id, user_id), move |_| bump())
}
>
"Retirer"
</button>
</li>
}
})
.collect_view()}
</ul>
}
.into_any()
})}
</Transition>
<form class="mt-3 flex gap-2" on:submit=share>
<input
class="field min-w-0 flex-1"
type="email"
required
placeholder="email@exemple.fr"
aria-label="Email de la personne"
bind:value=email
/>
<button type="submit" class="shrink-0 rounded-2xl border-2 border-ink bg-lime px-4 font-semibold">
"Partager"
</button>
</form>
</section>
}
}
/// Member view of a list someone shared: who owns it, and leave it.
#[component]
fn SharedListInfo(list: ShoppingList) -> impl IntoView {
let ctx = expect_context::<Ctx>();
let navigate = use_navigate();
let close = move || ctx.list_editor.set(None);
let list_id = list.id;
let leave = move |_| {
let confirmed = window().confirm_with_message("Quitter cette liste ?").unwrap_or(false);
if confirmed {
let navigate = navigate.clone();
ctx.mutate(crate::api::remove_member(list_id, ctx.user_id), move |_| {
close();
navigate("/", Default::default());
});
}
};
view! {
<Sheet title=list.name.clone() on_close=close>
<p class="mt-1 text-ink/70">{format!("Liste de {}, partagée avec toi.", list.owner_name)}</p>
<button
type="button"
class="mt-6 w-full rounded-2xl border-2 border-ink px-4 py-3 font-semibold"
on:click=leave
>
"Quitter la liste"
</button>
</Sheet> </Sheet>
} }
} }
+98
View File
@@ -0,0 +1,98 @@
//! Password hashing and cookie sessions (server only).
use std::sync::OnceLock;
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
use argon2::Argon2;
use axum::http::{HeaderValue, header, request::Parts};
use leptos::prelude::*;
use leptos_axum::ResponseOptions;
use rand_core::{OsRng, RngCore};
use sha2::{Digest, Sha256};
use sqlx::SqlitePool;
use crate::model::User;
const COOKIE: &str = "lisette_session";
const SESSION_DAYS: i64 = 30;
pub fn hash_password(password: &str) -> Result<String, argon2::password_hash::Error> {
let salt = SaltString::generate(&mut OsRng);
Ok(Argon2::default().hash_password(password.as_bytes(), &salt)?.to_string())
}
pub fn verify_password(password: &str, hash: &str) -> bool {
PasswordHash::new(hash)
.is_ok_and(|parsed| Argon2::default().verify_password(password.as_bytes(), &parsed).is_ok())
}
/// Hash checked when the email is unknown, so both cases take as long.
pub fn dummy_hash() -> &'static str {
static HASH: OnceLock<String> = OnceLock::new();
HASH.get_or_init(|| hash_password("not a real password").expect("argon2 hashing"))
}
fn hash_token(token: &str) -> String {
hex::encode(Sha256::digest(token.as_bytes()))
}
fn session_token() -> Option<String> {
let parts = use_context::<Parts>()?;
parts
.headers
.get_all(header::COOKIE)
.iter()
.filter_map(|value| value.to_str().ok())
.flat_map(|value| value.split(';'))
.find_map(|pair| pair.trim().strip_prefix(COOKIE)?.strip_prefix('=').map(str::to_owned))
}
fn set_cookie(value: &str, max_age: i64) {
let secure = if std::env::var("LEPTOS_ENV").is_ok_and(|env| env.eq_ignore_ascii_case("prod")) {
"; Secure"
} else {
""
};
let cookie = format!("{COOKIE}={value}; Path=/; HttpOnly; SameSite=Lax; Max-Age={max_age}{secure}");
if let (Some(response), Ok(header)) = (use_context::<ResponseOptions>(), HeaderValue::from_str(&cookie)) {
response.append_header(header::SET_COOKIE, header);
}
}
/// Opens a session for the user and sets the cookie.
pub async fn start_session(pool: &SqlitePool, user_id: i64) -> Result<(), sqlx::Error> {
let mut bytes = [0u8; 32];
OsRng.fill_bytes(&mut bytes);
let token = hex::encode(bytes);
crate::db::create_session(pool, &hash_token(&token), user_id, SESSION_DAYS).await?;
set_cookie(&token, SESSION_DAYS * 24 * 3600);
Ok(())
}
pub async fn end_session(pool: &SqlitePool) -> Result<(), sqlx::Error> {
if let Some(token) = session_token() {
crate::db::delete_session(pool, &hash_token(&token)).await?;
}
set_cookie("", 0);
Ok(())
}
pub async fn current_user(pool: &SqlitePool) -> Result<Option<User>, sqlx::Error> {
match session_token() {
Some(token) => crate::db::user_by_session(pool, &hash_token(&token)).await,
None => Ok(None),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn password_roundtrip() {
let hash = hash_password("correct horse").unwrap();
assert!(verify_password("correct horse", &hash));
assert!(!verify_password("wrong", &hash));
assert!(!verify_password("correct horse", "garbage"));
}
}
+269 -25
View File
@@ -1,8 +1,10 @@
use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions, SqliteRow}; use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions, SqliteRow};
use sqlx::Row; use sqlx::{Row, SqliteConnection};
use std::str::FromStr; use std::str::FromStr;
use crate::model::{Category, Icon, Item, ItemInput, ListColor, Quantity, ShoppingList, Suggestion, Unit}; use crate::model::{
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> {
let options = SqliteConnectOptions::from_str(url)? let options = SqliteConnectOptions::from_str(url)?
@@ -28,6 +30,8 @@ fn list_from_row(row: &SqliteRow) -> Result<ShoppingList, sqlx::Error> {
name: row.try_get("name")?, name: row.try_get("name")?,
color: decode(ListColor::parse(row.try_get("color")?), "color")?, color: decode(ListColor::parse(row.try_get("color")?), "color")?,
created_at: row.try_get("created_at")?, created_at: row.try_get("created_at")?,
is_owner: row.try_get("is_owner")?,
owner_name: row.try_get("owner_name")?,
}) })
} }
@@ -52,8 +56,139 @@ fn item_from_row(row: &SqliteRow) -> Result<Item, sqlx::Error> {
}) })
} }
pub async fn lists(pool: &SqlitePool) -> Result<Vec<ShoppingList>, sqlx::Error> { fn user_from_row(row: &SqliteRow) -> Result<User, sqlx::Error> {
sqlx::query("SELECT id, name, color, created_at FROM lists ORDER BY id") Ok(User {
id: row.try_get("id")?,
name: row.try_get("name")?,
email: row.try_get("email")?,
})
}
// --- Users & sessions -------------------------------------------------------
/// Products offered as suggestions to every new account.
const STARTER_CATALOG: &[(&str, Icon, Category)] = &[
("Beurre", Icon::Cheese, Category::Frais),
("Œufs", Icon::Egg, Category::Frais),
("Citrons", Icon::Lemon, Category::FruitsLegumes),
("Pain complet", Icon::Bread, Category::Boulangerie),
("Bananes", Icon::Banana, Category::FruitsLegumes),
("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.
pub async fn register(pool: &SqlitePool, email: &str, name: &str, password_hash: &str) -> Result<i64, sqlx::Error> {
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")?;
// Lists created before accounts existed go to the first user.
let claimed = sqlx::query("UPDATE lists SET owner_id = ? WHERE owner_id IS NULL")
.bind(user_id)
.execute(&mut *tx)
.await?
.rows_affected();
if claimed == 0 {
insert_list(&mut tx, user_id, "Courses de la semaine", ListColor::Lime).await?;
}
for (product, icon, category) in STARTER_CATALOG {
sqlx::query("INSERT INTO catalog (user_id, name, icon, category, use_count) VALUES (?, ?, ?, ?, 1)")
.bind(user_id)
.bind(product)
.bind(icon.as_str())
.bind(category.as_str())
.execute(&mut *tx)
.await?;
}
tx.commit().await?;
Ok(user_id)
}
/// The user and their password hash.
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 = ?")
.bind(email)
.fetch_optional(pool)
.await?
.map(|row| Ok((user_from_row(&row)?, row.try_get("password_hash")?)))
.transpose()
}
pub async fn create_session(pool: &SqlitePool, token_hash: &str, user_id: i64, days: i64) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM sessions WHERE expires_at <= datetime('now')")
.execute(pool)
.await?;
sqlx::query("INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (?, ?, datetime('now', ?))")
.bind(token_hash)
.bind(user_id)
.bind(format!("+{days} days"))
.execute(pool)
.await?;
Ok(())
}
pub async fn user_by_session(pool: &SqlitePool, token_hash: &str) -> Result<Option<User>, sqlx::Error> {
sqlx::query(
"SELECT u.id, u.name, u.email 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)
.fetch_optional(pool)
.await?
.as_ref()
.map(user_from_row)
.transpose()
}
pub async fn delete_session(pool: &SqlitePool, token_hash: &str) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM sessions WHERE token_hash = ?")
.bind(token_hash)
.execute(pool)
.await?;
Ok(())
}
// --- Lists & sharing --------------------------------------------------------
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Role {
Owner,
Member,
}
pub async fn list_role(pool: &SqlitePool, user_id: i64, list_id: i64) -> Result<Option<Role>, sqlx::Error> {
let row = sqlx::query(
"SELECT owner_id = ?1 AS is_owner FROM lists l
WHERE l.id = ?2 AND (
l.owner_id = ?1
OR EXISTS (SELECT 1 FROM list_members m WHERE m.list_id = l.id AND m.user_id = ?1)
)",
)
.bind(user_id)
.bind(list_id)
.fetch_optional(pool)
.await?;
row.map(|row| Ok(if row.try_get("is_owner")? { Role::Owner } else { Role::Member }))
.transpose()
}
/// Lists owned by or shared with the user.
pub async fn lists(pool: &SqlitePool, user_id: i64) -> Result<Vec<ShoppingList>, sqlx::Error> {
sqlx::query(
"SELECT l.id, l.name, l.color, l.created_at, l.owner_id = ?1 AS is_owner, u.name AS owner_name
FROM lists l JOIN users u ON u.id = l.owner_id
WHERE l.owner_id = ?1
OR EXISTS (SELECT 1 FROM list_members m WHERE m.list_id = l.id AND m.user_id = ?1)
ORDER BY l.id",
)
.bind(user_id)
.fetch_all(pool) .fetch_all(pool)
.await? .await?
.iter() .iter()
@@ -61,13 +196,18 @@ pub async fn lists(pool: &SqlitePool) -> Result<Vec<ShoppingList>, sqlx::Error>
.collect() .collect()
} }
pub async fn create_list(pool: &SqlitePool, name: &str, color: ListColor) -> Result<i64, sqlx::Error> { async fn insert_list(conn: &mut SqliteConnection, owner_id: i64, name: &str, color: ListColor) -> Result<i64, sqlx::Error> {
let row = sqlx::query("INSERT INTO lists (name, color) VALUES (?, ?) RETURNING id") sqlx::query("INSERT INTO lists (name, color, owner_id) VALUES (?, ?, ?) RETURNING id")
.bind(name) .bind(name)
.bind(color.as_str()) .bind(color.as_str())
.fetch_one(pool) .bind(owner_id)
.await?; .fetch_one(conn)
row.try_get("id") .await?
.try_get("id")
}
pub async fn create_list(pool: &SqlitePool, owner_id: i64, name: &str, color: ListColor) -> Result<i64, sqlx::Error> {
insert_list(&mut *pool.acquire().await?, owner_id, name, color).await
} }
pub async fn rename_list(pool: &SqlitePool, id: i64, name: &str) -> Result<(), sqlx::Error> { pub async fn rename_list(pool: &SqlitePool, id: i64, name: &str) -> Result<(), sqlx::Error> {
@@ -84,6 +224,42 @@ pub async fn delete_list(pool: &SqlitePool, id: i64) -> Result<(), sqlx::Error>
Ok(()) Ok(())
} }
pub async fn members(pool: &SqlitePool, list_id: i64) -> Result<Vec<Member>, sqlx::Error> {
sqlx::query(
"SELECT u.id, u.name, u.email FROM list_members m JOIN users u ON u.id = m.user_id
WHERE m.list_id = ? ORDER BY u.name",
)
.bind(list_id)
.fetch_all(pool)
.await?
.iter()
.map(|row| {
let user = user_from_row(row)?;
Ok(Member { user_id: user.id, name: user.name, email: user.email })
})
.collect()
}
pub async fn add_member(pool: &SqlitePool, list_id: i64, user_id: i64) -> Result<(), sqlx::Error> {
sqlx::query("INSERT OR IGNORE INTO list_members (list_id, user_id) VALUES (?, ?)")
.bind(list_id)
.bind(user_id)
.execute(pool)
.await?;
Ok(())
}
pub async fn remove_member(pool: &SqlitePool, list_id: i64, user_id: i64) -> Result<(), sqlx::Error> {
sqlx::query("DELETE FROM list_members WHERE list_id = ? AND user_id = ?")
.bind(list_id)
.bind(user_id)
.execute(pool)
.await?;
Ok(())
}
// --- Items ------------------------------------------------------------------
pub async fn items(pool: &SqlitePool, list_id: i64) -> Result<Vec<Item>, sqlx::Error> { pub async fn items(pool: &SqlitePool, list_id: i64) -> Result<Vec<Item>, sqlx::Error> {
sqlx::query( sqlx::query(
"SELECT id, list_id, name, amount, unit, icon, category, checked "SELECT id, list_id, name, amount, unit, icon, category, checked
@@ -97,15 +273,25 @@ pub async fn items(pool: &SqlitePool, list_id: i64) -> Result<Vec<Item>, sqlx::E
.collect() .collect()
} }
/// Remembers the product in the catalog so it can be suggested later. pub async fn item_list_id(pool: &SqlitePool, item_id: i64) -> Result<Option<i64>, sqlx::Error> {
async fn record_in_catalog(pool: &SqlitePool, input: &ItemInput) -> Result<(), sqlx::Error> { sqlx::query("SELECT list_id FROM items WHERE id = ?")
.bind(item_id)
.fetch_optional(pool)
.await?
.map(|row| row.try_get("list_id"))
.transpose()
}
/// Remembers the product in the user's catalog so it can be suggested later.
async fn record_in_catalog(pool: &SqlitePool, user_id: i64, input: &ItemInput) -> Result<(), sqlx::Error> {
sqlx::query( sqlx::query(
"INSERT INTO catalog (name, icon, category, use_count) VALUES (?, ?, ?, 1) "INSERT INTO catalog (user_id, name, icon, category, use_count) VALUES (?, ?, ?, ?, 1)
ON CONFLICT(name) DO UPDATE SET ON CONFLICT(user_id, name) DO UPDATE SET
icon = excluded.icon, icon = excluded.icon,
category = excluded.category, category = excluded.category,
use_count = use_count + 1", use_count = use_count + 1",
) )
.bind(user_id)
.bind(&input.name) .bind(&input.name)
.bind(input.icon.as_str()) .bind(input.icon.as_str())
.bind(input.category.as_str()) .bind(input.category.as_str())
@@ -114,7 +300,7 @@ async fn record_in_catalog(pool: &SqlitePool, input: &ItemInput) -> Result<(), s
Ok(()) Ok(())
} }
pub async fn add_item(pool: &SqlitePool, list_id: i64, input: &ItemInput) -> Result<i64, sqlx::Error> { pub async fn add_item(pool: &SqlitePool, user_id: i64, list_id: i64, input: &ItemInput) -> Result<i64, sqlx::Error> {
let row = sqlx::query( let row = sqlx::query(
"INSERT INTO items (list_id, name, amount, unit, icon, category) "INSERT INTO items (list_id, name, amount, unit, icon, category)
VALUES (?, ?, ?, ?, ?, ?) RETURNING id", VALUES (?, ?, ?, ?, ?, ?) RETURNING id",
@@ -127,7 +313,7 @@ pub async fn add_item(pool: &SqlitePool, list_id: i64, input: &ItemInput) -> Res
.bind(input.category.as_str()) .bind(input.category.as_str())
.fetch_one(pool) .fetch_one(pool)
.await?; .await?;
record_in_catalog(pool, input).await?; record_in_catalog(pool, user_id, input).await?;
row.try_get("id") row.try_get("id")
} }
@@ -160,16 +346,17 @@ pub async fn set_checked(pool: &SqlitePool, id: i64, checked: bool) -> Result<()
Ok(()) Ok(())
} }
/// Most used catalog products not already on the list. /// The user's most used products not already on the list.
pub async fn suggestions(pool: &SqlitePool, list_id: i64, limit: i64) -> Result<Vec<Suggestion>, sqlx::Error> { pub async fn suggestions(pool: &SqlitePool, user_id: i64, list_id: i64, limit: i64) -> Result<Vec<Suggestion>, sqlx::Error> {
sqlx::query( sqlx::query(
"SELECT name, icon, category FROM catalog c "SELECT name, icon, category FROM catalog c
WHERE NOT EXISTS ( WHERE c.user_id = ? AND NOT EXISTS (
SELECT 1 FROM items i WHERE i.list_id = ? AND i.name = c.name COLLATE NOCASE SELECT 1 FROM items i WHERE i.list_id = ? AND i.name = c.name COLLATE NOCASE
) )
ORDER BY use_count DESC, name ORDER BY use_count DESC, name
LIMIT ?", LIMIT ?",
) )
.bind(user_id)
.bind(list_id) .bind(list_id)
.bind(limit) .bind(limit)
.fetch_all(pool) .fetch_all(pool)
@@ -193,6 +380,10 @@ mod tests {
connect("sqlite::memory:").await.unwrap() connect("sqlite::memory:").await.unwrap()
} }
async fn user(pool: &SqlitePool, email: &str) -> i64 {
register(pool, email, "Test", "hash").await.unwrap()
}
fn input(name: &str) -> ItemInput { fn input(name: &str) -> ItemInput {
ItemInput { ItemInput {
name: name.into(), name: name.into(),
@@ -202,12 +393,63 @@ mod tests {
} }
} }
#[tokio::test]
async fn first_user_claims_seed_list_others_get_their_own() {
let pool = pool().await;
let first = user(&pool, "a@x.fr").await;
let second = user(&pool, "b@x.fr").await;
let a = lists(&pool, first).await.unwrap();
let b = lists(&pool, second).await.unwrap();
assert_eq!(a.len(), 1);
assert_eq!(b.len(), 1);
assert_ne!(a[0].id, b[0].id);
assert_eq!(list_role(&pool, second, a[0].id).await.unwrap(), None);
}
#[tokio::test]
async fn duplicate_email_is_rejected_case_insensitively() {
let pool = pool().await;
user(&pool, "a@x.fr").await;
assert!(register(&pool, "A@X.fr", "Autre", "hash").await.is_err());
}
#[tokio::test]
async fn sessions_resolve_to_user() {
let pool = pool().await;
let id = user(&pool, "a@x.fr").await;
create_session(&pool, "tok", id, 30).await.unwrap();
assert_eq!(user_by_session(&pool, "tok").await.unwrap().unwrap().id, id);
delete_session(&pool, "tok").await.unwrap();
assert!(user_by_session(&pool, "tok").await.unwrap().is_none());
}
#[tokio::test]
async fn sharing_grants_member_access() {
let pool = pool().await;
let owner = user(&pool, "a@x.fr").await;
let friend = user(&pool, "b@x.fr").await;
let list = create_list(&pool, owner, "Apéro", ListColor::Pink).await.unwrap();
add_member(&pool, list, friend).await.unwrap();
assert_eq!(list_role(&pool, friend, list).await.unwrap(), Some(Role::Member));
assert_eq!(list_role(&pool, owner, list).await.unwrap(), Some(Role::Owner));
let shared = lists(&pool, friend).await.unwrap();
assert!(shared.iter().any(|l| l.id == list && !l.is_owner && l.owner_name == "Test"));
assert_eq!(members(&pool, list).await.unwrap().len(), 1);
remove_member(&pool, list, friend).await.unwrap();
assert_eq!(list_role(&pool, friend, list).await.unwrap(), None);
}
#[tokio::test] #[tokio::test]
async fn item_crud_and_toggle() { async fn item_crud_and_toggle() {
let pool = pool().await; let pool = pool().await;
let list = lists(&pool).await.unwrap()[0].id; let me = user(&pool, "a@x.fr").await;
let list = lists(&pool, me).await.unwrap()[0].id;
let id = add_item(&pool, list, &input("Avocats")).await.unwrap(); let id = add_item(&pool, me, list, &input("Avocats")).await.unwrap();
assert_eq!(item_list_id(&pool, id).await.unwrap(), Some(list));
let mut edited = input("Avocats"); let mut edited = input("Avocats");
edited.quantity = Some(Quantity { amount: 4.0, unit: Unit::Piece }); edited.quantity = Some(Quantity { amount: 4.0, unit: Unit::Piece });
update_item(&pool, id, &edited).await.unwrap(); update_item(&pool, id, &edited).await.unwrap();
@@ -225,10 +467,11 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn suggestions_skip_items_on_list() { async fn suggestions_skip_items_on_list() {
let pool = pool().await; let pool = pool().await;
let list = lists(&pool).await.unwrap()[0].id; let me = user(&pool, "a@x.fr").await;
add_item(&pool, list, &input("beurre")).await.unwrap(); let list = lists(&pool, me).await.unwrap()[0].id;
add_item(&pool, me, list, &input("beurre")).await.unwrap();
let names: Vec<_> = suggestions(&pool, list, 3) let names: Vec<_> = suggestions(&pool, me, list, 3)
.await .await
.unwrap() .unwrap()
.into_iter() .into_iter()
@@ -241,8 +484,9 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn deleting_list_cascades() { async fn deleting_list_cascades() {
let pool = pool().await; let pool = pool().await;
let list = create_list(&pool, "Apéro", ListColor::Pink).await.unwrap(); let me = user(&pool, "a@x.fr").await;
add_item(&pool, list, &input("Chips")).await.unwrap(); let list = create_list(&pool, me, "Apéro", ListColor::Pink).await.unwrap();
add_item(&pool, me, list, &input("Chips")).await.unwrap();
delete_list(&pool, list).await.unwrap(); delete_list(&pool, list).await.unwrap();
assert!(items(&pool, list).await.unwrap().is_empty()); assert!(items(&pool, list).await.unwrap().is_empty());
} }
+2
View File
@@ -2,6 +2,8 @@ pub mod api;
pub mod app; pub mod app;
pub mod model; pub mod model;
#[cfg(feature = "ssr")]
pub mod auth;
#[cfg(feature = "ssr")] #[cfg(feature = "ssr")]
pub mod db; pub mod db;
+7 -3
View File
@@ -30,11 +30,15 @@ async fn main() {
move || shell(leptos_options.clone()) move || shell(leptos_options.clone())
}, },
) )
.fallback(leptos_axum::file_and_error_handler(shell)) .fallback(leptos_axum::file_and_error_handler_with_context(
{
let pool = pool.clone();
move || provide_context(pool.clone())
},
shell,
))
.with_state(leptos_options); .with_state(leptos_options);
// Server functions are registered by `leptos_routes_with_context`; they get the pool
// from the same context closure.
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap(); let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
leptos::logging::log!("listening on http://{addr}"); leptos::logging::log!("listening on http://{addr}");
axum::serve(listener, app.into_make_service()).await.unwrap(); axum::serve(listener, app.into_make_service()).await.unwrap();
+39
View File
@@ -28,6 +28,37 @@ pub struct ShoppingList {
pub name: String, pub name: String,
pub color: ListColor, pub color: ListColor,
pub created_at: String, pub created_at: String,
/// False when the list was shared with the current user.
pub is_owner: bool,
pub owner_name: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct User {
pub id: i64,
pub name: String,
pub email: String,
}
impl User {
/// "Camille Lefèvre" → "CL", "romain" → "RO".
pub fn initials(&self) -> String {
let words: Vec<&str> = self.name.split_whitespace().collect();
let initials: String = match words.as_slice() {
[first, second, ..] => first.chars().take(1).chain(second.chars().take(1)).collect(),
[single] => single.chars().take(2).collect(),
[] => String::new(),
};
initials.to_uppercase()
}
}
/// Someone a list is shared with.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Member {
pub user_id: i64,
pub name: String,
pub email: String,
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -231,6 +262,14 @@ mod tests {
assert_eq!(q(1.5, Unit::Litre), "1,5 L"); assert_eq!(q(1.5, Unit::Litre), "1,5 L");
} }
#[test]
fn initials() {
let user = |name: &str| User { id: 1, name: name.into(), email: String::new() };
assert_eq!(user("Camille Lefèvre").initials(), "CL");
assert_eq!(user("romain").initials(), "RO");
assert_eq!(user("élise").initials(), "ÉL");
}
#[test] #[test]
fn text_roundtrip() { fn text_roundtrip() {
for icon in Icon::ALL { for icon in Icon::ALL {