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:
1 parent
9536cf0dbe
commit
cbda09ed40
12 files changed
+1083
-60
No files matched your search
@@ -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
@@ -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! {
|
||||
<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> }>
|
||||
<Route path=path!("/") view=ListsPage />
|
||||
<Route path=path!("/l/:id") view=ListsPage />
|
||||
<Route path=path!("/connexion") view=LoginPage />
|
||||
<Route path=path!("/inscription") view=RegisterPage />
|
||||
</Routes>
|
||||
</Router>
|
||||
}
|
||||
@@ -74,6 +79,9 @@ pub struct Ctx {
|
||||
optimistic: RwSignal<HashMap<i64, bool>>,
|
||||
item_editor: RwSignal<Option<ItemEditor>>,
|
||||
list_editor: RwSignal<Option<ListEditor>>,
|
||||
account_open: RwSignal<bool>,
|
||||
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! { <RequireUser render=|user| view! { <ListsView user /> } /> }
|
||||
}
|
||||
|
||||
#[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::<Auth>(),
|
||||
};
|
||||
provide_context(ctx);
|
||||
|
||||
@@ -157,12 +182,13 @@ fn ListsPage() -> impl IntoView {
|
||||
<h1 class="font-display text-5xl leading-[0.9] font-extrabold tracking-tight">
|
||||
"mes"<br />"listes"
|
||||
</h1>
|
||||
<div
|
||||
<button
|
||||
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"
|
||||
</div>
|
||||
{user.initials()}
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<ErrorBanner />
|
||||
@@ -192,6 +218,7 @@ fn ListsPage() -> impl IntoView {
|
||||
|
||||
<ItemSheet list_id=active_id />
|
||||
<ListSheet />
|
||||
<AccountSheet user />
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,6 +299,14 @@ fn ListsContent(
|
||||
<h2 class="mt-1 font-display text-[1.7rem] leading-tight font-bold tracking-tight">
|
||||
{list.name.clone()}
|
||||
</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>
|
||||
|
||||
<div class="mt-5 grid grid-cols-3 gap-3">
|
||||
|
||||
+115
-2
@@ -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<f64> {
|
||||
#[component]
|
||||
pub fn ListSheet() -> impl IntoView {
|
||||
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]
|
||||
@@ -364,6 +370,113 @@ fn ListForm(editor: ListEditor) -> impl IntoView {
|
||||
</button>
|
||||
</div>
|
||||
</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>
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user