forge
Explore
Log in

Don't you dare go Hollow

Account screens, session cookie and the server-side role guard

Browse files at this commit

0dbf1cf0522e7aed8b9f5c619d897bf739bb9fa2Ahmet Kaan GümüşParent: 8f9026e
  • feat
    • account screens, session cookie and the server-side role guard
Show full message
✨ feat(web): account screens, session cookie and the server-side role guard

Three doors, decided on the server: an empty workspace offers "Set up Dizey",
a claimed one offers a sign-in, an invited member arrives on /join/<token> and
picks a password the admin can neither see nor set. Copy is the FirstLogin
artboard's.

The session cookie is HttpOnly, Secure, SameSite=Lax and holds a 128-bit token
stored as SHA-256; it rotates on sign-in and on password change, and changing a
password revokes every other session, as the pane promises. Role checks live in
`server::require_{user,writer,admin}` and are answered in the handler, not
hidden in the UI.
crates/dizey-web/Cargo.tomlmodified+3 -2
@@ -15,9 +15,10 @@ leptos_router = { version = "0.9.0-beta1" }
15 leptos_meta = { version = "0.9.0-beta" }15 leptos_meta = { version = "0.9.0-beta" }
16 leptos_axum = { version = "0.9.0-beta", optional = true }16 leptos_axum = { version = "0.9.0-beta", optional = true }
17 serde.workspace = true17 serde.workspace = true
18+time.workspace = true
18 thiserror.workspace = true19 thiserror.workspace = true
19 20
20-dizey-core = { workspace = true, optional = true }21+dizey-core = { workspace = true }
21 axum = { version = "0.8.9", optional = true }22 axum = { version = "0.8.9", optional = true }
22 tokio = { workspace = true, optional = true }23 tokio = { workspace = true, optional = true }
23 tower = { version = "0.5.2", optional = true }24 tower = { version = "0.5.2", optional = true }
@@ -43,6 +44,6 @@ ssr = [
43 "dep:tokio",44 "dep:tokio",
44 "dep:tower",45 "dep:tower",
45 "dep:tower-http",46 "dep:tower-http",
46- "dep:dizey-core",47+ "dizey-core/server",
47 "dep:turso",48 "dep:turso",
48 ]49 ]
crates/dizey-web/src/app.rsmodified+4 -20
@@ -3,6 +3,8 @@ use leptos_meta::{MetaTags, Stylesheet, Title, provide_meta_context};
3 use leptos_router::components::{Route, Router, Routes};3 use leptos_router::components::{Route, Router, Routes};
4 use leptos_router::path;4 use leptos_router::path;
5 5
6+use crate::pages::{Join, Landing};
7+
6 /// The HTML document the server streams. `cargo-leptos` writes the bundle to8 /// The HTML document the server streams. `cargo-leptos` writes the bundle to
7 /// `/pkg/dizey.{js,wasm,css}`, which is what the tags below point at.9 /// `/pkg/dizey.{js,wasm,css}`, which is what the tags below point at.
8 pub fn shell(options: LeptosOptions) -> impl IntoView {10 pub fn shell(options: LeptosOptions) -> impl IntoView {
@@ -38,31 +40,13 @@ pub fn App() -> impl IntoView {
38 <Title text="Dizey"/>40 <Title text="Dizey"/>
39 <Router>41 <Router>
40 <Routes fallback=NotFound>42 <Routes fallback=NotFound>
41- <Route path=path!("/") view=BoardPlaceholder/>43+ <Route path=path!("/") view=Landing/>
44+ <Route path=path!("/join/:token") view=Join/>
42 </Routes>45 </Routes>
43 </Router>46 </Router>
44 }47 }
45 }48 }
46 49
47-/// The top bar from the Main artboard. The board itself lands in a later slice;
48-/// this exists so the scaffold renders something real rather than "hello".
49-#[component]
50-fn BoardPlaceholder() -> impl IntoView {
51- view! {
52- <header class="topbar">
53- <div class="wordmark">
54- <span class="wordmark-text">"dizey"</span>
55- <span class="wordmark-dot"></span>
56- </div>
57- <div class="topbar-divider"></div>
58- <span class="board-name">"Launch — Q3"</span>
59- </header>
60- <main class="scaffold-note">
61- <p>"The board is not wired up yet."</p>
62- </main>
63- }
64-}
65-
66 #[component]50 #[component]
67 fn NotFound() -> impl IntoView {51 fn NotFound() -> impl IntoView {
68 #[cfg(feature = "ssr")]52 #[cfg(feature = "ssr")]
crates/dizey-web/src/auth.rsadded+257 -0
@@ -0,0 +1,257 @@
1+//! The account surface: claiming the workspace, first sign-in from an invited
2+//! link, signing in and out, and changing a password.
3+//!
4+//! The public forms answer identically whether or not an address has an
5+//! account. The honest, specific wording belongs to the admin-side calls.
6+
7+use leptos::prelude::*;
8+use serde::{Deserialize, Serialize};
9+
10+/// Everything a refused call is allowed to say.
11+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
12+pub enum Refusal {
13+ /// Wrong address, wrong password, or no account at all — deliberately one
14+ /// answer for all three.
15+ Rejected,
16+ RateLimited,
17+ /// A password broke a stated rule. Only reachable once we know who the
18+ /// person is, so it gives nothing away.
19+ Password(String),
20+ Forbidden,
21+ SignInFirst,
22+ AlreadyClaimed,
23+ /// Admin-side wording, shown on the member list and nowhere public.
24+ AddressTaken,
25+ /// The link is spent, expired, or was never real.
26+ LinkNotUsable,
27+ Unavailable,
28+}
29+
30+impl Refusal {
31+ pub fn message(&self) -> String {
32+ match self {
33+ Refusal::Rejected => "That did not work.".to_string(),
34+ Refusal::RateLimited => {
35+ "Too many attempts — wait a few minutes and try again.".to_string()
36+ }
37+ Refusal::Password(problem) => problem.clone(),
38+ Refusal::Forbidden => "Not permitted.".to_string(),
39+ Refusal::SignInFirst => "Sign in first.".to_string(),
40+ Refusal::AlreadyClaimed => "This workspace already has an owner.".to_string(),
41+ Refusal::AddressTaken => "That address already has an account.".to_string(),
42+ Refusal::LinkNotUsable => {
43+ "This link no longer works. Ask the admin to send another."
44+ .to_string()
45+ }
46+ Refusal::Unavailable => "Something went wrong. Try again.".to_string(),
47+ }
48+ }
49+}
50+
51+/// The person the current browser is signed in as.
52+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
53+pub struct Me {
54+ pub display_name: String,
55+ pub email: String,
56+ pub role: dizey_core::Role,
57+}
58+
59+/// Which of the three doors this browser is standing at.
60+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
61+pub enum Gate {
62+ /// Nobody has signed in yet: the next account administers the workspace.
63+ NeedsSetup,
64+ NeedsSignIn,
65+ SignedIn(Me),
66+}
67+
68+/// The name and address an invitation was made out to. Only the holder of the
69+/// link can ask, and the link is a 128-bit secret, so answering is safe.
70+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
71+pub struct Invited {
72+ pub display_name: String,
73+ pub email: String,
74+}
75+
76+/// The workspace has exactly one name and no screen that sets it, so it is a
77+/// constant rather than a field nobody was shown.
78+pub const WORKSPACE_NAME: &str = "Dizey";
79+
80+/// Which door to show. (The `#[server]` macro names a struct after the
81+/// function, so the call is `current_gate` and the answer is a `Gate`.)
82+#[server]
83+pub async fn current_gate() -> Result<Gate, ServerFnError> {
84+ use crate::server::{accounts, current_user};
85+
86+ if let Some(user) = current_user().await {
87+ return Ok(Gate::SignedIn(Me {
88+ display_name: user.display_name,
89+ email: user.email,
90+ role: user.role,
91+ }));
92+ }
93+ let claimed = accounts()
94+ .store()
95+ .owner()
96+ .await
97+ .map_err(|e| ServerFnError::new(e.to_string()))?
98+ .is_some();
99+ Ok(if claimed {
100+ Gate::NeedsSignIn
101+ } else {
102+ Gate::NeedsSetup
103+ })
104+}
105+
106+/// The first account. It becomes the admin and owns the workspace.
107+#[server]
108+pub async fn claim_workspace(
109+ display_name: String,
110+ email: String,
111+ password: String,
112+) -> Result<Option<Refusal>, ServerFnError> {
113+ use crate::server::{accounts, set_session_cookie};
114+ use dizey_core::accounts::SESSION_LIFETIME;
115+
116+ match accounts()
117+ .claim_workspace(WORKSPACE_NAME, &email, &display_name, &password)
118+ .await
119+ {
120+ Ok((_workspace, signed_in)) => {
121+ set_session_cookie(signed_in.session_token.expose(), SESSION_LIFETIME);
122+ Ok(None)
123+ }
124+ Err(error) => Ok(Some(error.into())),
125+ }
126+}
127+
128+/// Who an invitation was made out to, for the "signing in as" line.
129+#[server]
130+pub async fn invitation(token: String) -> Result<Option<Invited>, ServerFnError> {
131+ use crate::server::accounts;
132+ use dizey_core::auth::hash_token;
133+ use time::OffsetDateTime;
134+
135+ let store = accounts().store().clone();
136+ let digest = hash_token(&token);
137+ let Some(link) = store
138+ .signin_link_by_hash(&digest)
139+ .await
140+ .map_err(|e| ServerFnError::new(e.to_string()))?
141+ else {
142+ return Ok(None);
143+ };
144+ if !link.is_usable(OffsetDateTime::now_utc()) {
145+ return Ok(None);
146+ }
147+ let Some(user) = store
148+ .user(&link.user_id)
149+ .await
150+ .map_err(|e| ServerFnError::new(e.to_string()))?
151+ else {
152+ return Ok(None);
153+ };
154+ Ok(Some(Invited {
155+ display_name: user.display_name,
156+ email: user.email,
157+ }))
158+}
159+
160+/// The invited member's first sign-in: they pick their own password. The admin
161+/// can neither read nor set it.
162+#[server]
163+pub async fn redeem_link(
164+ token: String,
165+ password: String,
166+) -> Result<Option<Refusal>, ServerFnError> {
167+ use crate::server::{accounts, set_session_cookie};
168+ use dizey_core::accounts::SESSION_LIFETIME;
169+
170+ match accounts().redeem_signin_link(&token, &password).await {
171+ Ok(signed_in) => {
172+ set_session_cookie(signed_in.session_token.expose(), SESSION_LIFETIME);
173+ Ok(None)
174+ }
175+ Err(error) => Ok(Some(error.into())),
176+ }
177+}
178+
179+/// Signing in. Answers the same whether the address is unknown, has no password
180+/// yet, or the password is wrong.
181+#[server]
182+pub async fn sign_in(
183+ email: String,
184+ password: String,
185+) -> Result<Option<Refusal>, ServerFnError> {
186+ use crate::server::{accounts, client_label, set_session_cookie};
187+ use dizey_core::accounts::SESSION_LIFETIME;
188+
189+ match accounts()
190+ .sign_in(&email, &password, &client_label())
191+ .await
192+ {
193+ Ok(signed_in) => {
194+ set_session_cookie(signed_in.session_token.expose(), SESSION_LIFETIME);
195+ Ok(None)
196+ }
197+ Err(error) => Ok(Some(error.into())),
198+ }
199+}
200+
201+/// Ends this browser's session. Other browsers keep theirs.
202+#[server]
203+pub async fn sign_out() -> Result<(), ServerFnError> {
204+ use crate::server::{accounts, clear_session_cookie, presented_session};
205+
206+ if let Some(presented) = presented_session() {
207+ let _ = accounts().sign_out(&presented).await;
208+ }
209+ clear_session_cookie();
210+ Ok(())
211+}
212+
213+/// Changes the password and signs the other devices out, as the pane promises.
214+/// The browser that asked gets a fresh cookie.
215+#[server]
216+pub async fn change_password(
217+ current: String,
218+ new: String,
219+) -> Result<Option<Refusal>, ServerFnError> {
220+ use crate::server::{require_user, set_session_cookie};
221+ use dizey_core::accounts::SESSION_LIFETIME;
222+
223+ let user = match require_user().await {
224+ Ok(user) => user,
225+ Err(refusal) => return Ok(Some(refusal)),
226+ };
227+ match crate::server::accounts()
228+ .change_password(&user.id, &current, &new)
229+ .await
230+ {
231+ Ok(signed_in) => {
232+ set_session_cookie(signed_in.session_token.expose(), SESSION_LIFETIME);
233+ Ok(None)
234+ }
235+ Err(error) => Ok(Some(error.into())),
236+ }
237+}
238+
239+/// Admin creates an account with a name and an address and no password, and
240+/// gets the first-sign-in link back exactly once.
241+#[server]
242+pub async fn invite_member(
243+ email: String,
244+ display_name: String,
245+ role: dizey_core::Role,
246+) -> Result<Result<String, Refusal>, ServerFnError> {
247+ use crate::server::{accounts, require_admin};
248+
249+ let admin = match require_admin().await {
250+ Ok(admin) => admin,
251+ Err(refusal) => return Ok(Err(refusal)),
252+ };
253+ match accounts().invite(&admin, &email, &display_name, role).await {
254+ Ok(invitation) => Ok(Ok(format!("/join/{}", invitation.token.expose()))),
255+ Err(error) => Ok(Err(error.into())),
256+ }
257+}
crates/dizey-web/src/lib.rsmodified+4 -0
@@ -1,4 +1,8 @@
1 pub mod app;1 pub mod app;
2+pub mod auth;
3+pub mod pages;
4+#[cfg(feature = "ssr")]
5+pub mod server;
2 6
3 #[cfg(feature = "hydrate")]7 #[cfg(feature = "hydrate")]
4 #[wasm_bindgen::prelude::wasm_bindgen]8 #[wasm_bindgen::prelude::wasm_bindgen]
crates/dizey-web/src/main.rsmodified+30 -5
@@ -2,9 +2,21 @@
2 #[tokio::main]2 #[tokio::main]
3 async fn main() {3 async fn main() {
4 use axum::Router;4 use axum::Router;
5+ use dizey_core::accounts::Accounts;
6+ use dizey_core::store::TursoStore;
5 use dizey_web::app::{App, shell};7 use dizey_web::app::{App, shell};
6 use leptos::prelude::*;8 use leptos::prelude::*;
7 use leptos_axum::{LeptosRoutes, generate_route_list};9 use leptos_axum::{LeptosRoutes, generate_route_list};
10+ use std::sync::Arc;
11+
12+ // One process per database file: Turso is a single-writer engine and a
13+ // second process on the same file loses writes rather than queueing.
14+ let database = std::env::var("DIZEY_DATABASE").unwrap_or_else(|_| "dizey.db".to_string());
15+ // `open` applies any unapplied migration before it returns.
16+ let store = TursoStore::open(&database)
17+ .await
18+ .expect("failed to open the database");
19+ let accounts = Accounts::new(Arc::new(store));
8 20
9 let conf = get_configuration(None).expect("failed to read leptos configuration");21 let conf = get_configuration(None).expect("failed to read leptos configuration");
10 let leptos_options = conf.leptos_options;22 let leptos_options = conf.leptos_options;
@@ -13,10 +25,20 @@ async fn main() {
13 25
14 let app = Router::new()26 let app = Router::new()
15 .route("/healthz", axum::routing::get(|| async { "ok" }))27 .route("/healthz", axum::routing::get(|| async { "ok" }))
16- .leptos_routes(&leptos_options, routes, {28+ .leptos_routes_with_context(
17- let leptos_options = leptos_options.clone();29+ &leptos_options,
18- move || shell(leptos_options.clone())30+ routes,
19- })31+ {
32+ // Provided here *and* to the server-function handler, which
33+ // `leptos_routes_with_context` registers with the same closure.
34+ let accounts = accounts.clone();
35+ move || provide_context(accounts.clone())
36+ },
37+ {
38+ let leptos_options = leptos_options.clone();
39+ move || shell(leptos_options.clone())
40+ },
41+ )
20 .fallback(leptos_axum::file_and_error_handler(shell))42 .fallback(leptos_axum::file_and_error_handler(shell))
21 .with_state(leptos_options);43 .with_state(leptos_options);
22 44
@@ -24,7 +46,10 @@ async fn main() {
24 .await46 .await
25 .expect("failed to bind");47 .expect("failed to bind");
26 println!("dizey listening on http://{addr}");48 println!("dizey listening on http://{addr}");
27- axum::serve(listener, app.into_make_service())49+ axum::serve(
50+ listener,
51+ app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
52+ )
28 .await53 .await
29 .expect("server error");54 .expect("server error");
30 }55 }
crates/dizey-web/src/pages.rsadded+338 -0
@@ -0,0 +1,338 @@
1+//! The account screens, from the FirstLogin artboard: setting up the first
2+//! account, an invited member picking a password, and signing in.
3+
4+use leptos::prelude::*;
5+use leptos_router::hooks::use_params_map;
6+
7+use crate::auth::{
8+ ClaimWorkspace, Gate, Invited, RedeemLink, Refusal, SignIn, current_gate, invitation,
9+};
10+
11+/// The front door. Which screen this is depends on the workspace, and the
12+/// server decides — an empty workspace offers setup, a claimed one offers a
13+/// sign-in, a signed-in browser gets the board.
14+#[component]
15+pub fn Landing() -> impl IntoView {
16+ let gate = Resource::new(|| (), |_| async move { current_gate().await });
17+
18+ view! {
19+ <Topbar/>
20+ <Suspense fallback=|| view! { <main class="auth-stage"></main> }>
21+ {move || Suspend::new(async move {
22+ match gate.await {
23+ Ok(Gate::NeedsSetup) => {
24+ view! { <SetupCard on_done=move || gate.refetch()/> }.into_any()
25+ }
26+ Ok(Gate::NeedsSignIn) => {
27+ view! { <SignInCard on_done=move || gate.refetch()/> }.into_any()
28+ }
29+ Ok(Gate::SignedIn(me)) => {
30+ view! {
31+ <main class="scaffold-note">
32+ <p>
33+ "Signed in as " {me.display_name} " (" {me.email} ")."
34+ </p>
35+ <p>"The board is not wired up yet."</p>
36+ </main>
37+ }
38+ .into_any()
39+ }
40+ Err(_) => {
41+ view! {
42+ <main class="scaffold-note">
43+ <p>"Something went wrong. Reload the page."</p>
44+ </main>
45+ }
46+ .into_any()
47+ }
48+ }
49+ })}
50+ </Suspense>
51+ }
52+}
53+
54+#[component]
55+fn Topbar() -> impl IntoView {
56+ view! {
57+ <header class="topbar">
58+ <div class="wordmark">
59+ <span class="wordmark-text">"dizey"</span>
60+ <span class="wordmark-dot"></span>
61+ </div>
62+ </header>
63+ }
64+}
65+
66+/// "Set up Dizey" — the first account in an empty workspace.
67+#[component]
68+fn SetupCard(on_done: impl Fn() + Copy + Send + Sync + 'static) -> impl IntoView {
69+ let action = ServerAction::<ClaimWorkspace>::new();
70+ let value = action.value();
71+ Effect::new(move |_| {
72+ if matches!(value.get(), Some(Ok(None))) {
73+ on_done();
74+ }
75+ });
76+
77+ view! {
78+ <main class="auth-stage">
79+ <div class="auth-column">
80+ <span class="auth-kicker">"FIRST ACCOUNT — EMPTY WORKSPACE"</span>
81+ <div class="auth-card">
82+ <div class="auth-head">
83+ <div class="auth-title">"Set up Dizey"</div>
84+ <div class="auth-sub">
85+ "Nobody has signed in yet, so this account administers the workspace: the mail sender, the limits and the member list are yours."
86+ </div>
87+ </div>
88+ <ActionForm action=action>
89+ <label class="auth-field">
90+ <span class="auth-label">"YOUR NAME"</span>
91+ <input
92+ class="auth-input"
93+ type="text"
94+ name="display_name"
95+ autocomplete="name"
96+ required
97+ />
98+ </label>
99+ <label class="auth-field">
100+ <span class="auth-label">"EMAIL"</span>
101+ <input
102+ class="auth-input auth-input-mono"
103+ type="email"
104+ name="email"
105+ autocomplete="email"
106+ required
107+ />
108+ </label>
109+ <label class="auth-field">
110+ <span class="auth-label">"PASSWORD"</span>
111+ <input
112+ class="auth-input auth-input-mono"
113+ type="password"
114+ name="password"
115+ autocomplete="new-password"
116+ required
117+ />
118+ </label>
119+ <PasswordRules/>
120+ <button class="auth-submit" type="submit" disabled=move || action.pending().get()>
121+ <span class="auth-submit-text">"Create workspace"</span>
122+ <span class="auth-key">"↵"</span>
123+ </button>
124+ </ActionForm>
125+ <Problem value=value/>
126+ <div class="auth-foot">
127+ "Mail rules stay quiet until you connect a sender in Settings. Nothing leaves the machine before that."
128+ </div>
129+ </div>
130+ </div>
131+ </main>
132+ }
133+}
134+
135+/// "Pick a password" — the invited member's first sign-in, reached from the
136+/// emailed link. The address was set by the admin and cannot be edited here.
137+#[component]
138+pub fn Join() -> impl IntoView {
139+ let params = use_params_map();
140+ let token = move || params.read().get("token").unwrap_or_default();
141+ let who = Resource::new(token, |token| async move { invitation(token).await });
142+
143+ view! {
144+ <Topbar/>
145+ <Suspense fallback=|| view! { <main class="auth-stage"></main> }>
146+ {move || Suspend::new(async move {
147+ match who.await {
148+ Ok(Some(person)) => view! { <JoinCard token=token() person=person/> }.into_any(),
149+ _ => {
150+ view! {
151+ <main class="auth-stage">
152+ <div class="auth-column">
153+ <div class="auth-card">
154+ <div class="auth-title">"This link no longer works"</div>
155+ <div class="auth-sub">
156+ "Sign-in links last seven days. Ask the admin to send another — it opens the same account, with the same history."
157+ </div>
158+ </div>
159+ </div>
160+ </main>
161+ }
162+ .into_any()
163+ }
164+ }
165+ })}
166+ </Suspense>
167+ }
168+}
169+
170+#[component]
171+fn JoinCard(token: String, person: Invited) -> impl IntoView {
172+ let action = ServerAction::<RedeemLink>::new();
173+ let value = action.value();
174+ let navigate = leptos_router::hooks::use_navigate();
175+ Effect::new(move |_| {
176+ if matches!(value.get(), Some(Ok(None))) {
177+ navigate("/", Default::default());
178+ }
179+ });
180+
181+ let repeat = RwSignal::new(String::new());
182+ let chosen = RwSignal::new(String::new());
183+ let matches_yet = move || {
184+ let repeat = repeat.get();
185+ !repeat.is_empty() && repeat == chosen.get()
186+ };
187+ let invited_by = person.display_name.clone();
188+
189+ view! {
190+ <main class="auth-stage">
191+ <div class="auth-column">
192+ <span class="auth-kicker">"INVITED MEMBER — FIRST SIGN-IN"</span>
193+ <div class="auth-card">
194+ <div class="auth-head">
195+ <div class="auth-title">"Pick a password"</div>
196+ <div class="auth-sub">
197+ {invited_by} " made you an account. It has no password yet."
198+ </div>
199+ </div>
200+ <div class="auth-field">
201+ <span class="auth-label">"SIGNING IN AS"</span>
202+ <div class="auth-locked">
203+ <span class="auth-locked-value">{person.email}</span>
204+ <span class="auth-locked-note">"set by the admin"</span>
205+ </div>
206+ </div>
207+ <ActionForm action=action>
208+ <input type="hidden" name="token" value=token/>
209+ <label class="auth-field">
210+ <span class="auth-label">"NEW PASSWORD"</span>
211+ <input
212+ class="auth-input auth-input-mono"
213+ type="password"
214+ name="password"
215+ autocomplete="new-password"
216+ required
217+ on:input=move |ev| chosen.set(event_target_value(&ev))
218+ />
219+ </label>
220+ <label class="auth-field">
221+ <span class="auth-label">"REPEAT IT"</span>
222+ <input
223+ class="auth-input auth-input-mono"
224+ type="password"
225+ autocomplete="new-password"
226+ on:input=move |ev| repeat.set(event_target_value(&ev))
227+ />
228+ <Show when=move || !repeat.get().is_empty() && !matches_yet()>
229+ <span class="auth-warn">"not the same yet"</span>
230+ </Show>
231+ </label>
232+ <PasswordRules/>
233+ <button
234+ class="auth-submit"
235+ type="submit"
236+ disabled=move || !matches_yet() || action.pending().get()
237+ >
238+ <span class="auth-submit-text">"Set password and sign in"</span>
239+ </button>
240+ <Show when=move || !matches_yet()>
241+ <div class="auth-warn">"Waiting for the repeated password to match."</div>
242+ </Show>
243+ </ActionForm>
244+ <Problem value=value/>
245+ <div class="auth-foot">
246+ "Name and photo can wait — you land on the board straight after this. The admin cannot see or set your password."
247+ </div>
248+ </div>
249+ </div>
250+ </main>
251+ }
252+}
253+
254+/// The sign-in form for an account that already has a password. It answers the
255+/// same whether the address is unknown, has no password yet, or the password is
256+/// wrong — the difference is not the browser's business.
257+#[component]
258+fn SignInCard(on_done: impl Fn() + Copy + Send + Sync + 'static) -> impl IntoView {
259+ let action = ServerAction::<SignIn>::new();
260+ let value = action.value();
261+ Effect::new(move |_| {
262+ if matches!(value.get(), Some(Ok(None))) {
263+ on_done();
264+ }
265+ });
266+
267+ view! {
268+ <main class="auth-stage">
269+ <div class="auth-column">
270+ <span class="auth-kicker">"SIGN IN"</span>
271+ <div class="auth-card">
272+ <div class="auth-head">
273+ <div class="auth-title">"Sign in to Dizey"</div>
274+ <div class="auth-sub">
275+ "Accounts are made by the admin. If you were invited, use the link you were sent — it is where you choose your password."
276+ </div>
277+ </div>
278+ <ActionForm action=action>
279+ <label class="auth-field">
280+ <span class="auth-label">"EMAIL"</span>
281+ <input
282+ class="auth-input auth-input-mono"
283+ type="email"
284+ name="email"
285+ autocomplete="username"
286+ required
287+ />
288+ </label>
289+ <label class="auth-field">
290+ <span class="auth-label">"PASSWORD"</span>
291+ <input
292+ class="auth-input auth-input-mono"
293+ type="password"
294+ name="password"
295+ autocomplete="current-password"
296+ required
297+ />
298+ </label>
299+ <button class="auth-submit" type="submit" disabled=move || action.pending().get()>
300+ <span class="auth-submit-text">"Sign in"</span>
301+ <span class="auth-key">"↵"</span>
302+ </button>
303+ </ActionForm>
304+ <Problem value=value/>
305+ </div>
306+ </div>
307+ </main>
308+ }
309+}
310+
311+/// The two rules, stated where the password is chosen. The server checks them
312+/// again and is the one that decides.
313+#[component]
314+fn PasswordRules() -> impl IntoView {
315+ view! {
316+ <ul class="auth-rules">
317+ <li>"at least 10 characters"</li>
318+ <li>"not your address or your name"</li>
319+ </ul>
320+ }
321+}
322+
323+/// Whatever the server refused with, in its own words.
324+#[component]
325+fn Problem(
326+ #[prop(into)] value: Signal<Option<Result<Option<Refusal>, ServerFnError>>>,
327+) -> impl IntoView {
328+ let message = move || match value.get() {
329+ Some(Ok(Some(refusal))) => Some(refusal.message()),
330+ Some(Err(_)) => Some(Refusal::Unavailable.message()),
331+ _ => None,
332+ };
333+ view! {
334+ <Show when=move || message().is_some()>
335+ <div class="auth-problem">{move || message().unwrap_or_default()}</div>
336+ </Show>
337+ }
338+}
crates/dizey-web/src/server.rsadded+148 -0
@@ -0,0 +1,148 @@
1+//! Server-side plumbing for the auth surface: the session cookie, the person
2+//! behind the current request, and the role guards.
3+//!
4+//! Every guard here is the real one. The UI hides what a role may not do, but
5+//! the answer that matters is the one given in this module, on the server.
6+
7+use axum::http::HeaderValue;
8+use axum::http::header::{COOKIE, SET_COOKIE};
9+use axum::http::request::Parts;
10+use dizey_core::accounts::{AccountError, Accounts};
11+use dizey_core::store::User;
12+use leptos::prelude::*;
13+use leptos_axum::ResponseOptions;
14+
15+/// The session cookie's name. One cookie, one browser, one session row.
16+pub const SESSION_COOKIE: &str = "dizey_session";
17+
18+/// The workspace's account service, put into context by the router.
19+pub fn accounts() -> Accounts {
20+ expect_context::<Accounts>()
21+}
22+
23+/// The cookie value this request presented, if it presented one.
24+pub fn presented_session() -> Option<String> {
25+ let parts = use_context::<Parts>()?;
26+ for header in parts.headers.get_all(COOKIE) {
27+ let Ok(raw) = header.to_str() else { continue };
28+ for pair in raw.split(';') {
29+ let pair = pair.trim();
30+ if let Some(value) = pair.strip_prefix(SESSION_COOKIE)
31+ && let Some(value) = value.strip_prefix('=')
32+ {
33+ return Some(value.to_string());
34+ }
35+ }
36+ }
37+ None
38+}
39+
40+/// A stable-enough label for the client, for rate limiting. A proxy header is
41+/// only trusted because Dizey is meant to sit behind one; the address bucket is
42+/// the limit that actually protects the Argon2 work either way.
43+pub fn client_label() -> String {
44+ let Some(parts) = use_context::<Parts>() else {
45+ return "unknown".to_string();
46+ };
47+ if let Some(forwarded) = parts.headers.get("x-forwarded-for")
48+ && let Ok(raw) = forwarded.to_str()
49+ && let Some(first) = raw.split(',').next()
50+ && !first.trim().is_empty()
51+ {
52+ return first.trim().to_string();
53+ }
54+ parts
55+ .extensions
56+ .get::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
57+ .map(|info| info.0.ip().to_string())
58+ .unwrap_or_else(|| "unknown".to_string())
59+}
60+
61+/// Writes the session cookie. `HttpOnly` so script cannot read it, `Secure` so
62+/// it never crosses plain HTTP, `SameSite=Lax` so another site's form cannot
63+/// post with it.
64+pub fn set_session_cookie(token: &str, lifetime: time::Duration) {
65+ let value = format!(
66+ "{SESSION_COOKIE}={token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age={}",
67+ lifetime.whole_seconds().max(0)
68+ );
69+ write_cookie(&value);
70+}
71+
72+/// Removes the session cookie from this browser. The server-side revocation is
73+/// what actually ends the session; this only tidies the client.
74+pub fn clear_session_cookie() {
75+ write_cookie(&format!(
76+ "{SESSION_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0"
77+ ));
78+}
79+
80+fn write_cookie(value: &str) {
81+ let Some(response) = use_context::<ResponseOptions>() else {
82+ return;
83+ };
84+ match HeaderValue::from_str(value) {
85+ Ok(header) => response.append_header(SET_COOKIE, header),
86+ Err(_) => {
87+ // A token is hex, and the rest is a literal, so this cannot happen
88+ // from user input; refusing to send a malformed header is still the
89+ // right failure.
90+ eprintln!("refusing to set a malformed session cookie");
91+ }
92+ }
93+}
94+
95+/// The person behind this request, or nobody.
96+pub async fn current_user() -> Option<User> {
97+ let presented = presented_session()?;
98+ accounts().authenticate(&presented).await.ok().flatten()
99+}
100+
101+/// The person behind this request, or a refusal the caller can return as-is.
102+pub async fn require_user() -> Result<User, Refusal> {
103+ current_user().await.ok_or(Refusal::SignInFirst)
104+}
105+
106+/// The admin behind this request. A member or a viewer is refused *here*, not
107+/// merely hidden from in the UI.
108+pub async fn require_admin() -> Result<User, Refusal> {
109+ let user = require_user().await?;
110+ if user.role.can_administer() {
111+ Ok(user)
112+ } else {
113+ Err(Refusal::Forbidden)
114+ }
115+}
116+
117+/// The person behind this request if they may change the board.
118+pub async fn require_writer() -> Result<User, Refusal> {
119+ let user = require_user().await?;
120+ if user.role.can_write_tasks() {
121+ Ok(user)
122+ } else {
123+ Err(Refusal::Forbidden)
124+ }
125+}
126+
127+use crate::auth::Refusal;
128+
129+impl From<AccountError> for Refusal {
130+ fn from(error: AccountError) -> Self {
131+ match error {
132+ AccountError::Rejected => Refusal::Rejected,
133+ AccountError::RateLimited => Refusal::RateLimited,
134+ AccountError::Password(problem) => Refusal::Password(problem.to_string()),
135+ AccountError::Forbidden => Refusal::Forbidden,
136+ AccountError::AlreadyClaimed => Refusal::AlreadyClaimed,
137+ AccountError::AddressTaken => Refusal::AddressTaken,
138+ AccountError::Store(error) => {
139+ eprintln!("store error: {error}");
140+ Refusal::Unavailable
141+ }
142+ AccountError::Auth(error) => {
143+ eprintln!("auth error: {error}");
144+ Refusal::Unavailable
145+ }
146+ }
147+ }
148+}
style/main.scssmodified+181 -0
@@ -79,3 +79,184 @@ a {
79 padding: 32px 24px;79 padding: 32px 24px;
80 color: var(--muted);80 color: var(--muted);
81 }81 }
82+
83+// --- Account screens (FirstLogin artboard) ---------------------------------
84+
85+.auth-stage {
86+ min-height: calc(100vh - var(--topbar-height));
87+ display: flex;
88+ align-items: center;
89+ justify-content: center;
90+ padding: 0 40px 40px;
91+}
92+
93+.auth-column {
94+ width: 520px;
95+ max-width: 100%;
96+ display: flex;
97+ flex-direction: column;
98+ gap: 10px;
99+}
100+
101+.auth-kicker {
102+ font-family: var(--font-mono);
103+ font-size: 10px;
104+ letter-spacing: 0.08em;
105+ color: var(--muted-soft);
106+}
107+
108+.auth-card {
109+ background: var(--surface);
110+ border: 1px solid var(--border);
111+ border-radius: 12px;
112+ padding: 28px 30px;
113+ display: flex;
114+ flex-direction: column;
115+ gap: 18px;
116+ box-shadow: 0 4px 16px rgba(28, 27, 24, 0.04);
117+
118+ form {
119+ display: flex;
120+ flex-direction: column;
121+ gap: 18px;
122+ }
123+}
124+
125+.auth-head {
126+ display: flex;
127+ flex-direction: column;
128+ gap: 6px;
129+}
130+
131+.auth-title {
132+ font-size: 19px;
133+ font-weight: 600;
134+}
135+
136+.auth-sub {
137+ font-size: 13px;
138+ color: var(--muted);
139+ line-height: 1.5;
140+}
141+
142+.auth-field {
143+ display: flex;
144+ flex-direction: column;
145+ gap: 6px;
146+}
147+
148+.auth-label {
149+ font-family: var(--font-mono);
150+ font-size: 10px;
151+ letter-spacing: 0.08em;
152+ color: var(--muted-soft);
153+}
154+
155+.auth-input {
156+ height: 40px;
157+ padding: 0 12px;
158+ background: #faf9f6;
159+ border: 1px solid var(--border-strong);
160+ border-radius: var(--radius);
161+ font-family: var(--font-sans);
162+ font-size: 13px;
163+ color: var(--ink);
164+
165+ &:focus {
166+ outline: none;
167+ background: var(--surface);
168+ border-color: var(--accent);
169+ }
170+}
171+
172+.auth-input-mono {
173+ font-family: var(--font-mono);
174+}
175+
176+// The address an invited member signs in as: shown, never edited.
177+.auth-locked {
178+ display: flex;
179+ align-items: center;
180+ gap: 8px;
181+ height: 40px;
182+ padding: 0 12px;
183+ background: #f2f0ea;
184+ border: 1px solid var(--border-strong);
185+ border-radius: var(--radius);
186+}
187+
188+.auth-locked-value {
189+ font-family: var(--font-mono);
190+ font-size: 13px;
191+ color: var(--muted);
192+ flex-grow: 1;
193+}
194+
195+.auth-locked-note {
196+ font-size: 12px;
197+ color: var(--muted-soft);
198+}
199+
200+.auth-rules {
201+ margin: 0;
202+ padding-left: 18px;
203+ display: flex;
204+ flex-direction: column;
205+ gap: 4px;
206+ font-size: 12px;
207+ color: #5c7b46;
208+}
209+
210+.auth-submit {
211+ height: 42px;
212+ display: flex;
213+ align-items: center;
214+ justify-content: center;
215+ gap: 8px;
216+ background: var(--accent);
217+ color: var(--surface);
218+ border: 0;
219+ border-radius: var(--radius);
220+ cursor: pointer;
221+ font-family: var(--font-sans);
222+
223+ &:disabled {
224+ opacity: 0.45;
225+ cursor: default;
226+ }
227+}
228+
229+.auth-submit-text {
230+ font-size: 14px;
231+ font-weight: 600;
232+}
233+
234+.auth-key {
235+ font-family: var(--font-mono);
236+ font-size: 10px;
237+ background: #5a6a94;
238+ border-radius: 4px;
239+ padding: 1px 5px;
240+}
241+
242+.auth-warn {
243+ font-size: 12px;
244+ color: #a04a24;
245+}
246+
247+.auth-problem {
248+ font-size: 13px;
249+ color: #a04a24;
250+ background: #fbf1ec;
251+ border: 1px solid #eddcd3;
252+ border-radius: var(--radius);
253+ padding: 10px 12px;
254+}
255+
256+.auth-foot {
257+ font-size: 12px;
258+ color: var(--muted-soft);
259+ line-height: 1.5;
260+ border-top: 1px solid #f0eee7;
261+ padding-top: 12px;
262+}