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
+1083 -60

No files matched your search

+274 -30
View File
@@ -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<SqlitePool, sqlx::Error> {
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")?,
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<Item, sqlx::Error> {
})
}
pub async fn lists(pool: &SqlitePool) -> Result<Vec<ShoppingList>, 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<User, sqlx::Error> {
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<i64, sqlx::Error> {
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<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)
.await?
.iter()
.map(list_from_row)
.collect()
}
async fn insert_list(conn: &mut SqliteConnection, owner_id: i64, name: &str, color: ListColor) -> Result<i64, sqlx::Error> {
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<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> {
@@ -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<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> {
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<Vec<Item>, 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<Option<i64>, 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<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(
"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<Vec<Suggestion>, 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<Vec<Suggestion>, 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());
}