forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

users.rs511 lines, 18.2 KiBHistoryRawDownload
1//! `/admin/users`: the list of accounts with search and keyset paging, and each account's page with the
2//! administrator actions.
3//!
4//! The actions are disable and enable, make and remove administrator, reset two-factor sign-in, end every
5//! session, and delete. Each POST checks the admin guard, then its CSRF token, then the rules of the
6//! account: an administrator never acts on their own account here, and the last enabled administrator
7//! cannot be disabled, demoted or deleted (the store refuses it in the same statement that would do it).
8//! An action that changes what a person sees of their account bumps that account's live topic, so their
9//! open pages refresh and a disabled or deleted person is signed out at once.
10
11use im_core::Error as CoreError;
12use im_core::model::{AuditAction, User};
13use im_core::names::{normalize_email, single_line};
14use im_core::store::admin::AdminChange;
15use im_core::store::backchannel::EndReason;
16use serde::Deserialize;
17use serde_json::json;
18use topcoat::Result;
19use topcoat::context::{Cx, app_context};
20use topcoat::router::content::Form;
21use topcoat::router::error::{SeeOther, not_found};
22use topcoat::router::{page, route};
23use topcoat::view::{View, component, view};
24
25use crate::audit::{Actor, record};
26use crate::auth::{Viewer, percent_encode, require_admin, require_admin_csrf};
27use crate::i18n::Lang;
28use crate::i18n::admin::{A, text};
29use crate::live::Topic;
30use crate::mail::{self, Notice};
31use crate::pages::admin::{
32 FlashQuery, PAGE_SIZE, Tab, action_button, changed, done, error_text, flash_messages,
33 frame_info, notice_text, refused, tabs,
34};
35use crate::pages::path_param;
36use crate::state::AppState;
37use crate::views::{ViewerInfo, page_lang, shell};
38
39/// The query of the account list: the search, the cursor of the next page, and the flash codes.
40#[derive(Deserialize, Default)]
41struct UsersQuery {
42 #[serde(default, deserialize_with = "single_line")]
43 q: String,
44 /// `created_at|id` of the last account of the previous page.
45 #[serde(default)]
46 after: String,
47 #[serde(default)]
48 notice: String,
49 #[serde(default)]
50 error: String,
51}
52
53/// The form of every account action. Only the fields the action needs are read.
54#[derive(Deserialize, Default)]
55struct ActionForm {
56 #[serde(default)]
57 csrf: String,
58 /// `1` makes the account an administrator, `0` removes the flag.
59 #[serde(default)]
60 on: String,
61 /// The email address typed to confirm a deletion.
62 #[serde(default)]
63 confirm: String,
64}
65
66/// One row of the account list, with the text already resolved.
67struct UserRow {
68 name: String,
69 email: String,
70 status: &'static str,
71 admin: bool,
72 created: String,
73 href: String,
74}
75
76/// The account list. Newest first; `q` filters by part of the address or the name.
77#[page("/admin/users")]
78async fn users_page(cx: &Cx, Form(query): Form<UsersQuery>) -> Result<impl View> {
79 let viewer = require_admin(cx).await?;
80 let state = app_context::<AppState>(cx);
81 let (lang, info) = frame_info(cx, &viewer);
82 let search: String = query.q.trim().chars().take(100).collect();
83 let cursor = query
84 .after
85 .split_once('|')
86 .filter(|(at, id)| !at.is_empty() && !id.is_empty());
87 let mut users = state
88 .store
89 .list_users(
90 (!search.is_empty()).then_some(search.as_str()),
91 cursor,
92 PAGE_SIZE + 1,
93 )
94 .await?;
95 let more = users.len() > PAGE_SIZE as usize;
96 users.truncate(PAGE_SIZE as usize);
97 let next = more
98 .then(|| users.last().map(|u| format!("{}|{}", u.created_at, u.id)))
99 .flatten()
100 .map(|cursor| {
101 format!(
102 "/admin/users?q={}&after={}",
103 percent_encode(&search),
104 percent_encode(&cursor)
105 )
106 });
107 let rows: Vec<UserRow> = users.iter().map(|user| row_of(lang, user)).collect();
108 Ok(users_view(
109 cx,
110 lang,
111 info,
112 search,
113 rows,
114 next,
115 notice_text(lang, &query.notice).map(str::to_owned),
116 error_text(lang, &query.error).map(str::to_owned),
117 ))
118}
119
120/// The list row of an account.
121fn row_of(lang: Lang, user: &User) -> UserRow {
122 UserRow {
123 name: user.name.clone(),
124 email: user.email.clone(),
125 status: if user.is_disabled() {
126 text(lang, A::Disabled)
127 } else {
128 text(lang, A::Active)
129 },
130 admin: user.is_admin,
131 created: user.created_at.clone(),
132 href: format!("/admin/users/{}", user.id),
133 }
134}
135
136/// The account list page.
137#[allow(clippy::too_many_arguments)]
138fn users_view(
139 cx: &Cx,
140 lang: Lang,
141 info: ViewerInfo,
142 search: String,
143 rows: Vec<UserRow>,
144 next: Option<String>,
145 success: Option<String>,
146 problem: Option<String>,
147) -> impl View {
148 view! { cx =>
149 shell(title: text(lang, A::UsersTitle), lang: lang, viewer: Some(info),
150 tabs(lang: lang, current: Tab::Users)
151 <section class="stack" data-live="/admin/events">
152 <h1>(text(lang, A::UsersTitle))</h1>
153 <p class="muted">(text(lang, A::UsersIntro))</p>
154 flash_messages(success: success, problem: problem)
155 <form method="get" action="/admin/users" class="row">
156 <label class="field">
157 <span class="field-label">(text(lang, A::SearchLabel))</span>
158 <input name="q" type="search" value=(search) spellcheck="false">
159 </label>
160 <button type="submit" class="button ghost">(text(lang, A::Search))</button>
161 </form>
162 if rows.is_empty() {
163 <p class="muted">(text(lang, A::NoUsers))</p>
164 } else {
165 <table class="table">
166 <thead><tr>
167 <th>(text(lang, A::Name))</th>
168 <th>(text(lang, A::Email))</th>
169 <th>(text(lang, A::Status))</th>
170 <th>(text(lang, A::Created))</th>
171 <th><span class="visually-hidden">(text(lang, A::Open))</span></th>
172 </tr></thead>
173 <tbody>
174 for row in rows {
175 user_row(lang: lang, row: row)
176 }
177 </tbody>
178 </table>
179 }
180 if let Some(href) = next {
181 <p><a class="button ghost" href=(href)>(text(lang, A::NextPage))</a></p>
182 }
183 </section>
184 )
185 }
186}
187
188/// One account in the list.
189#[component]
190async fn user_row(lang: Lang, row: UserRow) -> Result<impl View> {
191 Ok(view! {
192 <tr>
193 <td>(row.name.clone())</td>
194 <td>(row.email.clone())</td>
195 <td>
196 <span class="badge">(row.status)</span>
197 if row.admin {
198 <span class="badge accent">(text(lang, A::Administrator))</span>
199 }
200 </td>
201 <td>(row.created.clone())</td>
202 <td><a href=(row.href.clone())>(text(lang, A::Open))</a></td>
203 </tr>
204 })
205}
206
207/// One account's page: its facts and the actions on it.
208#[page("/admin/users/{id}")]
209async fn user_page(cx: &Cx, Form(query): Form<FlashQuery>) -> Result<impl View> {
210 let viewer = require_admin(cx).await?;
211 let state = app_context::<AppState>(cx);
212 let (lang, info) = frame_info(cx, &viewer);
213 let Some(id) = path_param(cx, "id") else {
214 return Err(not_found().into());
215 };
216 let Some(user) = state.store.user_by_id(&id).await? else {
217 return Err(not_found().into());
218 };
219 let sessions = state.store.list_sessions(&user.id).await?.len();
220 let is_self = user.id == viewer.user.id;
221 Ok(user_view(
222 cx,
223 lang,
224 info,
225 viewer.session.csrf_token.clone(),
226 user,
227 sessions,
228 is_self,
229 notice_text(lang, &query.notice).map(str::to_owned),
230 error_text(lang, &query.error).map(str::to_owned),
231 ))
232}
233
234/// The markup of one account's page. The actions are shown only for other accounts.
235#[allow(clippy::too_many_arguments)]
236fn user_view(
237 cx: &Cx,
238 lang: Lang,
239 info: ViewerInfo,
240 csrf: String,
241 user: User,
242 sessions: usize,
243 is_self: bool,
244 success: Option<String>,
245 problem: Option<String>,
246) -> impl View {
247 let base = format!("/admin/users/{}", user.id);
248 let status = if user.is_disabled() {
249 text(lang, A::Disabled)
250 } else {
251 text(lang, A::Active)
252 };
253 let two_factor = if user.totp_enabled() {
254 text(lang, A::TwoFactorOn)
255 } else {
256 text(lang, A::TwoFactorOff)
257 };
258 let admin_flag = if user.is_admin {
259 text(lang, A::RemoveAdmin)
260 } else {
261 text(lang, A::MakeAdmin)
262 };
263 let admin_on = if user.is_admin { "0" } else { "1" };
264 let admin_text = if user.is_admin {
265 text(lang, A::Yes)
266 } else {
267 text(lang, A::No)
268 };
269 view! { cx =>
270 shell(title: text(lang, A::UserTitle), lang: lang, viewer: Some(info),
271 tabs(lang: lang, current: Tab::Users)
272 <section class="stack" data-live="/admin/events">
273 <p><a href="/admin/users">(text(lang, A::NavUsers))</a></p>
274 <h1>(user.name.clone())</h1>
275 flash_messages(success: success, problem: problem)
276 <dl class="facts">
277 <dt>(text(lang, A::Email))</dt><dd>(user.email.clone())</dd>
278 <dt>(text(lang, A::Status))</dt><dd>(status)</dd>
279 <dt>(text(lang, A::Administrator))</dt><dd>(admin_text)</dd>
280 <dt>(text(lang, A::Created))</dt><dd>(user.created_at.clone())</dd>
281 <dt>(text(lang, A::SessionsLabel))</dt><dd>(sessions.to_string())</dd>
282 <dt>(text(lang, A::TwoFactor))</dt><dd>(two_factor)</dd>
283 </dl>
284 if is_self {
285 <p class="notice">(text(lang, A::YouLabel))". "(text(lang, A::NoOwnAccountHere))</p>
286 } else {
287 <div class="stack">
288 if user.is_disabled() {
289 action_button(action: format!("{base}/enable"), csrf: csrf.clone(), label: text(lang, A::EnableAccount), class: "button primary", on: "")
290 } else {
291 action_button(action: format!("{base}/disable"), csrf: csrf.clone(), label: text(lang, A::DisableAccount), class: "button danger", on: "")
292 }
293 action_button(action: format!("{base}/admin"), csrf: csrf.clone(), label: admin_flag, class: "button ghost", on: admin_on)
294 action_button(action: format!("{base}/reset-2fa"), csrf: csrf.clone(), label: text(lang, A::ResetTwoFactor), class: "button ghost", on: "")
295 action_button(action: format!("{base}/revoke-sessions"), csrf: csrf.clone(), label: text(lang, A::RevokeSessions), class: "button ghost", on: "")
296 <form method="post" action=(format!("{base}/delete")) class="stack">
297 <input type="hidden" name="csrf" value=(csrf.clone())>
298 <p class="hint">(text(lang, A::DeleteWarning))</p>
299 <label class="field">
300 <span class="field-label">(text(lang, A::ConfirmEmail))</span>
301 <input name="confirm" type="email" autocomplete="off" spellcheck="false">
302 </label>
303 <button type="submit" class="button danger">(text(lang, A::DeleteAccount))</button>
304 </form>
305 </div>
306 }
307 </section>
308 )
309 }
310}
311
312/// Checks the CSRF token and loads the account named by the path. A member gets 404 before the token is
313/// read; a wrong token gets 403; a missing account gets 404.
314async fn target(cx: &Cx, csrf: &str) -> Result<(Viewer, User)> {
315 let viewer = require_admin_csrf(cx, csrf).await?;
316 let state = app_context::<AppState>(cx);
317 let Some(id) = path_param(cx, "id") else {
318 return Err(not_found().into());
319 };
320 let Some(user) = state.store.user_by_id(&id).await? else {
321 return Err(not_found().into());
322 };
323 Ok((viewer, user))
324}
325
326/// `POST /admin/users/{id}/disable`. Ends the account's sessions and queues the back-channel logouts.
327#[route(POST "/admin/users/{id}/disable")]
328async fn disable(cx: &Cx, Form(form): Form<ActionForm>) -> Result<SeeOther> {
329 let (viewer, user) = target(cx, &form.csrf).await?;
330 let base = format!("/admin/users/{}", user.id);
331 if user.id == viewer.user.id {
332 return Ok(refused(&base, "self-disable"));
333 }
334 if user.is_disabled() {
335 return Ok(done(&base, "disabled"));
336 }
337 let state = app_context::<AppState>(cx);
338 if state.store.disable_user(&user.id).await? {
339 state.live.bump(&Topic::Account(user.id.clone()));
340 changed(&state.live);
341 record(
342 cx,
343 Actor::User(&viewer.user.id),
344 AuditAction::UserDisabled,
345 Some(("user", &user.id)),
346 json!({}),
347 )
348 .await;
349 return Ok(done(&base, "disabled"));
350 }
351 // The store refused: the account is the last enabled administrator.
352 Ok(refused(&base, "last-admin"))
353}
354
355/// `POST /admin/users/{id}/enable`.
356#[route(POST "/admin/users/{id}/enable")]
357async fn enable(cx: &Cx, Form(form): Form<ActionForm>) -> Result<SeeOther> {
358 let (viewer, user) = target(cx, &form.csrf).await?;
359 let base = format!("/admin/users/{}", user.id);
360 let state = app_context::<AppState>(cx);
361 if state.store.enable_user(&user.id).await? {
362 changed(&state.live);
363 state.live.bump(&Topic::Account(user.id.clone()));
364 record(
365 cx,
366 Actor::User(&viewer.user.id),
367 AuditAction::UserEnabled,
368 Some(("user", &user.id)),
369 json!({}),
370 )
371 .await;
372 }
373 Ok(done(&base, "enabled"))
374}
375
376/// `POST /admin/users/{id}/admin`. `on=1` makes the account an administrator, `on=0` removes the flag.
377#[route(POST "/admin/users/{id}/admin")]
378async fn set_admin_flag(cx: &Cx, Form(form): Form<ActionForm>) -> Result<SeeOther> {
379 let (viewer, user) = target(cx, &form.csrf).await?;
380 let base = format!("/admin/users/{}", user.id);
381 if user.id == viewer.user.id {
382 return Ok(refused(&base, "self-admin"));
383 }
384 let make = form.on == "1";
385 let state = app_context::<AppState>(cx);
386 let outcome = state.store.set_admin(&user.id, make).await?;
387 let code = if make {
388 "admin-granted"
389 } else {
390 "admin-removed"
391 };
392 match outcome {
393 AdminChange::LastAdmin => Ok(refused(&base, "last-admin")),
394 AdminChange::Unchanged => Ok(done(&base, code)),
395 AdminChange::Changed => {
396 state.live.bump(&Topic::Account(user.id.clone()));
397 changed(&state.live);
398 let action = if make {
399 AuditAction::AdminGranted
400 } else {
401 AuditAction::AdminRemoved
402 };
403 record(
404 cx,
405 Actor::User(&viewer.user.id),
406 action,
407 Some(("user", &user.id)),
408 json!({}),
409 )
410 .await;
411 Ok(done(&base, code))
412 }
413 }
414}
415
416/// `POST /admin/users/{id}/reset-2fa`. Clears the second factor and the recovery codes, and mails the
417/// account's own address so the person knows.
418#[route(POST "/admin/users/{id}/reset-2fa")]
419async fn reset_two_factor(cx: &Cx, Form(form): Form<ActionForm>) -> Result<SeeOther> {
420 let (viewer, user) = target(cx, &form.csrf).await?;
421 let base = format!("/admin/users/{}", user.id);
422 if user.id == viewer.user.id {
423 return Ok(refused(&base, "self"));
424 }
425 let state = app_context::<AppState>(cx);
426 state.store.disable_totp(&user.id, None).await?;
427 state.live.bump(&Topic::Account(user.id.clone()));
428 changed(&state.live);
429 let request_lang = page_lang(cx, Some(&viewer));
430 mail::notify(
431 &state.store,
432 &state.key,
433 &user,
434 request_lang,
435 Notice::TwoFactorOff,
436 )
437 .await;
438 record(
439 cx,
440 Actor::User(&viewer.user.id),
441 AuditAction::AdminTwoFactorReset,
442 Some(("user", &user.id)),
443 json!({}),
444 )
445 .await;
446 Ok(done(&base, "2fa-reset"))
447}
448
449/// `POST /admin/users/{id}/revoke-sessions`. Ends every session of the account, with their logouts.
450#[route(POST "/admin/users/{id}/revoke-sessions")]
451async fn revoke_sessions(cx: &Cx, Form(form): Form<ActionForm>) -> Result<SeeOther> {
452 let (viewer, user) = target(cx, &form.csrf).await?;
453 let base = format!("/admin/users/{}", user.id);
454 if user.id == viewer.user.id {
455 return Ok(refused(&base, "self"));
456 }
457 let state = app_context::<AppState>(cx);
458 let ended = state
459 .store
460 .end_all_sessions(&user.id, EndReason::Revoked)
461 .await?;
462 if !ended.is_empty() {
463 state.live.bump(&Topic::Account(user.id.clone()));
464 changed(&state.live);
465 record(
466 cx,
467 Actor::User(&viewer.user.id),
468 AuditAction::AdminSessionsRevoked,
469 Some(("user", &user.id)),
470 json!({ "count": ended.len() }),
471 )
472 .await;
473 }
474 Ok(done(&base, "sessions-revoked"))
475}
476
477/// `POST /admin/users/{id}/delete`. The address must be typed again. Deletes the account, its sessions,
478/// links and recovery codes, and then its photo file. The last enabled administrator cannot be deleted.
479#[route(POST "/admin/users/{id}/delete")]
480async fn delete_account(cx: &Cx, Form(form): Form<ActionForm>) -> Result<SeeOther> {
481 let (viewer, user) = target(cx, &form.csrf).await?;
482 let base = format!("/admin/users/{}", user.id);
483 if user.id == viewer.user.id {
484 return Ok(refused(&base, "self-delete"));
485 }
486 if normalize_email(&form.confirm) != user.email {
487 return Ok(refused(&base, "confirm-email"));
488 }
489 let state = app_context::<AppState>(cx);
490 match state.store.delete_user(&user.id).await {
491 Ok(true) => {
492 if let Err(error) = im_core::photo::remove_photo(&state.config.data_dir, &user.id) {
493 tracing::error!(error = %error, "photo of a deleted account not removed");
494 }
495 state.live.bump(&Topic::Account(user.id.clone()));
496 changed(&state.live);
497 record(
498 cx,
499 Actor::User(&viewer.user.id),
500 AuditAction::UserDeleted,
501 Some(("user", &user.id)),
502 json!({}),
503 )
504 .await;
505 Ok(done("/admin/users", "deleted"))
506 }
507 Ok(false) => Ok(done("/admin/users", "deleted")),
508 Err(CoreError::Conflict(_)) => Ok(refused(&base, "last-admin")),
509 Err(error) => Err(error.into()),
510 }
511}