steid

@jamesgill /

Rust17.5 KBCode·Blame·History·Raw
1//! Profile settings — `/{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
6use std::time::SystemTime;
7
8use serde::Deserialize;
9use topcoat::{
10 Result,
11 context::Cx,
12 router::{
13 IntoResponse, Response, StatusCode, content::Form, error::not_found, error::see_other,
14 page, query_params, route,
15 },
16 session,
17 view::{attributes, component, view},
18};
19
20use crate::{
21 application::{Error, change_password, update_profile},
22 components::{
23 button::button,
24 flash::{FlashKind, flash},
25 input::input,
26 label::label,
27 textarea::textarea,
28 },
29 domain::{DomainError, Organization, Password, SessionTokenHash},
30};
31
32use super::{
33 backup::{backup_url, last_scheduled_backup},
34 context::{
35 current_actor, hex, instance_owner, location, memberships, orgs, owned_profile, resets,
36 server_error, sessions, users,
37 },
38 csrf::{csrf_field, csrf_verified, csrf_verified_response},
39 format::{ago, optional, timestamp},
40 layout::narrow,
41 password::refusal_code,
42};
43
44/// What the Backup section has to say.
45///
46/// Two independent facts, and the section is drawn from both: whether *this* viewer may
47/// take a backup at all, and when the machine last took one by itself. Neither implies
48/// the other — a schedule runs whether anybody is signed in or not.
49#[derive(Debug, Clone, Copy, Default)]
50struct BackupState {
51 /// Whether the viewer is the instance's owner, which is stricter than owning this
52 /// profile — see [`instance_owner`](super::context::instance_owner).
53 downloadable: bool,
54 /// When the configured timer last ran. `None` covers both "no timer" and "a timer
55 /// that has never completed", which look the same from here and mean the same thing
56 /// to whoever is reading the page: no backup has been taken for you.
57 last_scheduled: Option<SystemTime>,
58}
59
60async fn backup_state(cx: &Cx) -> Result<BackupState> {
61 Ok(BackupState {
62 downloadable: instance_owner(cx).await?,
63 last_scheduled: last_scheduled_backup(cx),
64 })
65}
66
67#[derive(Debug, Deserialize)]
68struct ProfileForm {
69 /// The hidden field every form carries; see [`csrf`](super::csrf).
70 ///
71 /// `default` so that a submission with no token at all is refused by
72 /// `csrf_verified` — a 403 saying what happened — rather than failing
73 /// deserialization into a bare 400 that says nothing.
74 #[serde(default)]
75 csrf_token: String,
76 display_name: String,
77 bio: String,
78}
79
80/// Set after a successful save so the confirmation survives the redirect.
81///
82/// Post-redirect-get: reloading after a save must not resubmit it.
83#[query_params(error = bad_request)]
84struct Saved {
85 saved: Option<String>,
86}
87
88/// How the last password change went, as it travels through the redirect.
89#[query_params(error = bad_request)]
90struct PasswordOutcome {
91 password: Option<String>,
92}
93
94/// The password section's three fields.
95#[derive(Debug, Deserialize)]
96struct PasswordForm {
97 /// The hidden field every form carries; see [`csrf`](super::csrf).
98 ///
99 /// `default` so that a submission with no token at all is refused by
100 /// `csrf_verified` — a 403 saying what happened — rather than failing
101 /// deserialization into a bare 400 that says nothing.
102 #[serde(default)]
103 csrf_token: String,
104 current: String,
105 password: String,
106 confirmation: String,
107}
108
109/// The refusal a code stands for.
110///
111/// A closed set rather than the message itself, for the reason `web::password` gives:
112/// a message carried in a URL is a message a stranger can put on the page.
113fn password_message(code: Option<&str>) -> (FlashKind, &'static str) {
114 match code {
115 Some("changed") => (
116 FlashKind::Success,
117 "Password changed. Every other device has been signed out.",
118 ),
119 Some("wrong") => (FlashKind::Error, "That is not your current password."),
120 Some("mismatch") => (FlashKind::Error, "Those two new passwords are different."),
121 // The one sentence, from the one place — see `Password`. `web::password` shows
122 // the same words on the reset page.
123 Some("short") => (FlashKind::Error, Password::RULE),
124 Some("long") => (FlashKind::Error, "That password is too long to hash."),
125 Some(_) => (FlashKind::Error, "That did not work. Try again."),
126 None => (FlashKind::Info, ""),
127 }
128}
129
130#[page("/{handle}/settings")]
131async fn settings_page(cx: &Cx) -> Result {
132 let profile = owned_profile(cx).await?;
133
134 let saved = query_params::<Saved>(cx)?.saved.is_some();
135 let backups = backup_state(cx).await?;
136 let password = query_params::<PasswordOutcome>(cx)?.password.clone();
137
138 view! {
139 settings_form(
140 handle: profile.handle.as_str(),
141 // The stored display name, not the label: the label falls back to the
142 // handle, which would put text in a field the owner never typed.
143 display_name: profile.display_name.as_deref().unwrap_or(""),
144 bio: profile.bio.as_deref().unwrap_or(""),
145 saved: saved,
146 error: "",
147 sections: Sections { backups: &backups, password: password.as_deref() },
148 )
149 }
150}
151
152/// Applies an edit.
153///
154/// Success replies 303, so a reload cannot resubmit — see [`location`] for why it is
155/// spelled this way and not with `redirect()`, which is a 307 and would re-POST this
156/// form to itself.
157///
158/// Failure re-renders with the message and **what was typed** — bouncing back to a
159/// blank form would throw away the work and leave the reason invisible, which is the
160/// whole problem `flash` exists to fix.
161#[page(POST "/{handle}/settings")]
162async fn save(cx: &Cx, Form(submitted): Form<ProfileForm>) -> Result {
163 csrf_verified(cx, &submitted.csrf_token).await?;
164
165 let profile = owned_profile(cx).await?;
166 let backups = backup_state(cx).await?;
167
168 let outcome = update_profile(
169 &current_actor(cx).await?,
170 &profile.handle,
171 optional(&submitted.display_name),
172 optional(&submitted.bio),
173 &orgs(cx),
174 &memberships(cx),
175 )
176 .await;
177
178 let message = match outcome {
179 Ok(()) => {
180 return view! {
181 (StatusCode::SEE_OTHER)
182 (location(&format!("/{}/settings?saved", profile.handle))?)
183 };
184 }
185 // The visitor's to fix, so it is shown.
186 Err(Error::Domain(DomainError::Validation { field, reason })) => {
187 format!("That {field} is no good: {reason}.")
188 }
189 Err(Error::Domain(DomainError::Forbidden)) => return Err(not_found().into()),
190 // Ours, so it is logged and answered generically.
191 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
192 };
193
194 view! {
195 settings_form(
196 handle: profile.handle.as_str(),
197 display_name: submitted.display_name.as_str(),
198 bio: submitted.bio.as_str(),
199 saved: false,
200 error: message.as_str(),
201 sections: Sections { backups: &backups, password: None },
202 )
203 }
204}
205
206/// Changes the owner's password.
207///
208/// Not rate limited: reaching it needs a session, so the budget it would spend belongs
209/// to the person already signed in. The guessing this would otherwise enable is
210/// guessing your own password on your own browser.
211///
212/// A `#[route]` rather than a `#[page]` because there is nothing to re-render — three
213/// password fields, none of which a browser should be handed back. The outcome travels
214/// as `?password=` and the settings page renders the message; a redirect that usually
215/// discards what was typed discards nothing here.
216#[route(POST "/{handle}/settings/password")]
217async fn change(cx: &Cx, Form(submitted): Form<PasswordForm>) -> Result<Response> {
218 if let Some(response) = csrf_verified_response(cx, &submitted.csrf_token).await? {
219 return Ok(response);
220 }
221
222 let profile = owned_profile(cx).await?;
223
224 // The session doing the changing, spared so the owner is not signed out of the
225 // browser they are looking at. Absent only if the cookie went between the page
226 // rendering and the form arriving, in which case every session goes — which is the
227 // safe way to be wrong.
228 let here = session::token_hash(cx)
229 .await?
230 .map(|hash| SessionTokenHash::from_trusted(hex(&hash)));
231
232 let outcome = change_password(
233 &current_actor(cx).await?,
234 &submitted.current,
235 &submitted.password,
236 &submitted.confirmation,
237 here.as_ref(),
238 SystemTime::now(),
239 &users(cx),
240 &resets(cx),
241 &sessions(cx),
242 &crate::infrastructure::password::Argon2Hasher::new(),
243 )
244 .await;
245
246 let code = match outcome {
247 Ok(()) => "changed",
248 Err(Error::Domain(DomainError::InvalidCredentials)) => "wrong",
249 Err(Error::Domain(DomainError::Validation { reason, .. })) => refusal_code(&reason),
250 Err(Error::Domain(DomainError::Forbidden)) => return Err(not_found().into()),
251 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
252 };
253
254 see_other(&format!("/{}/settings?password={code}", profile.handle)).into_response(cx)
255}
256
257/// The edit form.
258///
259/// Values arrive as parameters rather than being read back from storage, so a rejected
260/// submission can re-render exactly what was typed.
261/// The two sections below the profile form, as one value: a `#[component]` drops outer
262/// attributes, so an eighth parameter is a clippy warning with no way to silence it.
263#[derive(Debug, Clone, Copy)]
264struct Sections<'a> {
265 backups: &'a BackupState,
266 /// The `?password=` code from the last change, or `None` for a page nobody has
267 /// submitted that form to.
268 password: Option<&'a str>,
269}
270
271#[component]
272async fn settings_form(
273 handle: &str,
274 display_name: &str,
275 bio: &str,
276 saved: bool,
277 error: &str,
278 sections: Sections<'_>,
279) -> Result {
280 let Sections { backups, password } = sections;
281 let (password_kind, password_text) = password_message(password);
282
283 view! {
284 narrow(
285 <h1 class="text-xl font-semibold tracking-tight">"Profile settings"</h1>
286 <p class="mt-1 font-mono text-sm text-muted-foreground">"@" (handle)</p>
287
288 if saved {
289 <div class="mt-6">
290 flash(kind: FlashKind::Success, "Profile updated.")
291 </div>
292 }
293
294 if !error.is_empty() {
295 <div class="mt-6">
296 flash(kind: FlashKind::Error, (error))
297 </div>
298 }
299
300 <form method="post" action=(format!("/{handle}/settings")) class="mt-6 space-y-5">
301 csrf_field()
302 <div class="space-y-2">
303 label(attrs: attributes! { for="display_name" }, "Display name")
304 input(attrs: attributes! {
305 id="display_name"
306 name="display_name"
307 type="text"
308 value=(display_name)
309 placeholder=(handle)
310 })
311 <p class="text-xs text-muted-foreground">
312 "Shown instead of your handle. Leave blank to use @" (handle) "."
313 </p>
314 </div>
315
316 <div class="space-y-2">
317 label(attrs: attributes! { for="bio" }, "Bio")
318 textarea(
319 attrs: attributes! {
320 id="bio"
321 name="bio"
322 rows="4"
323 maxlength=(Organization::MAX_BIO_LEN.to_string())
324 },
325 (bio)
326 )
327 <p class="text-xs text-muted-foreground">
328 "At most " (Organization::MAX_BIO_LEN.to_string()) " characters."
329 </p>
330 </div>
331
332 <div class="flex items-center gap-3">
333 button(attrs: attributes! { type="submit" }, "Save")
334 <a
335 href=(format!("/{handle}"))
336 class="text-sm text-muted-foreground hover:text-foreground"
337 >"Back to profile"</a>
338 </div>
339 </form>
340
341 <section class="mt-10 border-t border-border pt-6">
342 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
343 "Password"
344 </h2>
345
346 if !password_text.is_empty() {
347 <div class="mt-3">
348 flash(kind: password_kind, (password_text))
349 </div>
350 }
351
352 <form
353 method="post"
354 action=(format!("/{handle}/settings/password"))
355 class="mt-4 max-w-sm space-y-4"
356 >
357 csrf_field()
358 <div class="space-y-2">
359 label(attrs: attributes! { for="current" }, "Current password")
360 input(attrs: attributes! {
361 id="current"
362 name="current"
363 type="password"
364 autocomplete="current-password"
365 required=(true)
366 })
367 </div>
368 <div class="space-y-2">
369 label(attrs: attributes! { for="password" }, "New password")
370 input(attrs: attributes! {
371 id="password"
372 name="password"
373 type="password"
374 autocomplete="new-password"
375 required=(true)
376 })
377 </div>
378 <div class="space-y-2">
379 label(attrs: attributes! { for="confirmation" }, "New password again")
380 input(attrs: attributes! {
381 id="confirmation"
382 name="confirmation"
383 type="password"
384 autocomplete="new-password"
385 required=(true)
386 })
387 </div>
388 <p class="text-xs text-muted-foreground">(Password::RULE)</p>
389 <p class="text-xs text-muted-foreground">
390 "Changing it signs out every other device, and retires any reset "
391 "link that is still outstanding."
392 </p>
393 button(attrs: attributes! { type="submit" }, "Change password")
394 </form>
395 </section>
396
397 <section class="mt-10 border-t border-border pt-6">
398 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
399 "Access tokens"
400 </h2>
401 <p class="mt-2 text-sm text-muted-foreground">
402 "Tokens are how git authenticates when you push or clone a private "
403 "repository over HTTPS."
404 </p>
405 <p class="mt-3">
406 <a
407 href=(format!("/{handle}/settings/tokens"))
408 class="text-sm font-medium hover:underline"
409 >"Manage tokens →"</a>
410 </p>
411 </section>
412
413 if backups.downloadable {
414 <section class="mt-8 border-t border-border pt-6">
415 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
416 "Backup"
417 </h2>
418 <p class="mt-2 text-sm text-muted-foreground">
419 "One archive of the database and every repository, taken at a "
420 "single moment. Restore it into an empty instance with "
421 <code class="font-mono text-xs">"steid restore"</code> "."
422 </p>
423
424 <div class="mt-3 flex flex-wrap items-baseline gap-x-2 gap-y-1 text-xs">
425 <span class="text-muted-foreground">"Scheduled"</span>
426 // The one live fact in the section, so it carries the colour when
427 // there is something to say and stays muted when there is not.
428 if let Some(last) = backups.last_scheduled {
429 <span class="font-mono text-primary" title=(timestamp(last))>
430 (ago(last))
431 </span>
432 } else {
433 <span class="font-mono text-muted-foreground">"none configured"</span>
434 <span class="text-muted-foreground">
435 "— " <code class="font-mono">"install.sh --backups daily"</code>
436 " sets up a nightly one."
437 </span>
438 }
439 </div>
440
441 <p class="mt-3">
442 <a
443 href=(backup_url(handle))
444 class="text-sm font-medium hover:underline"
445 >"Download a backup now →"</a>
446 </p>
447 <p class="mt-1 text-xs text-muted-foreground">
448 "Large instances take a while, and at most two an hour."
449 </p>
450 </section>
451 }
452 )
453 }
454}