//! The administrator area: users, invitations, services and clients, mail, message, policy settings, signing //! keys, the audit log and health. //! //! Every page and every form here calls [`require_admin`] (or [`require_admin_csrf`] for a form). A member, or //! anyone signed out, gets the styled 404 before anything else happens, so the area does not reveal itself. //! A form also checks its CSRF token before any side effect, and answers 403 when the token is wrong. //! //! Writes redirect (Post/Redirect/Get) with a short code in the query string: `?notice=` for success, //! `?error=` for a refusal. The codes map to translated text in [`notice_text`] and [`error_text`]. A //! write that changes what an admin page shows calls [`changed`], which wakes the page's live stream //! (`/admin/events`). A write that changes what a person sees of their own account also bumps that account's //! topic, so their open pages refresh. pub mod audit; pub mod clients; pub mod health; pub mod invites; pub mod keys; pub mod mail; pub mod message; pub mod settings; pub mod users; #[cfg(test)] mod tests; use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, app_context}; use topcoat::router::error::{SeeOther, see_other}; use topcoat::router::response::Response; use topcoat::router::route; use topcoat::view::{View, component, view}; use crate::auth::require_admin; use crate::i18n::Lang; use crate::i18n::account::{Txt, text as account_text}; use crate::i18n::admin::{A, text}; use crate::live::{LiveHub, Topic, stream_changes}; use crate::state::AppState; use crate::views::{ViewerInfo, alert, notice, page_lang}; /// Rows per page of the long lists (users, mail, audit log). pub const PAGE_SIZE: u32 = 50; /// The query of every admin list and of the redirects after a write. #[derive(Deserialize, Default)] pub struct FlashQuery { /// A success code, see [`notice_text`]. #[serde(default)] pub notice: String, /// A refusal code, see [`error_text`]. #[serde(default)] pub error: String, } /// The tabs of the administrator area. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Tab { Users, Invites, Services, Mail, Message, Settings, Keys, Audit, Health, } /// The tab bar, with the current tab marked. #[component] pub async fn tabs(lang: Lang, current: Tab) -> Result { Ok(view! { }) } /// The CSS class of one tab: the current one is marked for the screen reader and the style. fn tab_class(current: Tab, tab: Tab) -> &'static str { if current == tab { "tab current" } else { "tab" } } /// Notifies the admin pages that something they show has changed. Call it after the write commits. pub fn changed(live: &LiveHub) { live.bump(&Topic::Admin); } /// The text of a success code, or `None` for an unknown code (which is then ignored). pub fn notice_text(lang: Lang, code: &str) -> Option<&'static str> { let key = match code { "disabled" => A::NoticeDisabled, "enabled" => A::NoticeEnabled, "admin-granted" => A::NoticeAdminGranted, "admin-removed" => A::NoticeAdminRemoved, "2fa-reset" => A::NoticeTwoFactorReset, "sessions-revoked" => A::NoticeSessionsRevoked, "deleted" => A::NoticeDeleted, "invite-revoked" => A::NoticeInviteRevoked, "invite-resent" => A::NoticeInviteResent, "invite-sent" => A::InviteQueued, "client-saved" => A::ClientSaved, "secret-rotated" => A::NoticeSecretRotated, "client-disabled" => A::NoticeClientDisabled, "mail-retried" => A::NoticeMailRetried, "mail-abandoned" => A::NoticeMailAbandoned, "test-queued" => A::NoticeTestQueued, "settings-saved" => A::NoticeSettingsSaved, "key-rotated" => A::NoticeKeyRotated, "key-retired" => A::NoticeKeyRetired, "file-value" => A::NoticeFileValue, "message-sent" => A::NoticeMessageSent, "backup-started" => A::NoticeBackupStarted, _ => return None, }; Some(text(lang, key)) } /// The text of a refusal code, or `None` for an unknown code. pub fn error_text(lang: Lang, code: &str) -> Option<&'static str> { let key = match code { "last-admin" => A::ErrLastAdmin, "self-disable" => A::ErrSelfDisable, "self-admin" => A::ErrSelfAdmin, "self-delete" => A::ErrSelfDelete, "self" => A::NoOwnAccountHere, "confirm-email" => A::ErrConfirmEmail, "mail-retry" => A::ErrMailNotRetryable, "mail-abandon" => A::ErrMailNotAbandonable, "message-empty" => A::ErrMessageEmpty, "message-subject" => A::ErrMessageSubjectLong, "message-body" => A::ErrMessageBodyLong, "message-email" => A::ErrMessageEmailInvalid, "rate-limited" => A::ErrMessageRateLimited, "key-current" => A::ErrKeyNotRetirable, "backup-off" => A::ErrBackupOff, "invite-gone" => A::ErrInviteGone, "no-client" => A::ErrNoSuchClient, "settings" => A::ErrSettingsInvalid, "invite-taken" => A::ErrInviteTaken, "email" => A::ErrInviteAddress, "client-name" => A::ErrClientName, "client-uri" => A::ErrUri, "family-key" => A::ErrFamilyKey, "family-taken" => A::ErrFamilyKeyTaken, "public-url" => A::ErrPublicUrl, "scopes" => A::ErrScopes, _ => return None, }; Some(text(lang, key)) } /// `path?error=`, the redirect of a refused write. pub fn refused(path: &str, code: &str) -> SeeOther { see_other(format!("{path}?error={code}")) } /// `path?notice=`, the redirect of a successful write. pub fn done(path: &str, code: &str) -> SeeOther { see_other(format!("{path}?notice={code}")) } /// The viewer's info and language for an admin page, after the admin check. pub fn frame_info(cx: &Cx, viewer: &crate::auth::Viewer) -> (Lang, ViewerInfo) { (page_lang(cx, Some(viewer)), ViewerInfo::of(viewer)) } /// `GET /admin`: the first tab. Non-administrators get 404. #[route(GET "/admin")] async fn admin_root(cx: &Cx) -> Result { require_admin(cx).await?; Ok(see_other("/admin/users")) } /// `GET /admin/events`: the live stream of the admin pages. It sends one `changed` event for each admin /// write, and the page fetches itself again. Non-administrators get 404. /// /// The session and the administrator role are checked again on every wake, before an event is sent. A /// session that ended, or an account that lost the role or was disabled, ends the stream. #[route(GET "/admin/events")] async fn admin_events(cx: &Cx) -> Result { let viewer = require_admin(cx).await?; let state = app_context::(cx); let live = state.live.clone(); let store = state.store.clone(); let session_id = viewer.session.id.clone(); let user_id = viewer.user.id.clone(); stream_changes(cx, &state.live, &[Topic::Admin], move || { let live = live.clone(); let store = store.clone(); let session_id = session_id.clone(); let user_id = user_id.clone(); async move { let session_live = store.session_is_live(&session_id).await?; let admin = store .user_by_id(&user_id) .await? .is_some_and(|user| user.is_admin && !user.is_disabled()); if !(session_live && admin) { return Err(topcoat::Error::msg( "the administrator stream is no longer allowed", )); } Ok(live.generation(&Topic::Admin).to_string()) } }) .await } /// A form with one button, and the CSRF token. `on` is sent as a hidden field; it is empty for most actions. #[component] pub async fn action_button( action: String, csrf: String, label: &'static str, class: &'static str, on: &'static str, ) -> Result { Ok(view! {
}) } /// The success notice and the alert of an admin page, drawn above its content. #[component] pub async fn flash_messages(success: Option, problem: Option) -> Result { Ok(view! { if let Some(message) = success { notice(message: message) } if let Some(message) = problem { alert(message: message) } }) }