steid

@jamesgill /

Rust26.3 KBCode·Blame·History·Raw
1//! Settings for a handle — `/{handle}/settings`.
2//!
3//! Owner only. Authorization is the use case's decision, not this module's; the page
4//! only chooses how to render the answer.
5//!
6//! **One route, two pages.** A handle is a person or an organisation, and which one is
7//! [derived](crate::application::is_personal_org) rather than stored — an organisation
8//! is personal exactly when some user's `personal_org_id` points at it. A person's
9//! settings carry their password, their tokens and the instance backup; an
10//! organisation's carry its profile and whether it is the home page. Giving an
11//! organisation a second copy of the profile form at a URL of its own would be two
12//! forms writing one row, so the page branches instead of the route.
13
14use std::time::SystemTime;
15
16use serde::Deserialize;
17use topcoat::{
18 Result,
19 context::Cx,
20 router::{
21 IntoResponse, Response, StatusCode, content::Form, error::not_found, error::see_other,
22 page, query_params, route,
23 },
24 session,
25 view::{attributes, component, view},
26};
27
28use crate::{
29 application::{Error, change_password, set_home_by_handle, update_profile},
30 components::{
31 button::button,
32 flash::{FlashKind, flash},
33 input::input,
34 label::label,
35 textarea::textarea,
36 },
37 domain::{DomainError, OrgName, Organization, Password, SessionTokenHash},
38};
39
40use super::{
41 backup::{backup_url, last_scheduled_backup},
42 context::{
43 current_actor, hex, instance_owner, instance_settings, location, memberships, orgs,
44 owned_profile, resets, server_error, sessions, users,
45 },
46 csrf::{CsrfGuard, csrf_field, csrf_verified, csrf_verified_response},
47 format::{ago, optional, timestamp},
48 layout::narrow,
49 org::{home, is_personal},
50 password::refusal_code,
51};
52
53/// What the Backup section has to say.
54///
55/// Two independent facts, and the section is drawn from both: whether *this* viewer may
56/// take a backup at all, and when the machine last took one by itself. Neither implies
57/// the other — a schedule runs whether anybody is signed in or not.
58#[derive(Debug, Clone, Copy, Default)]
59struct BackupState {
60 /// Whether the viewer is the instance's owner, which is stricter than owning this
61 /// profile — see [`instance_owner`](super::context::instance_owner).
62 downloadable: bool,
63 /// When the configured timer last ran. `None` covers both "no timer" and "a timer
64 /// that has never completed", which look the same from here and mean the same thing
65 /// to whoever is reading the page: no backup has been taken for you.
66 last_scheduled: Option<SystemTime>,
67}
68
69async fn backup_state(cx: &Cx) -> Result<BackupState> {
70 Ok(BackupState {
71 downloadable: instance_owner(cx).await?,
72 last_scheduled: last_scheduled_backup(cx),
73 })
74}
75
76#[derive(Debug, Deserialize)]
77struct ProfileForm {
78 /// The hidden field every form carries; see [`csrf`](super::csrf).
79 ///
80 /// `default` so that a submission with no token at all is refused by
81 /// `csrf_verified` — a 403 saying what happened — rather than failing
82 /// deserialization into a bare 400 that says nothing.
83 #[serde(default)]
84 csrf_token: String,
85 display_name: String,
86 bio: String,
87}
88
89/// Set after a successful save so the confirmation survives the redirect.
90///
91/// Post-redirect-get: reloading after a save must not resubmit it.
92#[query_params(error = bad_request)]
93struct Saved {
94 saved: Option<String>,
95}
96
97/// How the last password change went, as it travels through the redirect.
98#[query_params(error = bad_request)]
99struct PasswordOutcome {
100 password: Option<String>,
101}
102
103/// The password section's three fields.
104#[derive(Debug, Deserialize)]
105struct PasswordForm {
106 /// The hidden field every form carries; see [`csrf`](super::csrf).
107 ///
108 /// `default` so that a submission with no token at all is refused by
109 /// `csrf_verified` — a 403 saying what happened — rather than failing
110 /// deserialization into a bare 400 that says nothing.
111 #[serde(default)]
112 csrf_token: String,
113 current: String,
114 password: String,
115 confirmation: String,
116}
117
118/// The refusal a code stands for.
119///
120/// A closed set rather than the message itself, for the reason `web::password` gives:
121/// a message carried in a URL is a message a stranger can put on the page.
122fn password_message(code: Option<&str>) -> (FlashKind, &'static str) {
123 match code {
124 Some("changed") => (
125 FlashKind::Success,
126 "Password changed. Every other device has been signed out.",
127 ),
128 Some("wrong") => (FlashKind::Error, "That is not your current password."),
129 Some("mismatch") => (FlashKind::Error, "Those two new passwords are different."),
130 // The one sentence, from the one place — see `Password`. `web::password` shows
131 // the same words on the reset page.
132 Some("short") => (FlashKind::Error, Password::RULE),
133 Some("long") => (FlashKind::Error, "That password is too long to hash."),
134 Some(_) => (FlashKind::Error, "That did not work. Try again."),
135 None => (FlashKind::Info, ""),
136 }
137}
138
139/// Whether this handle is already where the root URL lands.
140///
141/// Compared by handle rather than by id because that is what the page has, and because
142/// [`home`](super::org::home) answers the same question the root does — so a page that
143/// says "this is the home page" is saying something a visitor can check by typing `/`.
144async fn is_home(cx: &Cx, handle: &OrgName) -> Result<bool> {
145 Ok(home(cx).await?.as_ref() == Some(handle))
146}
147
148/// Set after the home page moved, so the confirmation survives the redirect.
149#[query_params(error = bad_request)]
150struct HomeOutcome {
151 home: Option<String>,
152}
153
154#[page("/{handle}/settings")]
155async fn settings_page(cx: &Cx) -> Result {
156 let profile = owned_profile(cx).await?;
157
158 let saved = query_params::<Saved>(cx)?.saved.is_some();
159 let home_moved = query_params::<HomeOutcome>(cx)?.home.is_some();
160 let here_is_home = is_home(cx, &profile.handle).await?;
161
162 if !is_personal(cx, &profile.handle).await? {
163 return view! {
164 org_settings_form(
165 handle: profile.handle.as_str(),
166 display_name: profile.display_name.as_deref().unwrap_or(""),
167 bio: profile.bio.as_deref().unwrap_or(""),
168 saved: saved,
169 error: "",
170 home: HomeState { is_home: here_is_home, moved: home_moved },
171 )
172 };
173 }
174
175 let backups = backup_state(cx).await?;
176 let password = query_params::<PasswordOutcome>(cx)?.password.clone();
177
178 view! {
179 settings_form(
180 handle: profile.handle.as_str(),
181 // The stored display name, not the label: the label falls back to the
182 // handle, which would put text in a field the owner never typed.
183 display_name: profile.display_name.as_deref().unwrap_or(""),
184 bio: profile.bio.as_deref().unwrap_or(""),
185 saved: saved,
186 error: "",
187 sections: Sections {
188 backups: &backups,
189 password: password.as_deref(),
190 home: HomeState { is_home: here_is_home, moved: home_moved },
191 },
192 )
193 }
194}
195
196/// Points the root URL at this handle.
197///
198/// A `#[route]`, not a `#[page]`: there is one button and nothing to re-render with
199/// what was typed, so the outcome travels as `?home` and the settings page says it.
200/// The use case decides who may — owning the organisation being pointed at — and a
201/// refusal is the 404 every owner-only page here gives.
202#[route(POST "/{handle}/settings/home")]
203async fn make_home(cx: &Cx, Form(guard): Form<CsrfGuard>) -> Result<Response> {
204 if let Some(response) = csrf_verified_response(cx, &guard.csrf_token).await? {
205 return Ok(response);
206 }
207
208 let profile = owned_profile(cx).await?;
209
210 match set_home_by_handle(
211 &current_actor(cx).await?,
212 &profile.handle,
213 &orgs(cx),
214 &memberships(cx),
215 &users(cx),
216 &instance_settings(cx),
217 )
218 .await
219 {
220 Ok(()) => {}
221 Err(Error::Domain(DomainError::Forbidden | DomainError::NotFound { .. })) => {
222 return Err(not_found().into());
223 }
224 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
225 }
226
227 see_other(&format!("/{}/settings?home", profile.handle)).into_response(cx)
228}
229
230/// Applies an edit.
231///
232/// Success replies 303, so a reload cannot resubmit — see [`location`] for why it is
233/// spelled this way and not with `redirect()`, which is a 307 and would re-POST this
234/// form to itself.
235///
236/// Failure re-renders with the message and **what was typed** — bouncing back to a
237/// blank form would throw away the work and leave the reason invisible, which is the
238/// whole problem `flash` exists to fix.
239#[page(POST "/{handle}/settings")]
240async fn save(cx: &Cx, Form(submitted): Form<ProfileForm>) -> Result {
241 csrf_verified(cx, &submitted.csrf_token).await?;
242
243 let profile = owned_profile(cx).await?;
244 let personal = is_personal(cx, &profile.handle).await?;
245 let here_is_home = is_home(cx, &profile.handle).await?;
246
247 let outcome = update_profile(
248 &current_actor(cx).await?,
249 &profile.handle,
250 optional(&submitted.display_name),
251 optional(&submitted.bio),
252 &orgs(cx),
253 &memberships(cx),
254 )
255 .await;
256
257 let message = match outcome {
258 Ok(()) => {
259 return view! {
260 (StatusCode::SEE_OTHER)
261 (location(&format!("/{}/settings?saved", profile.handle))?)
262 };
263 }
264 // The visitor's to fix, so it is shown.
265 Err(Error::Domain(DomainError::Validation { field, reason })) => {
266 format!("That {field} is no good: {reason}.")
267 }
268 Err(Error::Domain(DomainError::Forbidden)) => return Err(not_found().into()),
269 // Ours, so it is logged and answered generically.
270 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
271 };
272
273 let home = HomeState {
274 is_home: here_is_home,
275 moved: false,
276 };
277
278 if !personal {
279 return view! {
280 org_settings_form(
281 handle: profile.handle.as_str(),
282 display_name: submitted.display_name.as_str(),
283 bio: submitted.bio.as_str(),
284 saved: false,
285 error: message.as_str(),
286 home: home,
287 )
288 };
289 }
290
291 let backups = backup_state(cx).await?;
292
293 view! {
294 settings_form(
295 handle: profile.handle.as_str(),
296 display_name: submitted.display_name.as_str(),
297 bio: submitted.bio.as_str(),
298 saved: false,
299 error: message.as_str(),
300 sections: Sections { backups: &backups, password: None, home },
301 )
302 }
303}
304
305/// Changes the owner's password.
306///
307/// Not rate limited: reaching it needs a session, so the budget it would spend belongs
308/// to the person already signed in. The guessing this would otherwise enable is
309/// guessing your own password on your own browser.
310///
311/// A `#[route]` rather than a `#[page]` because there is nothing to re-render — three
312/// password fields, none of which a browser should be handed back. The outcome travels
313/// as `?password=` and the settings page renders the message; a redirect that usually
314/// discards what was typed discards nothing here.
315#[route(POST "/{handle}/settings/password")]
316async fn change(cx: &Cx, Form(submitted): Form<PasswordForm>) -> Result<Response> {
317 if let Some(response) = csrf_verified_response(cx, &submitted.csrf_token).await? {
318 return Ok(response);
319 }
320
321 let profile = owned_profile(cx).await?;
322
323 // The session doing the changing, spared so the owner is not signed out of the
324 // browser they are looking at. Absent only if the cookie went between the page
325 // rendering and the form arriving, in which case every session goes — which is the
326 // safe way to be wrong.
327 let here = session::token_hash(cx)
328 .await?
329 .map(|hash| SessionTokenHash::from_trusted(hex(&hash)));
330
331 let outcome = change_password(
332 &current_actor(cx).await?,
333 &submitted.current,
334 &submitted.password,
335 &submitted.confirmation,
336 here.as_ref(),
337 SystemTime::now(),
338 &users(cx),
339 &resets(cx),
340 &sessions(cx),
341 &crate::infrastructure::password::Argon2Hasher::new(),
342 )
343 .await;
344
345 let code = match outcome {
346 Ok(()) => "changed",
347 Err(Error::Domain(DomainError::InvalidCredentials)) => "wrong",
348 Err(Error::Domain(DomainError::Validation { reason, .. })) => refusal_code(&reason),
349 Err(Error::Domain(DomainError::Forbidden)) => return Err(not_found().into()),
350 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
351 };
352
353 see_other(&format!("/{}/settings?password={code}", profile.handle)).into_response(cx)
354}
355
356/// The edit form.
357///
358/// Values arrive as parameters rather than being read back from storage, so a rejected
359/// submission can re-render exactly what was typed.
360/// The two sections below the profile form, as one value: a `#[component]` drops outer
361/// attributes, so an eighth parameter is a clippy warning with no way to silence it.
362#[derive(Debug, Clone, Copy)]
363struct Sections<'a> {
364 backups: &'a BackupState,
365 /// The `?password=` code from the last change, or `None` for a page nobody has
366 /// submitted that form to.
367 password: Option<&'a str>,
368 home: HomeState,
369}
370
371/// What the Home section has to say.
372///
373/// Shown on both settings pages, because both kinds of handle can be the front door:
374/// "Just me" in the setup wizard points the root at a person's own page, and without
375/// this there would be no way back to it once an organisation had taken it.
376#[derive(Debug, Clone, Copy)]
377struct HomeState {
378 /// Whether the root URL already lands here.
379 is_home: bool,
380 /// Whether it landed here as a result of the submission that redirected to this
381 /// page, so the confirmation survives the redirect.
382 moved: bool,
383}
384
385#[component]
386async fn settings_form(
387 handle: &str,
388 display_name: &str,
389 bio: &str,
390 saved: bool,
391 error: &str,
392 sections: Sections<'_>,
393) -> Result {
394 let Sections {
395 backups,
396 password,
397 home,
398 } = sections;
399 let (password_kind, password_text) = password_message(password);
400
401 view! {
402 narrow(
403 <h1 class="text-xl font-semibold tracking-tight">"Profile settings"</h1>
404 <p class="mt-1 font-mono text-sm text-muted-foreground">"@" (handle)</p>
405
406 if saved {
407 <div class="mt-6">
408 flash(kind: FlashKind::Success, "Profile updated.")
409 </div>
410 }
411
412 if !error.is_empty() {
413 <div class="mt-6">
414 flash(kind: FlashKind::Error, (error))
415 </div>
416 }
417
418 <form method="post" action=(format!("/{handle}/settings")) class="mt-6 space-y-5">
419 csrf_field()
420 <div class="space-y-2">
421 label(attrs: attributes! { for="display_name" }, "Display name")
422 input(attrs: attributes! {
423 id="display_name"
424 name="display_name"
425 type="text"
426 value=(display_name)
427 placeholder=(handle)
428 })
429 <p class="text-xs text-muted-foreground">
430 "Shown instead of your handle. Leave blank to use @" (handle) "."
431 </p>
432 </div>
433
434 <div class="space-y-2">
435 label(attrs: attributes! { for="bio" }, "Bio")
436 textarea(
437 attrs: attributes! {
438 id="bio"
439 name="bio"
440 rows="4"
441 maxlength=(Organization::MAX_BIO_LEN.to_string())
442 },
443 (bio)
444 )
445 <p class="text-xs text-muted-foreground">
446 "At most " (Organization::MAX_BIO_LEN.to_string()) " characters."
447 </p>
448 </div>
449
450 <div class="flex items-center gap-3">
451 button(attrs: attributes! { type="submit" }, "Save")
452 <a
453 href=(format!("/{handle}"))
454 class="text-sm text-muted-foreground hover:text-foreground"
455 >"Back to profile"</a>
456 </div>
457 </form>
458
459 <section class="mt-10 border-t border-border pt-6">
460 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
461 "Password"
462 </h2>
463
464 if !password_text.is_empty() {
465 <div class="mt-3">
466 flash(kind: password_kind, (password_text))
467 </div>
468 }
469
470 <form
471 method="post"
472 action=(format!("/{handle}/settings/password"))
473 class="mt-4 max-w-sm space-y-4"
474 >
475 csrf_field()
476 <div class="space-y-2">
477 label(attrs: attributes! { for="current" }, "Current password")
478 input(attrs: attributes! {
479 id="current"
480 name="current"
481 type="password"
482 autocomplete="current-password"
483 required=(true)
484 })
485 </div>
486 <div class="space-y-2">
487 label(attrs: attributes! { for="password" }, "New password")
488 input(attrs: attributes! {
489 id="password"
490 name="password"
491 type="password"
492 autocomplete="new-password"
493 required=(true)
494 })
495 </div>
496 <div class="space-y-2">
497 label(attrs: attributes! { for="confirmation" }, "New password again")
498 input(attrs: attributes! {
499 id="confirmation"
500 name="confirmation"
501 type="password"
502 autocomplete="new-password"
503 required=(true)
504 })
505 </div>
506 <p class="text-xs text-muted-foreground">(Password::RULE)</p>
507 <p class="text-xs text-muted-foreground">
508 "Changing it signs out every other device, and retires any reset "
509 "link that is still outstanding."
510 </p>
511 button(attrs: attributes! { type="submit" }, "Change password")
512 </form>
513 </section>
514
515 home_section(handle: handle, state: home)
516
517 <section class="mt-10 border-t border-border pt-6">
518 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
519 "Access tokens"
520 </h2>
521 <p class="mt-2 text-sm text-muted-foreground">
522 "Tokens are how git authenticates when you push or clone a private "
523 "repository over HTTPS."
524 </p>
525 <p class="mt-3">
526 <a
527 href=(format!("/{handle}/settings/tokens"))
528 class="text-sm font-medium hover:underline"
529 >"Manage tokens →"</a>
530 </p>
531 </section>
532
533 if backups.downloadable {
534 <section class="mt-8 border-t border-border pt-6">
535 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
536 "Backup"
537 </h2>
538 <p class="mt-2 text-sm text-muted-foreground">
539 "One archive of the database and every repository, taken at a "
540 "single moment. Restore it into an empty instance with "
541 <code class="font-mono text-xs">"steid restore"</code> "."
542 </p>
543
544 <div class="mt-3 flex flex-wrap items-baseline gap-x-2 gap-y-1 text-xs">
545 <span class="text-muted-foreground">"Scheduled"</span>
546 // The one live fact in the section, so it carries the colour when
547 // there is something to say and stays muted when there is not.
548 if let Some(last) = backups.last_scheduled {
549 <span class="font-mono text-primary" title=(timestamp(last))>
550 (ago(last))
551 </span>
552 } else {
553 <span class="font-mono text-muted-foreground">"none configured"</span>
554 <span class="text-muted-foreground">
555 "— " <code class="font-mono">"install.sh --backups daily"</code>
556 " sets up a nightly one."
557 </span>
558 }
559 </div>
560
561 <p class="mt-3">
562 <a
563 href=(backup_url(handle))
564 class="text-sm font-medium hover:underline"
565 >"Download a backup now →"</a>
566 </p>
567 <p class="mt-1 text-xs text-muted-foreground">
568 "Large instances take a while, and at most two an hour."
569 </p>
570 </section>
571 }
572 )
573 }
574}
575
576/// The Home section, shared by both settings pages.
577///
578/// A statement when this handle is already the front door, and one button when it is
579/// not. No way to *unset* it: an instance with no home falls back to its sole owner,
580/// which is a state a fresh instance is in rather than one anybody would choose, and
581/// "point it somewhere else" is the same button on the other page.
582#[component]
583async fn home_section(handle: &str, state: HomeState) -> Result {
584 view! {
585 <section class="mt-10 border-t border-border pt-6">
586 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
587 "Home page"
588 </h2>
589
590 if state.moved {
591 <div class="mt-3">
592 flash(kind: FlashKind::Success, "This is now the home page.")
593 </div>
594 }
595
596 if state.is_home {
597 <p class="mt-2 text-sm text-muted-foreground">
598 "This is the home page. " <code class="font-mono text-xs">"/"</code>
599 " lands here, for everyone."
600 </p>
601 } else {
602 <p class="mt-2 text-sm text-muted-foreground">
603 "The root of this instance lands somewhere else. Moving it here "
604 "changes where every visitor arrives."
605 </p>
606 <form
607 method="post"
608 action=(format!("/{handle}/settings/home"))
609 class="mt-3"
610 >
611 csrf_field()
612 button(attrs: attributes! { type="submit" }, "Make this the home page")
613 </form>
614 }
615 </section>
616 }
617}
618
619/// An organisation's settings: its profile, and whether it is the home page.
620///
621/// Deliberately not the person's page. An organisation has no password, no tokens and
622/// no instance backup — those belong to whoever owns it, on their own settings page,
623/// and offering them here would be three forms that write somebody else's rows.
624#[component]
625async fn org_settings_form(
626 handle: &str,
627 display_name: &str,
628 bio: &str,
629 saved: bool,
630 error: &str,
631 home: HomeState,
632) -> Result {
633 view! {
634 narrow(
635 <h1 class="text-xl font-semibold tracking-tight">"Organisation settings"</h1>
636 <p class="mt-1 font-mono text-sm text-muted-foreground">"@" (handle)</p>
637
638 if saved {
639 <div class="mt-6">
640 flash(kind: FlashKind::Success, "Organisation updated.")
641 </div>
642 }
643
644 if !error.is_empty() {
645 <div class="mt-6">
646 flash(kind: FlashKind::Error, (error))
647 </div>
648 }
649
650 <form method="post" action=(format!("/{handle}/settings")) class="mt-6 space-y-5">
651 csrf_field()
652 <div class="space-y-2">
653 label(attrs: attributes! { for="display_name" }, "Display name")
654 input(attrs: attributes! {
655 id="display_name"
656 name="display_name"
657 type="text"
658 value=(display_name)
659 placeholder=(handle)
660 })
661 <p class="text-xs text-muted-foreground">
662 "Shown instead of the handle. Leave blank to use @" (handle) "."
663 </p>
664 </div>
665
666 <div class="space-y-2">
667 label(attrs: attributes! { for="bio" }, "Bio")
668 textarea(
669 attrs: attributes! {
670 id="bio"
671 name="bio"
672 rows="4"
673 maxlength=(Organization::MAX_BIO_LEN.to_string())
674 },
675 (bio)
676 )
677 <p class="text-xs text-muted-foreground">
678 "At most " (Organization::MAX_BIO_LEN.to_string()) " characters."
679 </p>
680 </div>
681
682 <div class="flex items-center gap-3">
683 button(attrs: attributes! { type="submit" }, "Save")
684 <a
685 href=(format!("/{handle}"))
686 class="text-sm text-muted-foreground hover:text-foreground"
687 >"Back to " (handle)</a>
688 </div>
689 </form>
690
691 home_section(handle: handle, state: home)
692 )
693 }
694}