//! `/admin/users`: the list of accounts with search and keyset paging, and each account's page with the //! administrator actions. //! //! The actions are disable and enable, make and remove administrator, reset two-factor sign-in, end every //! session, and delete. Each POST checks the admin guard, then its CSRF token, then the rules of the //! account: an administrator never acts on their own account here, and the last enabled administrator //! cannot be disabled, demoted or deleted (the store refuses it in the same statement that would do it). //! An action that changes what a person sees of their account bumps that account's live topic, so their //! open pages refresh and a disabled or deleted person is signed out at once. use im_core::Error as CoreError; use im_core::model::{AuditAction, User}; use im_core::names::{normalize_email, single_line}; use im_core::store::admin::AdminChange; use im_core::store::backchannel::EndReason; use serde::Deserialize; use serde_json::json; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; use topcoat::router::error::{SeeOther, not_found}; use topcoat::router::{page, route}; use topcoat::view::{View, component, view}; use crate::audit::{Actor, record}; use crate::auth::{Viewer, percent_encode, require_admin, require_admin_csrf}; use crate::i18n::Lang; use crate::i18n::admin::{A, text}; use crate::live::Topic; use crate::mail::{self, Notice}; use crate::pages::admin::{ FlashQuery, PAGE_SIZE, Tab, action_button, changed, done, error_text, flash_messages, frame_info, notice_text, refused, tabs, }; use crate::pages::path_param; use crate::state::AppState; use crate::views::{ViewerInfo, page_lang, shell}; /// The query of the account list: the search, the cursor of the next page, and the flash codes. #[derive(Deserialize, Default)] struct UsersQuery { #[serde(default, deserialize_with = "single_line")] q: String, /// `created_at|id` of the last account of the previous page. #[serde(default)] after: String, #[serde(default)] notice: String, #[serde(default)] error: String, } /// The form of every account action. Only the fields the action needs are read. #[derive(Deserialize, Default)] struct ActionForm { #[serde(default)] csrf: String, /// `1` makes the account an administrator, `0` removes the flag. #[serde(default)] on: String, /// The email address typed to confirm a deletion. #[serde(default)] confirm: String, } /// One row of the account list, with the text already resolved. struct UserRow { name: String, email: String, status: &'static str, admin: bool, created: String, href: String, } /// The account list. Newest first; `q` filters by part of the address or the name. #[page("/admin/users")] async fn users_page(cx: &Cx, Form(query): Form) -> Result { let viewer = require_admin(cx).await?; let state = app_context::(cx); let (lang, info) = frame_info(cx, &viewer); let search: String = query.q.trim().chars().take(100).collect(); let cursor = query .after .split_once('|') .filter(|(at, id)| !at.is_empty() && !id.is_empty()); let mut users = state .store .list_users( (!search.is_empty()).then_some(search.as_str()), cursor, PAGE_SIZE + 1, ) .await?; let more = users.len() > PAGE_SIZE as usize; users.truncate(PAGE_SIZE as usize); let next = more .then(|| users.last().map(|u| format!("{}|{}", u.created_at, u.id))) .flatten() .map(|cursor| { format!( "/admin/users?q={}&after={}", percent_encode(&search), percent_encode(&cursor) ) }); let rows: Vec = users.iter().map(|user| row_of(lang, user)).collect(); Ok(users_view( cx, lang, info, search, rows, next, notice_text(lang, &query.notice).map(str::to_owned), error_text(lang, &query.error).map(str::to_owned), )) } /// The list row of an account. fn row_of(lang: Lang, user: &User) -> UserRow { UserRow { name: user.name.clone(), email: user.email.clone(), status: if user.is_disabled() { text(lang, A::Disabled) } else { text(lang, A::Active) }, admin: user.is_admin, created: user.created_at.clone(), href: format!("/admin/users/{}", user.id), } } /// The account list page. #[allow(clippy::too_many_arguments)] fn users_view( cx: &Cx, lang: Lang, info: ViewerInfo, search: String, rows: Vec, next: Option, success: Option, problem: Option, ) -> impl View { view! { cx => shell(title: text(lang, A::UsersTitle), lang: lang, viewer: Some(info), tabs(lang: lang, current: Tab::Users)

(text(lang, A::UsersTitle))

(text(lang, A::UsersIntro))

flash_messages(success: success, problem: problem)
if rows.is_empty() {

(text(lang, A::NoUsers))

} else { for row in rows { user_row(lang: lang, row: row) }
(text(lang, A::Name)) (text(lang, A::Email)) (text(lang, A::Status)) (text(lang, A::Created)) (text(lang, A::Open))
} if let Some(href) = next {

(text(lang, A::NextPage))

}
) } } /// One account in the list. #[component] async fn user_row(lang: Lang, row: UserRow) -> Result { Ok(view! { (row.name.clone()) (row.email.clone()) (row.status) if row.admin { (text(lang, A::Administrator)) } (row.created.clone()) (text(lang, A::Open)) }) } /// One account's page: its facts and the actions on it. #[page("/admin/users/{id}")] async fn user_page(cx: &Cx, Form(query): Form) -> Result { let viewer = require_admin(cx).await?; let state = app_context::(cx); let (lang, info) = frame_info(cx, &viewer); let Some(id) = path_param(cx, "id") else { return Err(not_found().into()); }; let Some(user) = state.store.user_by_id(&id).await? else { return Err(not_found().into()); }; let sessions = state.store.list_sessions(&user.id).await?.len(); let is_self = user.id == viewer.user.id; Ok(user_view( cx, lang, info, viewer.session.csrf_token.clone(), user, sessions, is_self, notice_text(lang, &query.notice).map(str::to_owned), error_text(lang, &query.error).map(str::to_owned), )) } /// The markup of one account's page. The actions are shown only for other accounts. #[allow(clippy::too_many_arguments)] fn user_view( cx: &Cx, lang: Lang, info: ViewerInfo, csrf: String, user: User, sessions: usize, is_self: bool, success: Option, problem: Option, ) -> impl View { let base = format!("/admin/users/{}", user.id); let status = if user.is_disabled() { text(lang, A::Disabled) } else { text(lang, A::Active) }; let two_factor = if user.totp_enabled() { text(lang, A::TwoFactorOn) } else { text(lang, A::TwoFactorOff) }; let admin_flag = if user.is_admin { text(lang, A::RemoveAdmin) } else { text(lang, A::MakeAdmin) }; let admin_on = if user.is_admin { "0" } else { "1" }; let admin_text = if user.is_admin { text(lang, A::Yes) } else { text(lang, A::No) }; view! { cx => shell(title: text(lang, A::UserTitle), lang: lang, viewer: Some(info), tabs(lang: lang, current: Tab::Users)

(text(lang, A::NavUsers))

(user.name.clone())

flash_messages(success: success, problem: problem)
(text(lang, A::Email))
(user.email.clone())
(text(lang, A::Status))
(status)
(text(lang, A::Administrator))
(admin_text)
(text(lang, A::Created))
(user.created_at.clone())
(text(lang, A::SessionsLabel))
(sessions.to_string())
(text(lang, A::TwoFactor))
(two_factor)
if is_self {

(text(lang, A::YouLabel))". "(text(lang, A::NoOwnAccountHere))

} else {
if user.is_disabled() { action_button(action: format!("{base}/enable"), csrf: csrf.clone(), label: text(lang, A::EnableAccount), class: "button primary", on: "") } else { action_button(action: format!("{base}/disable"), csrf: csrf.clone(), label: text(lang, A::DisableAccount), class: "button danger", on: "") } action_button(action: format!("{base}/admin"), csrf: csrf.clone(), label: admin_flag, class: "button ghost", on: admin_on) action_button(action: format!("{base}/reset-2fa"), csrf: csrf.clone(), label: text(lang, A::ResetTwoFactor), class: "button ghost", on: "") action_button(action: format!("{base}/revoke-sessions"), csrf: csrf.clone(), label: text(lang, A::RevokeSessions), class: "button ghost", on: "")

(text(lang, A::DeleteWarning))

}
) } } /// Checks the CSRF token and loads the account named by the path. A member gets 404 before the token is /// read; a wrong token gets 403; a missing account gets 404. async fn target(cx: &Cx, csrf: &str) -> Result<(Viewer, User)> { let viewer = require_admin_csrf(cx, csrf).await?; let state = app_context::(cx); let Some(id) = path_param(cx, "id") else { return Err(not_found().into()); }; let Some(user) = state.store.user_by_id(&id).await? else { return Err(not_found().into()); }; Ok((viewer, user)) } /// `POST /admin/users/{id}/disable`. Ends the account's sessions and queues the back-channel logouts. #[route(POST "/admin/users/{id}/disable")] async fn disable(cx: &Cx, Form(form): Form) -> Result { let (viewer, user) = target(cx, &form.csrf).await?; let base = format!("/admin/users/{}", user.id); if user.id == viewer.user.id { return Ok(refused(&base, "self-disable")); } if user.is_disabled() { return Ok(done(&base, "disabled")); } let state = app_context::(cx); if state.store.disable_user(&user.id).await? { state.live.bump(&Topic::Account(user.id.clone())); changed(&state.live); record( cx, Actor::User(&viewer.user.id), AuditAction::UserDisabled, Some(("user", &user.id)), json!({}), ) .await; return Ok(done(&base, "disabled")); } // The store refused: the account is the last enabled administrator. Ok(refused(&base, "last-admin")) } /// `POST /admin/users/{id}/enable`. #[route(POST "/admin/users/{id}/enable")] async fn enable(cx: &Cx, Form(form): Form) -> Result { let (viewer, user) = target(cx, &form.csrf).await?; let base = format!("/admin/users/{}", user.id); let state = app_context::(cx); if state.store.enable_user(&user.id).await? { changed(&state.live); state.live.bump(&Topic::Account(user.id.clone())); record( cx, Actor::User(&viewer.user.id), AuditAction::UserEnabled, Some(("user", &user.id)), json!({}), ) .await; } Ok(done(&base, "enabled")) } /// `POST /admin/users/{id}/admin`. `on=1` makes the account an administrator, `on=0` removes the flag. #[route(POST "/admin/users/{id}/admin")] async fn set_admin_flag(cx: &Cx, Form(form): Form) -> Result { let (viewer, user) = target(cx, &form.csrf).await?; let base = format!("/admin/users/{}", user.id); if user.id == viewer.user.id { return Ok(refused(&base, "self-admin")); } let make = form.on == "1"; let state = app_context::(cx); let outcome = state.store.set_admin(&user.id, make).await?; let code = if make { "admin-granted" } else { "admin-removed" }; match outcome { AdminChange::LastAdmin => Ok(refused(&base, "last-admin")), AdminChange::Unchanged => Ok(done(&base, code)), AdminChange::Changed => { state.live.bump(&Topic::Account(user.id.clone())); changed(&state.live); let action = if make { AuditAction::AdminGranted } else { AuditAction::AdminRemoved }; record( cx, Actor::User(&viewer.user.id), action, Some(("user", &user.id)), json!({}), ) .await; Ok(done(&base, code)) } } } /// `POST /admin/users/{id}/reset-2fa`. Clears the second factor and the recovery codes, and mails the /// account's own address so the person knows. #[route(POST "/admin/users/{id}/reset-2fa")] async fn reset_two_factor(cx: &Cx, Form(form): Form) -> Result { let (viewer, user) = target(cx, &form.csrf).await?; let base = format!("/admin/users/{}", user.id); if user.id == viewer.user.id { return Ok(refused(&base, "self")); } let state = app_context::(cx); state.store.disable_totp(&user.id, None).await?; state.live.bump(&Topic::Account(user.id.clone())); changed(&state.live); let request_lang = page_lang(cx, Some(&viewer)); mail::notify( &state.store, &state.key, &user, request_lang, Notice::TwoFactorOff, ) .await; record( cx, Actor::User(&viewer.user.id), AuditAction::AdminTwoFactorReset, Some(("user", &user.id)), json!({}), ) .await; Ok(done(&base, "2fa-reset")) } /// `POST /admin/users/{id}/revoke-sessions`. Ends every session of the account, with their logouts. #[route(POST "/admin/users/{id}/revoke-sessions")] async fn revoke_sessions(cx: &Cx, Form(form): Form) -> Result { let (viewer, user) = target(cx, &form.csrf).await?; let base = format!("/admin/users/{}", user.id); if user.id == viewer.user.id { return Ok(refused(&base, "self")); } let state = app_context::(cx); let ended = state .store .end_all_sessions(&user.id, EndReason::Revoked) .await?; if !ended.is_empty() { state.live.bump(&Topic::Account(user.id.clone())); changed(&state.live); record( cx, Actor::User(&viewer.user.id), AuditAction::AdminSessionsRevoked, Some(("user", &user.id)), json!({ "count": ended.len() }), ) .await; } Ok(done(&base, "sessions-revoked")) } /// `POST /admin/users/{id}/delete`. The address must be typed again. Deletes the account, its sessions, /// links and recovery codes, and then its photo file. The last enabled administrator cannot be deleted. #[route(POST "/admin/users/{id}/delete")] async fn delete_account(cx: &Cx, Form(form): Form) -> Result { let (viewer, user) = target(cx, &form.csrf).await?; let base = format!("/admin/users/{}", user.id); if user.id == viewer.user.id { return Ok(refused(&base, "self-delete")); } if normalize_email(&form.confirm) != user.email { return Ok(refused(&base, "confirm-email")); } let state = app_context::(cx); match state.store.delete_user(&user.id).await { Ok(true) => { if let Err(error) = im_core::photo::remove_photo(&state.config.data_dir, &user.id) { tracing::error!(error = %error, "photo of a deleted account not removed"); } state.live.bump(&Topic::Account(user.id.clone())); changed(&state.live); record( cx, Actor::User(&viewer.user.id), AuditAction::UserDeleted, Some(("user", &user.id)), json!({}), ) .await; Ok(done("/admin/users", "deleted")) } Ok(false) => Ok(done("/admin/users", "deleted")), Err(CoreError::Conflict(_)) => Ok(refused(&base, "last-admin")), Err(error) => Err(error.into()), } }