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

+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"));
}
}