diff --git a/Cargo.lock b/Cargo.lock index a08e828..21a5202 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -35,6 +35,18 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" 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]] name = "async-lock" version = "3.4.2" @@ -196,6 +208,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -1371,13 +1392,17 @@ dependencies = [ name = "lisette" version = "0.1.0" dependencies = [ + "argon2", "axum", "console_error_panic_hook", + "hex", "leptos", "leptos_axum", "leptos_meta", "leptos_router", + "rand_core 0.6.4", "serde", + "sha2", "sqlx", "tokio", "wasm-bindgen", @@ -1601,6 +1626,17 @@ dependencies = [ "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]] name = "paste" version = "1.0.15" diff --git a/Cargo.toml b/Cargo.toml index cf86b11..cc2979e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,10 @@ leptos_axum = { version = "0.8", optional = true } axum = { version = "0.8", 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 } +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"] } wasm-bindgen = { version = "=0.2.128", optional = true } console_error_panic_hook = { version = "0.1", optional = true } @@ -25,6 +29,10 @@ ssr = [ "dep:tokio", "dep:sqlx", "dep:leptos_axum", + "dep:argon2", + "dep:rand_core", + "dep:sha2", + "dep:hex", "leptos/ssr", "leptos_meta/ssr", "leptos_router/ssr", diff --git a/migrations/0002_auth.sql b/migrations/0002_auth.sql new file mode 100644 index 0000000..66d2203 --- /dev/null +++ b/migrations/0002_auth.sql @@ -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) +); diff --git a/src/api.rs b/src/api.rs index 03cd176..1bee68f 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1,13 +1,18 @@ use leptos::prelude::*; 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")] mod server { use leptos::prelude::*; use sqlx::SqlitePool; + use crate::db::Role; + use crate::model::User; + pub fn pool() -> Result { use_context::().ok_or_else(|| ServerFnError::new("database pool missing")) } @@ -17,75 +22,257 @@ mod server { ServerFnError::new("Erreur de base de données") } - pub fn clean_name(name: &str) -> Result { + pub async fn require_user(pool: &SqlitePool) -> Result { + 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 { + 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 { let name = name.trim(); - if name.is_empty() || name.chars().count() > 60 { - return Err(ServerFnError::new("Le nom doit faire entre 1 et 60 caractères")); + if name.is_empty() || name.chars().count() > max { + return Err(ServerFnError::new(format!("Le nom doit faire entre 1 et {max} caractères."))); } Ok(name.to_owned()) } + + pub fn clean_email(email: &str) -> Result { + 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(f: impl FnOnce() -> T + Send + 'static) -> Result { + tokio::task::spawn_blocking(f) + .await + .map_err(|_| ServerFnError::new("Erreur interne")) + } } +// --- Account ---------------------------------------------------------------- + +#[server] +pub async fn get_me() -> Result, 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] pub async fn get_lists() -> Result, ServerFnError> { 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] pub async fn create_list(name: String, color: ListColor) -> Result { use server::*; - let name = clean_name(&name)?; - crate::db::create_list(&pool()?, &name, color).await.map_err(db_err) + let pool = pool()?; + 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] pub async fn rename_list(id: i64, name: String) -> Result<(), ServerFnError> { use server::*; - let name = clean_name(&name)?; - crate::db::rename_list(&pool()?, id, &name).await.map_err(db_err) + let pool = pool()?; + 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] pub async fn delete_list(id: i64) -> Result<(), ServerFnError> { 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, 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] pub async fn get_items(list_id: i64) -> Result, ServerFnError> { 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)] pub async fn add_item(list_id: i64, input: ItemInput) -> Result { use server::*; - let input = ItemInput { name: clean_name(&input.name)?, ..input }; - crate::db::add_item(&pool()?, list_id, &input).await.map_err(db_err) + let pool = pool()?; + 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)] pub async fn update_item(id: i64, input: ItemInput) -> Result<(), ServerFnError> { use server::*; - let input = ItemInput { name: clean_name(&input.name)?, ..input }; - crate::db::update_item(&pool()?, id, &input).await.map_err(db_err) + let pool = pool()?; + 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] pub async fn delete_item(id: i64) -> Result<(), ServerFnError> { 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] pub async fn set_checked(id: i64, checked: bool) -> Result<(), ServerFnError> { 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] pub async fn get_suggestions(list_id: i64) -> Result, ServerFnError> { 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) } diff --git a/src/app/account.rs b/src/app/account.rs new file mode 100644 index 0000000..4815a38 --- /dev/null +++ b/src/app/account.rs @@ -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, ServerFnError>>, + pub login: ServerAction, + pub register: ServerAction, + pub logout: ServerAction, +} + +impl Auth { + pub fn provide() -> Self { + let login = ServerAction::::new(); + let register = ServerAction::::new(); + let logout = ServerAction::::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(render: F) -> impl IntoView +where + F: Fn(User) -> V + Send + Sync + 'static, + V: IntoView + 'static, +{ + let auth = expect_context::(); + let render = StoredValue::new(render); + view! { + + {move || Suspend::new(async move { + match auth.me.await { + Ok(Some(user)) => render.with_value(|render| render(user)).into_any(), + _ => view! { }.into_any(), + } + })} + + } +} + +/// Sends a signed-in user away from the login and sign-up pages. +#[component] +fn RedirectIfSignedIn() -> impl IntoView { + let auth = expect_context::(); + view! { + + {move || Suspend::new(async move { + matches!(auth.me.await, Ok(Some(_))).then(|| view! { }) + })} + + } +} + +#[component] +fn AuthLayout(title: &'static str, children: Children) -> impl IntoView { + view! { + +
+

+ "mes"
"listes" +

+
+

"Lisette · Courses"

+

{title}

+ {children()} +
+
+ } +} + +#[component] +fn FormError(#[prop(into)] error: Signal>) -> impl IntoView { + move || { + error.get().map(|msg| { + view! { + + } + }) + } +} + +#[component] +pub fn LoginPage() -> impl IntoView { + let auth = expect_context::(); + view! { + + + + + + + + + + + +

+ "Pas encore de compte ? " + + "Créer un compte" + +

+
+ } +} + +#[component] +pub fn RegisterPage() -> impl IntoView { + let auth = expect_context::(); + view! { + + + + + + + + + + + + + + +

+ "Déjà inscrit·e ? " + + "Se connecter" + +

+
+ } +} + +#[component] +fn Field(label: &'static str, children: Children) -> impl IntoView { + view! { + + } +} + +#[component] +fn SubmitButton(#[prop(into)] pending: Signal, label: &'static str) -> impl IntoView { + view! { + + } +} + +/// Avatar sheet: who is signed in, and sign out. +#[component] +pub fn AccountSheet(user: User) -> impl IntoView { + let auth = expect_context::(); + let ctx = expect_context::(); + let close = move || ctx.account_open.set(false); + let user = StoredValue::new(user); + + view! { + + +

{user.with_value(|u| u.email.clone())}

+ + + +
+
+ } +} diff --git a/src/app/mod.rs b/src/app/mod.rs index 05c97f4..5e5a587 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -1,3 +1,4 @@ +mod account; mod icons; mod sheets; mod tiles; @@ -13,7 +14,8 @@ use leptos_router::hooks::use_params_map; use leptos_router::path; 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 tiles::{BasketTile, ItemTile, SuggestionTile}; @@ -41,6 +43,7 @@ pub fn shell(options: LeptosOptions) -> impl IntoView { #[component] pub fn App() -> impl IntoView { provide_meta_context(); + Auth::provide(); view! { @@ -59,6 +62,8 @@ pub fn App() -> impl IntoView { "Page introuvable."

}> + +
} @@ -74,6 +79,9 @@ pub struct Ctx { optimistic: RwSignal>, item_editor: RwSignal>, list_editor: RwSignal>, + account_open: RwSignal, + user_id: i64, + auth: Auth, } impl Ctx { @@ -89,11 +97,20 @@ impl Ctx { on_ok(value); 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) { let (id, checked) = (item.id, !item.checked); self.optimistic.update(|map| { @@ -104,7 +121,7 @@ impl Ctx { self.optimistic.update(|map| { map.remove(&id); }); - self.error.set(Some(error_message(err))); + self.report(err); } }); } @@ -119,12 +136,20 @@ fn error_message(err: ServerFnError) -> String { #[component] fn ListsPage() -> impl IntoView { + view! { } /> } +} + +#[component] +fn ListsView(user: User) -> impl IntoView { let ctx = Ctx { refresh: RwSignal::new(0), error: RwSignal::new(None), optimistic: RwSignal::new(HashMap::new()), item_editor: RwSignal::new(None), list_editor: RwSignal::new(None), + account_open: RwSignal::new(false), + user_id: user.id, + auth: expect_context::(), }; provide_context(ctx); @@ -157,12 +182,13 @@ fn ListsPage() -> impl IntoView {

"mes"
"listes"

-
- "CL" -
+ {user.initials()} + @@ -192,6 +218,7 @@ fn ListsPage() -> impl IntoView { + } } @@ -272,6 +299,14 @@ fn ListsContent(

{list.name.clone()}

+ {(!list.is_owner) + .then(|| { + view! { +

+ {format!("Partagée par {}", list.owner_name)} +

+ } + })}

{move || remaining_text(remaining.get(), total())}

diff --git a/src/app/sheets.rs b/src/app/sheets.rs index 77c03e6..59e4cf8 100644 --- a/src/app/sheets.rs +++ b/src/app/sheets.rs @@ -4,6 +4,7 @@ use leptos_router::hooks::use_navigate; use super::Ctx; use super::icons::{IconSvg, icon_label}; +use crate::api::get_members; use crate::model::{Category, Icon, Item, ItemInput, ListColor, Quantity, ShoppingList, Unit}; #[derive(Clone, Debug, PartialEq)] @@ -20,7 +21,7 @@ pub enum ListEditor { /// Bottom sheet with a backdrop; `on_close` runs on backdrop tap or Escape. #[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| { if ev.key() == "Escape" { on_close(); @@ -249,7 +250,12 @@ fn parse_amount(text: &str) -> Option { #[component] pub fn ListSheet() -> impl IntoView { let ctx = expect_context::(); - move || ctx.list_editor.get().map(|editor| view! { }) + move || { + ctx.list_editor.get().map(|editor| match editor { + ListEditor::Edit(list) if !list.is_owner => view! { }.into_any(), + editor => view! { }.into_any(), + }) + } } #[component] @@ -364,6 +370,113 @@ fn ListForm(editor: ListEditor) -> impl IntoView {
+ {list_id.map(|list_id| view! { })} + + } +} + +/// 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::(); + 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! { +
+

"Partagée avec"

+ "…"

}> + {move || Suspend::new(async move { + let members = members.await.unwrap_or_default(); + if members.is_empty() { + return view! {

"Personne pour l'instant."

}.into_any(); + } + view! { +
    + {members + .into_iter() + .map(|member| { + let user_id = member.user_id; + view! { +
  • +
    +

    {member.name}

    +

    {member.email}

    +
    + +
  • + } + }) + .collect_view()} +
+ } + .into_any() + })} +
+
+ + +
+
+ } +} + +/// Member view of a list someone shared: who owns it, and leave it. +#[component] +fn SharedListInfo(list: ShoppingList) -> impl IntoView { + let ctx = expect_context::(); + 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! { + +

{format!("Liste de {}, partagée avec toi.", list.owner_name)}

+
} } diff --git a/src/auth.rs b/src/auth.rs new file mode 100644 index 0000000..4b54ac4 --- /dev/null +++ b/src/auth.rs @@ -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 { + 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 = 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 { + let parts = use_context::()?; + 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::(), 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, 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")); + } +} diff --git a/src/db.rs b/src/db.rs index cd11617..cccd155 100644 --- a/src/db.rs +++ b/src/db.rs @@ -1,8 +1,10 @@ use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions, SqliteRow}; -use sqlx::Row; +use sqlx::{Row, SqliteConnection}; 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 { let options = SqliteConnectOptions::from_str(url)? @@ -28,6 +30,8 @@ fn list_from_row(row: &SqliteRow) -> Result { name: row.try_get("name")?, color: decode(ListColor::parse(row.try_get("color")?), "color")?, created_at: row.try_get("created_at")?, + is_owner: row.try_get("is_owner")?, + owner_name: row.try_get("owner_name")?, }) } @@ -52,22 +56,158 @@ fn item_from_row(row: &SqliteRow) -> Result { }) } -pub async fn lists(pool: &SqlitePool) -> Result, sqlx::Error> { - sqlx::query("SELECT id, name, color, created_at FROM lists ORDER BY id") - .fetch_all(pool) - .await? - .iter() - .map(list_from_row) - .collect() +fn user_from_row(row: &SqliteRow) -> Result { + Ok(User { + id: row.try_get("id")?, + name: row.try_get("name")?, + email: row.try_get("email")?, + }) } -pub async fn create_list(pool: &SqlitePool, name: &str, color: ListColor) -> Result { - let row = sqlx::query("INSERT INTO lists (name, color) VALUES (?, ?) RETURNING id") +// --- 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 { + 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, 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, 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, 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, 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) + .await? + .iter() + .map(list_from_row) + .collect() +} + +async fn insert_list(conn: &mut SqliteConnection, owner_id: i64, name: &str, color: ListColor) -> Result { + sqlx::query("INSERT INTO lists (name, color, owner_id) VALUES (?, ?, ?) RETURNING id") .bind(name) .bind(color.as_str()) - .fetch_one(pool) - .await?; - row.try_get("id") + .bind(owner_id) + .fetch_one(conn) + .await? + .try_get("id") +} + +pub async fn create_list(pool: &SqlitePool, owner_id: i64, name: &str, color: ListColor) -> Result { + 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> { @@ -84,6 +224,42 @@ pub async fn delete_list(pool: &SqlitePool, id: i64) -> Result<(), sqlx::Error> Ok(()) } +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 + 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, sqlx::Error> { sqlx::query( "SELECT id, list_id, name, amount, unit, icon, category, checked @@ -97,15 +273,25 @@ pub async fn items(pool: &SqlitePool, list_id: i64) -> Result, sqlx::E .collect() } -/// Remembers the product in the catalog so it can be suggested later. -async fn record_in_catalog(pool: &SqlitePool, input: &ItemInput) -> Result<(), sqlx::Error> { +pub async fn item_list_id(pool: &SqlitePool, item_id: i64) -> 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( - "INSERT INTO catalog (name, icon, category, use_count) VALUES (?, ?, ?, 1) - ON CONFLICT(name) DO UPDATE SET + "INSERT INTO catalog (user_id, name, icon, category, use_count) VALUES (?, ?, ?, ?, 1) + ON CONFLICT(user_id, name) DO UPDATE SET icon = excluded.icon, category = excluded.category, use_count = use_count + 1", ) + .bind(user_id) .bind(&input.name) .bind(input.icon.as_str()) .bind(input.category.as_str()) @@ -114,7 +300,7 @@ async fn record_in_catalog(pool: &SqlitePool, input: &ItemInput) -> Result<(), s Ok(()) } -pub async fn add_item(pool: &SqlitePool, list_id: i64, input: &ItemInput) -> Result { +pub async fn add_item(pool: &SqlitePool, user_id: i64, list_id: i64, input: &ItemInput) -> Result { let row = sqlx::query( "INSERT INTO items (list_id, name, amount, unit, icon, category) 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()) .fetch_one(pool) .await?; - record_in_catalog(pool, input).await?; + record_in_catalog(pool, user_id, input).await?; row.try_get("id") } @@ -160,16 +346,17 @@ pub async fn set_checked(pool: &SqlitePool, id: i64, checked: bool) -> Result<() Ok(()) } -/// Most used catalog products not already on the list. -pub async fn suggestions(pool: &SqlitePool, list_id: i64, limit: i64) -> Result, sqlx::Error> { +/// The user's most used products not already on the list. +pub async fn suggestions(pool: &SqlitePool, user_id: i64, list_id: i64, limit: i64) -> Result, sqlx::Error> { sqlx::query( "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 ) ORDER BY use_count DESC, name LIMIT ?", ) + .bind(user_id) .bind(list_id) .bind(limit) .fetch_all(pool) @@ -193,6 +380,10 @@ mod tests { 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 { ItemInput { 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] async fn item_crud_and_toggle() { 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"); edited.quantity = Some(Quantity { amount: 4.0, unit: Unit::Piece }); update_item(&pool, id, &edited).await.unwrap(); @@ -225,10 +467,11 @@ mod tests { #[tokio::test] async fn suggestions_skip_items_on_list() { let pool = pool().await; - let list = lists(&pool).await.unwrap()[0].id; - add_item(&pool, list, &input("beurre")).await.unwrap(); + let me = user(&pool, "a@x.fr").await; + 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 .unwrap() .into_iter() @@ -241,8 +484,9 @@ mod tests { #[tokio::test] async fn deleting_list_cascades() { let pool = pool().await; - let list = create_list(&pool, "Apéro", ListColor::Pink).await.unwrap(); - add_item(&pool, list, &input("Chips")).await.unwrap(); + let me = user(&pool, "a@x.fr").await; + 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(); assert!(items(&pool, list).await.unwrap().is_empty()); } diff --git a/src/lib.rs b/src/lib.rs index f332f02..222d6c1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,8 @@ pub mod api; pub mod app; pub mod model; +#[cfg(feature = "ssr")] +pub mod auth; #[cfg(feature = "ssr")] pub mod db; diff --git a/src/main.rs b/src/main.rs index 10b7d22..f72d093 100644 --- a/src/main.rs +++ b/src/main.rs @@ -30,11 +30,15 @@ async fn main() { 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); - // 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(); leptos::logging::log!("listening on http://{addr}"); axum::serve(listener, app.into_make_service()).await.unwrap(); diff --git a/src/model.rs b/src/model.rs index c051d57..bcf72fe 100644 --- a/src/model.rs +++ b/src/model.rs @@ -28,6 +28,37 @@ pub struct ShoppingList { pub name: String, pub color: ListColor, 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)] @@ -231,6 +262,14 @@ mod tests { 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] fn text_roundtrip() { for icon in Icon::ALL {