forge
Explore
Log in

Don't you dare go Hollow

Settings crosses over

Browse files at this commit

6106c349e23361a34cb015711de4088595b85fb2Ahmet Kaan GümüşParent: 714d109
  • feat
    • settings crosses over
Show full message
✨ feat(topcoat): settings crosses over
crates/izlek-topcoat/src/settings.rsmodified+936 -1
@@ -1 +1,936 @@
1-//! Lands in the page-port fan-out.1+//! Settings, from the Settings and MemberSettings artboards.
2+//!
3+//! Which panels a person gets is decided on the server: the sender and the
4+//! limits belong to an admin, and a Member's answer simply does not carry
5+//! them — the page cannot hide what it was never sent. Every mutation here
6+//! checks the role again in its own handler, because a panel that is not
7+//! drawn is a courtesy and not a guard.
8+//!
9+//! Ported from `izlek-web/src/settings.rs`. That version reads through a
10+//! Leptos server fn behind a `Resource` and writes through `ServerAction`s
11+//! whose return value a hydrated page reads straight off; here the page is
12+//! rendered server-side on every request and a save is a plain form post, so
13+//! the answer — success or refusal — travels home the way `files.rs`'s
14+//! upload already does: appended to the redirect's query, in the same
15+//! `?refusal=<code>&on=<call>` shape `Refusal::code` was built for.
16+//!
17+//! `resend_link` differs from `izlek-web`'s in one respect: there it answered
18+//! a hydrated `ActionForm` with the mailed address directly. There is no
19+//! hydration here, so it redirects instead, carrying the address on the
20+//! query the same way a refusal does.
21+
22+use topcoat::Result;
23+use topcoat::context::Cx;
24+use topcoat::router::content::Form;
25+use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, page, route};
26+use topcoat::view::view;
27+
28+use izlek_core::store::{NewSender, SenderTest, User};
29+
30+use crate::server::{Refusal, accounts, mail, require_admin, require_user};
31+
32+/// The widest either limit may be set to. A ceiling of any size is a promise
33+/// the disk has to keep, and a limit typed with one extra zero is a mistake
34+/// nobody notices until the disk is full.
35+///
36+/// `izlek-topcoat::files` carries its own copy until that lane imports this
37+/// one (per the settings lane's note there).
38+pub const WIDEST_ATTACHMENT_MB: u64 = 500;
39+pub const WIDEST_PHOTO_MB: u64 = 20;
40+
41+const MB: u64 = 1024 * 1024;
42+
43+/// `1.2 s` for anything over a second, `840 ms` below it. A mail server that
44+/// answered in under a second is worth saying so precisely; one that took
45+/// eight is worth a number somebody can compare to the last one.
46+fn took_label(ms: u64) -> String {
47+ if ms >= 1000 {
48+ format!("{:.1} s", ms as f64 / 1000.0)
49+ } else {
50+ format!("{ms} ms")
51+ }
52+}
53+
54+/// The shallowest check that catches a typo without rejecting a real
55+/// address. Nothing here is trying to decide what RFC 5322 permits — the
56+/// mail server settles that, and a refusal from it lands in the ledger with
57+/// its own words.
58+fn is_address(raw: &str) -> bool {
59+ let mut halves = raw.split('@');
60+ let (Some(local), Some(domain), None) = (halves.next(), halves.next(), halves.next()) else {
61+ return false;
62+ };
63+ !local.is_empty()
64+ && domain.contains('.')
65+ && !domain.starts_with('.')
66+ && !domain.ends_with('.')
67+ && !raw.contains(char::is_whitespace)
68+}
69+
70+/// The typed list as extensions, or `None` if one of them is not an
71+/// extension.
72+///
73+/// Lowercased, dots dropped, duplicates dropped, and nothing but letters and
74+/// digits kept — a "type" with a slash or a dot in it would be a path or a
75+/// pattern wearing an extension's clothes, and this list is checked against a
76+/// filename later.
77+fn parse_types(raw: &str) -> Option<Vec<String>> {
78+ let mut types: Vec<String> = Vec::new();
79+ for piece in raw.split([',', ' ', '\n']) {
80+ let piece = piece.trim().trim_start_matches('.').to_lowercase();
81+ if piece.is_empty() {
82+ continue;
83+ }
84+ if piece.len() > 12 || !piece.chars().all(|c| c.is_ascii_alphanumeric()) {
85+ return None;
86+ }
87+ if !types.contains(&piece) {
88+ types.push(piece);
89+ }
90+ }
91+ Some(types)
92+}
93+
94+/// A query value survives the round trip to a `Location` header only if it
95+/// cannot be mistaken for another pair or break the header outright — a
96+/// mailed address may hold `+`, `&`, `=`, none of which a hand-built query
97+/// string may pass through raw.
98+fn encode_q(raw: &str) -> String {
99+ let mut out = String::with_capacity(raw.len());
100+ for byte in raw.bytes() {
101+ match byte {
102+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
103+ out.push(byte as char)
104+ }
105+ _ => out.push_str(&format!("%{byte:02X}")),
106+ }
107+ }
108+ out
109+}
110+
111+fn decode_q(raw: &str) -> String {
112+ let bytes = raw.as_bytes();
113+ let mut out = Vec::with_capacity(bytes.len());
114+ let mut i = 0;
115+ while i < bytes.len() {
116+ if bytes[i] == b'%' && i + 2 < bytes.len() {
117+ if let Ok(value) = u8::from_str_radix(&raw[i + 1..i + 3], 16) {
118+ out.push(value);
119+ i += 3;
120+ continue;
121+ }
122+ }
123+ out.push(bytes[i]);
124+ i += 1;
125+ }
126+ String::from_utf8_lossy(&out).into_owned()
127+}
128+
129+#[cfg(test)]
130+mod codec_tests {
131+ use super::{decode_q, encode_q, parse_types, took_label};
132+
133+ #[test]
134+ fn an_address_survives_the_round_trip() {
135+ for address in ["a@b.com", "a+tag@b.com", "a&b=c@b.com", "weird%chars@b.com"] {
136+ assert_eq!(decode_q(&encode_q(address)), address);
137+ }
138+ }
139+
140+ #[test]
141+ fn a_list_is_lowercased_undotted_and_deduplicated() {
142+ assert_eq!(
143+ parse_types(".PNG, png, jpg").unwrap(),
144+ vec!["png".to_string(), "jpg".to_string()]
145+ );
146+ }
147+
148+ #[test]
149+ fn an_empty_list_means_every_type() {
150+ assert_eq!(parse_types(" ").unwrap(), Vec::<String>::new());
151+ }
152+
153+ #[test]
154+ fn nothing_that_is_not_an_extension_is_stored_as_one() {
155+ assert!(parse_types("image/png").is_none());
156+ assert!(parse_types("../etc").is_none());
157+ assert!(parse_types("*").is_none());
158+ assert!(parse_types("tar.gz").is_none());
159+ }
160+
161+ #[test]
162+ fn a_send_is_timed_the_way_the_artboard_writes_it() {
163+ assert_eq!(took_label(1234), "1.2 s");
164+ assert_eq!(took_label(1000), "1.0 s");
165+ assert_eq!(took_label(999), "999 ms");
166+ assert_eq!(took_label(0), "0 ms");
167+ }
168+}
169+
170+/// A 303 to `/settings`, with `query` appended.
171+fn redirect_to(query: &str) -> (StatusCode, HeaderMap, Vec<u8>) {
172+ let mut headers = HeaderMap::new();
173+ let location = if query.is_empty() { "/settings".to_string() } else { format!("/settings?{query}") };
174+ if let Ok(value) = HeaderValue::from_str(&location) {
175+ headers.insert(header::LOCATION, value);
176+ }
177+ (StatusCode::SEE_OTHER, headers, Vec::new())
178+}
179+
180+/// Where a save lands: back on Settings, with the refusal (if any) on the
181+/// query the same way `files.rs`'s upload carries one, or `saved=<call>`
182+/// when there was nothing to refuse.
183+fn saved_or_refused(call: &str, refusal: Option<Refusal>) -> (StatusCode, HeaderMap, Vec<u8>) {
184+ match refusal {
185+ Some(refusal) => redirect_to(&format!("refusal={}&on={call}", refusal.code())),
186+ None => redirect_to(&format!("saved={call}")),
187+ }
188+}
189+
190+// ---------------------------------------------------------------------------
191+// Routes
192+// ---------------------------------------------------------------------------
193+
194+#[derive(serde::Deserialize)]
195+struct SaveLimitsForm {
196+ attachment_limit_mb: u64,
197+ photo_limit_mb: u64,
198+ allowed_file_types: String,
199+}
200+
201+/// Changes the workspace's limits. Admin-only, checked here.
202+///
203+/// The list is parsed rather than trusted: it is what a later upload is
204+/// checked against, so a type that is not a plain extension has no business
205+/// being stored as one.
206+#[route(POST "/api/save_limits")]
207+async fn save_limits(cx: &Cx, Form(input): Form<SaveLimitsForm>) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
208+ let admin = match require_admin(cx).await {
209+ Ok(admin) => admin,
210+ Err(refusal) => return Ok(saved_or_refused("save_limits", Some(refusal))),
211+ };
212+ if input.attachment_limit_mb == 0
213+ || input.photo_limit_mb == 0
214+ || input.attachment_limit_mb > WIDEST_ATTACHMENT_MB
215+ || input.photo_limit_mb > WIDEST_PHOTO_MB
216+ {
217+ return Ok(saved_or_refused("save_limits", Some(Refusal::BadLimit)));
218+ }
219+ let Some(types) = parse_types(&input.allowed_file_types) else {
220+ return Ok(saved_or_refused("save_limits", Some(Refusal::BadFileType)));
221+ };
222+ let outcome = accounts(cx)
223+ .store()
224+ .set_limits(
225+ &admin.workspace_id,
226+ input.attachment_limit_mb * MB,
227+ input.photo_limit_mb * MB,
228+ &types,
229+ )
230+ .await;
231+ let refusal = match outcome {
232+ Ok(()) => None,
233+ Err(problem) => {
234+ eprintln!("store error: {problem}");
235+ Some(Refusal::Unavailable)
236+ }
237+ };
238+ Ok(saved_or_refused("save_limits", refusal))
239+}
240+
241+#[derive(serde::Deserialize)]
242+struct SaveSenderForm {
243+ host: String,
244+ port: u32,
245+ username: String,
246+ #[serde(default)]
247+ password: String,
248+ from_name: String,
249+ from_address: String,
250+}
251+
252+/// Writes the workspace's sender. Admin-only, checked here.
253+///
254+/// `password` is empty when the admin did not type one, and empty means
255+/// "leave the stored one alone" rather than "delete it": the field is
256+/// write-only, so the form has nothing to send back for a password that
257+/// already exists, and a save that took the blank literally would stop the
258+/// workspace sending mail as a side effect of fixing a typo in the port.
259+///
260+/// A sender with no password at all is refused rather than stored, because a
261+/// half-filled sender is not a configuration — it is a mail nobody receives
262+/// and a ledger nobody reads.
263+#[route(POST "/api/save_sender")]
264+async fn save_sender(cx: &Cx, Form(input): Form<SaveSenderForm>) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
265+ let admin = match require_admin(cx).await {
266+ Ok(admin) => admin,
267+ Err(refusal) => return Ok(saved_or_refused("save_sender", Some(refusal))),
268+ };
269+
270+ let host = input.host.trim().to_string();
271+ let username = input.username.trim().to_string();
272+ let from_name = input.from_name.trim().to_string();
273+ let from_address = input.from_address.trim().to_string();
274+ // Not typed is not the same as blanked. Nothing here can clear a stored
275+ // password; replacing it means typing a new one.
276+ let password = (!input.password.is_empty()).then_some(input.password);
277+
278+ let store = accounts(cx).store().clone();
279+ let known = store
280+ .workspace()
281+ .await?
282+ .map(|ws| ws.smtp_password_set)
283+ .unwrap_or(false);
284+
285+ let complaint = if host.is_empty() {
286+ Some("Give the SMTP host.")
287+ } else if host.contains(char::is_whitespace) || host.contains('@') || host.contains('/') {
288+ Some("The SMTP host is a host name, not an address or a URL.")
289+ } else if !(1..=65535).contains(&input.port) {
290+ Some("A port is a number between 1 and 65535.")
291+ } else if username.is_empty() {
292+ Some("Give the SMTP username.")
293+ } else if password.is_none() && !known {
294+ Some("A password is needed the first time.")
295+ } else if !is_address(&from_address) {
296+ Some("That is not a from-address.")
297+ } else {
298+ None
299+ };
300+ if let Some(problem) = complaint {
301+ return Ok(saved_or_refused(
302+ "save_sender",
303+ Some(Refusal::BadSender(problem.to_string())),
304+ ));
305+ }
306+
307+ let outcome = store
308+ .set_sender(
309+ &admin.workspace_id,
310+ NewSender {
311+ host,
312+ port: input.port,
313+ username,
314+ password,
315+ from_name,
316+ from_address,
317+ },
318+ )
319+ .await;
320+ let refusal = match outcome {
321+ Ok(()) => None,
322+ Err(problem) => {
323+ eprintln!("store error: {problem}");
324+ Some(Refusal::Unavailable)
325+ }
326+ };
327+ Ok(saved_or_refused("save_sender", refusal))
328+}
329+
330+/// Sends one mail to the admin who pressed the button, and writes down how it
331+/// went so the answer survives a reload.
332+///
333+/// It goes to their own address and nowhere else. A test that could be
334+/// pointed at an address somebody typed would be a way to make Izlek mail a
335+/// stranger on demand, which is a thing worth not building.
336+#[route(POST "/api/send_test_mail")]
337+async fn send_test_mail(cx: &Cx) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
338+ let admin = match require_admin(cx).await {
339+ Ok(admin) => admin,
340+ Err(refusal) => return Ok(saved_or_refused("send_test_mail", Some(refusal))),
341+ };
342+
343+ let store = accounts(cx).store().clone();
344+ let configured = store
345+ .workspace()
346+ .await?
347+ .is_some_and(|ws| ws.smtp_password_set && ws.smtp_host.is_some());
348+ if !configured {
349+ return Ok(saved_or_refused(
350+ "send_test_mail",
351+ Some(Refusal::BadSender(
352+ "Fill the sender in and save it first — there is nothing to test yet.".to_string(),
353+ )),
354+ ));
355+ }
356+
357+ let Some(outcome) = mail(cx).test(&admin.email).await else {
358+ // No engine in this process at all. Nothing sends here, and saying so
359+ // beats writing down a failure the settings did not cause.
360+ return Ok(saved_or_refused("send_test_mail", Some(Refusal::Unavailable)));
361+ };
362+
363+ let at = time::OffsetDateTime::now_utc();
364+ let test = match outcome {
365+ Ok(took) => SenderTest {
366+ at,
367+ took_ms: took.whole_milliseconds().max(0) as u64,
368+ error: None,
369+ },
370+ Err(problem) => SenderTest {
371+ at,
372+ took_ms: 0,
373+ // The mailer builds this from what the server said, never from
374+ // the credentials it sent, so it is safe to store and to show.
375+ error: Some(problem.message.clone()),
376+ },
377+ };
378+ if let Err(problem) = store.record_sender_test(&admin.workspace_id, test).await {
379+ eprintln!("store error: {problem}");
380+ return Ok(saved_or_refused("send_test_mail", Some(Refusal::Unavailable)));
381+ }
382+ Ok(saved_or_refused("send_test_mail", None))
383+}
384+
385+#[derive(serde::Deserialize)]
386+struct SaveProfileForm {
387+ display_name: String,
388+}
389+
390+/// Renames the person asking. Nobody renames anybody else here: the id comes
391+/// from the session, never from the form.
392+#[route(POST "/api/save_profile")]
393+async fn save_profile(cx: &Cx, Form(input): Form<SaveProfileForm>) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
394+ let user = match require_user(cx).await {
395+ Ok(user) => user,
396+ Err(refusal) => return Ok(saved_or_refused("save_profile", Some(refusal))),
397+ };
398+ let display_name = input.display_name.trim().to_string();
399+ if display_name.is_empty() {
400+ return Ok(saved_or_refused("save_profile", Some(Refusal::EmptyName)));
401+ }
402+ let outcome = accounts(cx)
403+ .store()
404+ .set_profile(&user.id, &display_name, user.photo_path.as_deref())
405+ .await;
406+ let refusal = match outcome {
407+ Ok(()) => None,
408+ Err(problem) => {
409+ eprintln!("store error: {problem}");
410+ Some(Refusal::Unavailable)
411+ }
412+ };
413+ Ok(saved_or_refused("save_profile", refusal))
414+}
415+
416+#[derive(serde::Deserialize)]
417+struct ResendLinkForm {
418+ user_id: String,
419+}
420+
421+/// Sends the same person another first-sign-in link by mail. Admin-only,
422+/// checked here.
423+///
424+/// There is no hydrated action here to read a return value off of, so the
425+/// mailed address travels home on the redirect's query, the same way a
426+/// refusal does.
427+#[route(POST "/api/resend_link")]
428+async fn resend_link(cx: &Cx, Form(input): Form<ResendLinkForm>) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
429+ let admin = match require_admin(cx).await {
430+ Ok(admin) => admin,
431+ Err(refusal) => return Ok(saved_or_refused("resend_link", Some(refusal))),
432+ };
433+ match accounts(cx).resend_invitation(&admin, &input.user_id).await {
434+ Ok(invitation) => {
435+ mail(cx).after_invite();
436+ Ok(redirect_to(&format!("mailed={}", encode_q(&invitation.user.email))))
437+ }
438+ Err(error) => Ok(saved_or_refused("resend_link", Some(error.into()))),
439+ }
440+}
441+
442+// ---------------------------------------------------------------------------
443+// Page
444+// ---------------------------------------------------------------------------
445+
446+/// One row of the member list, as an admin may see it. There is no password
447+/// and no token here: whether a password exists is a fact about the account,
448+/// and the token of a live link is shown once at the moment it is minted and
449+/// is never readable afterwards — the store keeps only its hash.
450+struct Member {
451+ id: String,
452+ display_name: String,
453+ email: String,
454+ role: izlek_core::Role,
455+ has_password: bool,
456+ /// The day they last signed in, as the list writes it, or nothing.
457+ last_signed_in: Option<String>,
458+ is_you: bool,
459+ /// The first account. It administers the workspace and cannot be
460+ /// removed.
461+ is_owner: bool,
462+}
463+
464+async fn members_now(cx: &Cx, asking: &User) -> Result<Vec<Member>> {
465+ let store = accounts(cx).store().clone();
466+ let owner = store.owner().await?.map(|owner| owner.id);
467+ let users = store.users(&asking.workspace_id).await?;
468+ Ok(users
469+ .into_iter()
470+ .map(|user| Member {
471+ has_password: user.password_hash.is_some(),
472+ last_signed_in: user.last_signed_in_at.map(|at| izlek_core::board::day_label(at.date())),
473+ is_you: user.id == asking.id,
474+ is_owner: owner.as_deref() == Some(user.id.as_str()),
475+ id: user.id,
476+ display_name: user.display_name,
477+ email: user.email,
478+ role: user.role,
479+ })
480+ .collect())
481+}
482+
483+async fn limits_now(cx: &Cx, workspace_id: &str) -> Result<(u64, u64, Vec<String>)> {
484+ let workspace = accounts(cx)
485+ .store()
486+ .workspace()
487+ .await?
488+ .filter(|workspace| workspace.id == workspace_id)
489+ .ok_or_else(|| topcoat::Error::from(std::io::Error::other("no workspace")))?;
490+ Ok((
491+ workspace.attachment_limit_bytes / MB,
492+ workspace.photo_limit_bytes / MB,
493+ workspace.allowed_file_types,
494+ ))
495+}
496+
497+/// What the row under the test button says, once the workspace holds a
498+/// `sender_test` to read.
499+struct TestResult {
500+ moment: String,
501+ took: Option<String>,
502+ error: Option<String>,
503+}
504+
505+/// The sender as the admin's screen may see it, plus the last test's
506+/// outcome — persisted, so it survives the reload the redirect gives it
507+/// rather than living only in this request's memory.
508+struct Sender {
509+ host: String,
510+ port: u16,
511+ username: String,
512+ from_name: String,
513+ from_address: String,
514+ password_set: bool,
515+ test: Option<TestResult>,
516+}
517+
518+impl Sender {
519+ fn is_connected(&self) -> bool {
520+ !self.host.trim().is_empty()
521+ && !self.username.trim().is_empty()
522+ && !self.from_address.trim().is_empty()
523+ && self.password_set
524+ }
525+}
526+
527+async fn sender_now(cx: &Cx) -> Result<Sender> {
528+ let workspace = accounts(cx).store().workspace().await?;
529+ Ok(match workspace {
530+ None => Sender {
531+ host: String::new(),
532+ port: 587,
533+ username: String::new(),
534+ from_name: String::new(),
535+ from_address: String::new(),
536+ password_set: false,
537+ test: None,
538+ },
539+ Some(workspace) => Sender {
540+ host: workspace.smtp_host.unwrap_or_default(),
541+ port: workspace.smtp_port.and_then(|p| u16::try_from(p).ok()).unwrap_or(587),
542+ username: workspace.smtp_username.unwrap_or_default(),
543+ from_name: workspace.smtp_from_name.unwrap_or_default(),
544+ from_address: workspace.smtp_from_address.unwrap_or_default(),
545+ password_set: workspace.smtp_password_set,
546+ test: workspace.sender_test.map(|test| TestResult {
547+ moment: izlek_core::detail::moment_label(test.at),
548+ took: test.error.is_none().then(|| took_label(test.took_ms)),
549+ error: test.error,
550+ }),
551+ },
552+ })
553+}
554+
555+/// The refusal that landed on this call's redirect, if any, and this call's
556+/// own `saved=<call>` flag.
557+fn call_state<'q>(query: &'q str, call: &str) -> (Option<Refusal>, bool) {
558+ let mut refusal_code = None;
559+ let mut on = None;
560+ let mut saved = false;
561+ for pair in query.split('&') {
562+ let Some((key, value)) = pair.split_once('=') else { continue };
563+ match key {
564+ "refusal" => refusal_code = Some(value),
565+ "on" => on = Some(value),
566+ "saved" if value == call => saved = true,
567+ _ => {}
568+ }
569+ }
570+ let refusal = if on == Some(call) { refusal_code.and_then(Refusal::from_code) } else { None };
571+ (refusal, saved)
572+}
573+
574+fn query_value<'q>(query: &'q str, key: &str) -> Option<&'q str> {
575+ query.split('&').find_map(|pair| pair.split_once('=').filter(|(k, _)| *k == key).map(|(_, v)| v))
576+}
577+
578+/// The settings screen.
579+#[page("/settings")]
580+async fn settings_page(cx: &Cx) -> Result {
581+ let user = match require_user(cx).await {
582+ Ok(user) => user,
583+ Err(refusal) => {
584+ return view! {
585+ cx =>
586+ <main class="scaffold-note">
587+ <p>(refusal.message())</p>
588+ <p><a href="/">"Back to the board"</a></p>
589+ </main>
590+ };
591+ }
592+ };
593+ let administers = user.role.can_administer();
594+ let query = topcoat::router::request::uri(cx).query().unwrap_or("");
595+
596+ let sender = if administers { Some(sender_now(cx).await?) } else { None };
597+ let (limits, allowed_types) = if administers {
598+ let (attachment, photo, types) = limits_now(cx, &user.workspace_id).await?;
599+ (Some((attachment, photo)), types)
600+ } else {
601+ (None, Vec::new())
602+ };
603+ let members = if administers { Some(members_now(cx, &user).await?) } else { None };
604+
605+ let (profile_refusal, profile_saved) = call_state(query, "save_profile");
606+ let (sender_refusal, sender_saved) = call_state(query, "save_sender");
607+ let (test_refusal, _) = call_state(query, "send_test_mail");
608+ let (limits_refusal, limits_saved) = call_state(query, "save_limits");
609+ let (member_refusal, _) = call_state(query, "resend_link");
610+ let mailed = query_value(query, "mailed").map(decode_q);
611+
612+ view! {
613+ cx =>
614+ <header class="topbar">
615+ <div class="wordmark">
616+ <span class="wordmark-text">"izlek"</span>
617+ <span class="wordmark-dot"></span>
618+ </div>
619+ <div class="topbar-divider"></div>
620+ <span class="board-name">"Settings"</span>
621+ <div class="spacer"></div>
622+ <span class="topbar-who" title=(user.email.clone())>(user.display_name.clone())</span>
623+ </header>
624+
625+ <div class="settings-shell">
626+ <nav class="sidenav">
627+ <a class="sidenav-item" href="/">"Board"</a>
628+ <a class="sidenav-item" href="/rules">"Mail rules"</a>
629+ <a class="sidenav-item" href="/logs">"Logs"</a>
630+ <a class="sidenav-item sidenav-item-on" href="/settings">"Settings"</a>
631+ </nav>
632+
633+ <main class="settings-stage">
634+ <div class="settings-head">
635+ <h1 class="settings-title">"Settings"</h1>
636+ <span class="chip chip-role">(user.role.as_str().to_string())</span>
637+ </div>
638+
639+ <section class="panel">
640+ <div class="panel-head">
641+ <h2 class="panel-title">"Your profile"</h2>
642+ </div>
643+ <form method="post" action="/api/save_profile" class="panel-body">
644+ <label class="field">
645+ <span class="field-label">"DISPLAY NAME"</span>
646+ <input
647+ class="field-input"
648+ type="text"
649+ name="display_name"
650+ value=(user.display_name.clone())
651+ maxlength="80"
652+ required=""
653+ >
654+ </label>
655+ <label class="field">
656+ <span class="field-label">"EMAIL"</span>
657+ <input class="field-input" type="email" value=(user.email.clone()) disabled="">
658+ </label>
659+ <div class="panel-foot">
660+ if let Some(refusal) = &profile_refusal {
661+ <span class="field-error">(refusal.message())</span>
662+ }
663+ if profile_saved {
664+ <span class="field-note">"Saved."</span>
665+ }
666+ <button class="primary" type="submit">"Save"</button>
667+ </div>
668+ </form>
669+ <div class="panel-body panel-foot panel-foot-split">
670+ <form method="post" action="/api/sign_out">
671+ <button class="quiet" type="submit">"Sign out"</button>
672+ </form>
673+ </div>
674+ </section>
675+
676+ if let Some(sender) = &sender {
677+ let connected = sender.is_connected();
678+ let password_set = sender.password_set;
679+ <section class="panel">
680+ <div class="panel-head">
681+ <h2 class="panel-title">"Outgoing mail"</h2>
682+ <span class="chip chip-admin">"Admin only"</span>
683+ if connected {
684+ <span class="chip chip-connected">"Connected"</span>
685+ } else {
686+ <span class="chip chip-off">"Not configured"</span>
687+ }
688+ </div>
689+ <div class="panel-body">
690+ if !connected {
691+ <p class="panel-lede">"Not connected — mail queues until you save."</p>
692+ }
693+ <form method="post" action="/api/save_sender" id="sender-settings">
694+ <div class="field-row">
695+ <label class="field">
696+ <span class="field-label">"SMTP HOST"</span>
697+ <input
698+ class="field-input"
699+ type="text"
700+ name="host"
701+ value=(sender.host.clone())
702+ placeholder="smtp.fastmail.com"
703+ >
704+ </label>
705+ <label class="field field-narrow">
706+ <span class="field-label">"PORT"</span>
707+ <input
708+ class="field-input"
709+ type="number"
710+ name="port"
711+ min="1"
712+ max="65535"
713+ value=(sender.port.to_string())
714+ >
715+ </label>
716+ </div>
717+ <label class="field">
718+ <span class="field-label">"USERNAME"</span>
719+ <input class="field-input" type="text" name="username" value=(sender.username.clone())>
720+ </label>
721+ <label class="field">
722+ <span class="field-label">"PASSWORD"</span>
723+ <input
724+ class="field-input"
725+ type="password"
726+ name="password"
727+ autocomplete="off"
728+ placeholder=(if password_set { "Set — type a new one to replace it" } else { "Needed before anything can be sent" })
729+ >
730+ </label>
731+ <div class="field-row">
732+ <label class="field">
733+ <span class="field-label">"FROM NAME"</span>
734+ <input
735+ class="field-input"
736+ type="text"
737+ name="from_name"
738+ value=(sender.from_name.clone())
739+ placeholder="Izlek"
740+ >
741+ </label>
742+ <label class="field">
743+ <span class="field-label">"FROM ADDRESS"</span>
744+ <input
745+ class="field-input"
746+ type="text"
747+ name="from_address"
748+ value=(sender.from_address.clone())
749+ placeholder="board@izlek.sh"
750+ >
751+ </label>
752+ </div>
753+ </form>
754+ <div class="panel-foot panel-foot-split">
755+ <div class="foot-side">
756+ <form method="post" action="/api/send_test_mail">
757+ <button class="quiet" type="submit">"Send test mail to myself"</button>
758+ </form>
759+ match (&test_refusal, &sender.test) {
760+ (Some(refusal), _) => <span class="field-error">(refusal.message())</span>,
761+ (None, Some(result)) => match (&result.error, &result.took) {
762+ (Some(problem), _) => <span class="field-error">(format!("not delivered, {} — {problem}", result.moment))</span>,
763+ (None, Some(took)) => <span class="field-note">(format!("delivered in {took} — {}", result.moment))</span>,
764+ (None, None) => "",
765+ },
766+ (None, None) => "",
767+ }
768+ </div>
769+ <div class="foot-side">
770+ if let Some(refusal) = &sender_refusal {
771+ <span class="field-error">(refusal.message())</span>
772+ }
773+ if sender_saved {
774+ <span class="field-note">"Saved."</span>
775+ }
776+ <button class="primary" type="submit" form="sender-settings">"Save"</button>
777+ </div>
778+ </div>
779+ </div>
780+ </section>
781+ }
782+
783+ if let Some((attachment_limit_mb, photo_limit_mb)) = limits {
784+ <section class="panel">
785+ <div class="panel-head">
786+ <h2 class="panel-title">"Workspace limits"</h2>
787+ <span class="chip chip-admin">"Admin only"</span>
788+ </div>
789+ <form method="post" action="/api/save_limits" class="panel-body">
790+ <div class="field-row">
791+ <label class="field">
792+ <span class="field-label">"ATTACHMENT LIMIT (MB)"</span>
793+ <input
794+ class="field-input"
795+ type="number"
796+ name="attachment_limit_mb"
797+ min="1"
798+ max=(WIDEST_ATTACHMENT_MB.to_string())
799+ value=(attachment_limit_mb.to_string())
800+ required=""
801+ >
802+ </label>
803+ <label class="field">
804+ <span class="field-label">"PHOTO LIMIT (MB)"</span>
805+ <input
806+ class="field-input"
807+ type="number"
808+ name="photo_limit_mb"
809+ min="1"
810+ max=(WIDEST_PHOTO_MB.to_string())
811+ value=(photo_limit_mb.to_string())
812+ required=""
813+ >
814+ </label>
815+ </div>
816+ <label class="field">
817+ <span class="field-label">"ALLOWED FILE TYPES"</span>
818+ <input
819+ class="field-input"
820+ type="text"
821+ name="allowed_file_types"
822+ value=(allowed_types.join(", "))
823+ placeholder="png, jpg, pdf, zip"
824+ >
825+ </label>
826+ <p class="panel-lede">"A lower limit never touches files already uploaded."</p>
827+ <div class="panel-foot">
828+ if let Some(refusal) = &limits_refusal {
829+ <span class="field-error">(refusal.message())</span>
830+ }
831+ if limits_saved {
832+ <span class="field-note">"Saved."</span>
833+ }
834+ <button class="primary" type="submit">"Save"</button>
835+ </div>
836+ </form>
837+ </section>
838+ }
839+
840+ if let Some(members) = members {
841+ <section class="panel">
842+ <div class="panel-head">
843+ <h2 class="panel-title">"Members"</h2>
844+ <span class="chip chip-admin">"Admin only"</span>
845+ </div>
846+ <div class="panel-body">
847+ <table class="member-table">
848+ <thead>
849+ <tr>
850+ <th>"NAME"</th>
851+ <th>"ADDRESS"</th>
852+ <th>"ROLE"</th>
853+ <th>"ACCOUNT"</th>
854+ </tr>
855+ </thead>
856+ <tbody>
857+ for member in members {
858+ let account = if member.is_owner {
859+ "owner".to_string()
860+ } else if !member.has_password {
861+ "invited".to_string()
862+ } else if let Some(day) = member.last_signed_in.clone() {
863+ format!("last seen {day}")
864+ } else {
865+ "active".to_string()
866+ };
867+ <tr class="member-row">
868+ <td class="member-name">
869+ (member.display_name.clone())
870+ if member.is_you {
871+ <span class="member-you">"you"</span>
872+ }
873+ </td>
874+ <td class="member-address">(member.email.clone())</td>
875+ <td><span class="chip chip-role">(member.role.as_str().to_string())</span></td>
876+ <td class="member-account">
877+ (account)
878+ if !member.has_password {
879+ <form method="post" action="/api/resend_link" class="member-resend">
880+ <input type="hidden" name="user_id" value=(member.id.clone())>
881+ <button class="quiet" type="submit">"Resend mail"</button>
882+ </form>
883+ }
884+ </td>
885+ </tr>
886+ }
887+ </tbody>
888+ </table>
889+
890+ // `/api/invite_member` (auth.rs) answers a caller
891+ // with script, not this post, so a submit here
892+ // lands on its bare JSON rather than back on this
893+ // page.
894+ // corner-cut: no "Mailed to {address}" after
895+ // Add member, ceiling = give invite_member the
896+ // same redirect-carried answer `resend_link`
897+ // above uses, in a slice that may touch auth.rs.
898+ <form method="post" action="/api/invite_member" class="member-invite">
899+ <label class="field">
900+ <span class="field-label">"NAME"</span>
901+ <input class="field-input" type="text" name="display_name" maxlength="80" required="">
902+ </label>
903+ <label class="field">
904+ <span class="field-label">"ADDRESS"</span>
905+ <input class="field-input" type="email" name="email" required="">
906+ </label>
907+ <label class="field field-role">
908+ <span class="field-label">"ROLE"</span>
909+ <select class="field-input" name="role">
910+ <option value="member">"Member"</option>
911+ <option value="viewer">"Viewer"</option>
912+ <option value="admin">"Admin"</option>
913+ </select>
914+ </label>
915+ <button class="primary" type="submit">"Add member"</button>
916+ </form>
917+
918+ if let Some(refusal) = &member_refusal {
919+ <p class="field-error">(refusal.message())</p>
920+ }
921+ if let Some(address) = &mailed {
922+ <p class="field-note">(format!("Mailed to {address}"))</p>
923+ }
924+
925+ <div class="role-note">
926+ <p class="panel-lede"><b>"Admin"</b>" — sender, limits, members."</p>
927+ <p class="panel-lede"><b>"Member"</b>" — board and rule mail."</p>
928+ <p class="panel-lede"><b>"Viewer"</b>" — read and export only."</p>
929+ </div>
930+ </div>
931+ </section>
932+ }
933+ </main>
934+ </div>
935+ }
936+}