Site announcement banner, admin health page, nav and styles
Browse files at this commit75640ff0003200fbe2262e1ef0f12f373db8be77Parent: c2816cd- feat
- site announcement banner, admin health page, nav and styles
24 changed files +2242 -10
- crates/forge-core/migrations/0055_user_suspensions.sql +10 -0
- crates/forge-core/src/audit.rs +17 -2
- crates/forge-core/src/config.rs +65 -0
- crates/forge-core/src/server_settings.rs +40 -0
- crates/forge-core/src/store/health.rs +67 -0
- crates/forge-core/src/store/migrate.rs +4 -0
- crates/forge-core/src/store/mod.rs +13 -4
- crates/forge-core/src/store/suspension.rs +263 -0
- crates/forge-web/src/i18n/accounts.rs +238 -0
- crates/forge-web/src/i18n/mod.rs +1 -0
- crates/forge-web/src/mail/account.rs +27 -0
- crates/forge-web/src/mail/templates.rs +12 -0
- crates/forge-web/src/pages/account_tools_tests.rs +347 -0
- crates/forge-web/src/pages/admin_health.rs +332 -0
- crates/forge-web/src/pages/admin_user_detail.rs +421 -0
- crates/forge-web/src/pages/admin_users.rs +7 -1
- crates/forge-web/src/pages/banner.rs +133 -0
- crates/forge-web/src/pages/login.rs +31 -3
- crates/forge-web/src/pages/mod.rs +5 -0
- crates/forge-web/src/pages/settings_security.rs +10 -0
- crates/forge-web/src/test_support.rs +1 -0
- crates/forge-web/src/views/mod.rs +24 -0
- style/_account_admin.scss +172 -0
- style/main.scss +2 -0
crates/forge-core/migrations/0055_user_suspensions.sqladded+10 -0
| @@ -0,0 +1,10 @@ | ||
| 1 | +-- A suspended account cannot sign in, its sessions, tokens and SSH keys stop working, and git | |
| 2 | +-- access is refused. One row per suspended user; deleting the row lifts the suspension. | |
| 3 | +-- Applied by store/migrate.rs. | |
| 4 | + | |
| 5 | +CREATE TABLE user_suspensions ( | |
| 6 | + user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, | |
| 7 | + reason TEXT NOT NULL DEFAULT '', | |
| 8 | + suspended_at TEXT NOT NULL, | |
| 9 | + suspended_by TEXT | |
| 10 | +); |
crates/forge-core/src/audit.rsmodified+17 -2
| @@ -103,6 +103,11 @@ pub enum AuditAction { | ||
| 103 | 103 | EmailVerified, |
| 104 | 104 | InviteSent, |
| 105 | 105 | InviteAccepted, |
| 106 | + UserSuspended, | |
| 107 | + UserUnsuspended, | |
| 108 | + AdminGranted, | |
| 109 | + AdminRevoked, | |
| 110 | + TotpDisabledByAdmin, | |
| 106 | 111 | } |
| 107 | 112 | |
| 108 | 113 | impl AuditAction { |
| @@ -202,6 +207,11 @@ impl AuditAction { | ||
| 202 | 207 | AuditAction::EmailVerified, |
| 203 | 208 | AuditAction::InviteSent, |
| 204 | 209 | AuditAction::InviteAccepted, |
| 210 | + AuditAction::UserSuspended, | |
| 211 | + AuditAction::UserUnsuspended, | |
| 212 | + AuditAction::AdminGranted, | |
| 213 | + AuditAction::AdminRevoked, | |
| 214 | + AuditAction::TotpDisabledByAdmin, | |
| 205 | 215 | ]; |
| 206 | 216 | |
| 207 | 217 | pub fn as_str(self) -> &'static str { |
| @@ -300,6 +310,11 @@ impl AuditAction { | ||
| 300 | 310 | AuditAction::EmailVerified => "email_verified", |
| 301 | 311 | AuditAction::InviteSent => "invite_sent", |
| 302 | 312 | AuditAction::InviteAccepted => "invite_accepted", |
| 313 | + AuditAction::UserSuspended => "user_suspended", | |
| 314 | + AuditAction::UserUnsuspended => "user_unsuspended", | |
| 315 | + AuditAction::AdminGranted => "admin_granted", | |
| 316 | + AuditAction::AdminRevoked => "admin_revoked", | |
| 317 | + AuditAction::TotpDisabledByAdmin => "totp_disabled_by_admin", | |
| 303 | 318 | } |
| 304 | 319 | } |
| 305 | 320 | |
| @@ -396,13 +411,13 @@ mod tests { | ||
| 396 | 411 | #[test] |
| 397 | 412 | fn names_are_unique_and_round_trip() { |
| 398 | 413 | let mut names: Vec<&str> = AuditAction::ALL.iter().map(|a| a.as_str()).collect(); |
| 399 | - assert_eq!(names.len(), 94); | |
| 414 | + assert_eq!(names.len(), 99); | |
| 400 | 415 | for action in AuditAction::ALL { |
| 401 | 416 | assert_eq!(AuditAction::parse(action.as_str()), Some(*action)); |
| 402 | 417 | } |
| 403 | 418 | names.sort(); |
| 404 | 419 | names.dedup(); |
| 405 | - assert_eq!(names.len(), 94); | |
| 420 | + assert_eq!(names.len(), 99); | |
| 406 | 421 | assert_eq!(AuditAction::parse("nope"), None); |
| 407 | 422 | } |
| 408 | 423 |
crates/forge-core/src/config.rsmodified+65 -0
| @@ -105,6 +105,71 @@ pub struct Config { | ||
| 105 | 105 | /// Self-update after a green CI run of the forge's own repo, from the `[self_update]` section. |
| 106 | 106 | #[serde(default)] |
| 107 | 107 | pub self_update: SelfUpdateConfig, |
| 108 | + /// Site announcement shown under every page header, from the `[banner]` section. | |
| 109 | + #[serde(default)] | |
| 110 | + pub banner: BannerConfig, | |
| 111 | +} | |
| 112 | + | |
| 113 | +/// Site announcement banner. An empty `message` shows nothing. | |
| 114 | +#[derive(Debug, Clone, Deserialize)] | |
| 115 | +#[serde(deny_unknown_fields, default)] | |
| 116 | +pub struct BannerConfig { | |
| 117 | + /// One line of text. Empty turns the banner off. | |
| 118 | + pub message: String, | |
| 119 | + /// `info` or `warning`. | |
| 120 | + pub level: String, | |
| 121 | + /// UTC time as `YYYY-MM-DD HH:MM` after which the banner disappears. Empty for never. | |
| 122 | + pub expires: String, | |
| 123 | +} | |
| 124 | + | |
| 125 | +impl Default for BannerConfig { | |
| 126 | + fn default() -> Self { | |
| 127 | + BannerConfig { | |
| 128 | + message: String::new(), | |
| 129 | + level: "info".into(), | |
| 130 | + expires: String::new(), | |
| 131 | + } | |
| 132 | + } | |
| 133 | +} | |
| 134 | + | |
| 135 | +impl BannerConfig { | |
| 136 | + /// Unix seconds of `expires`, or `None` when unset or malformed. | |
| 137 | + pub fn expires_unix(&self) -> Option<i64> { | |
| 138 | + parse_banner_expiry(&self.expires) | |
| 139 | + } | |
| 140 | + | |
| 141 | + /// Whether the banner shows at `now` (unix seconds). | |
| 142 | + pub fn active_at(&self, now: i64) -> bool { | |
| 143 | + !self.message.trim().is_empty() && self.expires_unix().is_none_or(|t| now < t) | |
| 144 | + } | |
| 145 | +} | |
| 146 | + | |
| 147 | +/// Parses `YYYY-MM-DD HH:MM` (UTC) into unix seconds. | |
| 148 | +pub fn parse_banner_expiry(raw: &str) -> Option<i64> { | |
| 149 | + let raw = raw.trim(); | |
| 150 | + let (date, time) = raw.split_once(' ')?; | |
| 151 | + let mut d = date.split('-'); | |
| 152 | + let (y, m, day): (i64, i64, i64) = ( | |
| 153 | + d.next()?.parse().ok()?, | |
| 154 | + d.next()?.parse().ok()?, | |
| 155 | + d.next()?.parse().ok()?, | |
| 156 | + ); | |
| 157 | + if d.next().is_some() || !(1..=12).contains(&m) || !(1..=31).contains(&day) { | |
| 158 | + return None; | |
| 159 | + } | |
| 160 | + let (hh, mm) = time.split_once(':')?; | |
| 161 | + let (hh, mm): (i64, i64) = (hh.parse().ok()?, mm.parse().ok()?); | |
| 162 | + if !(0..24).contains(&hh) || !(0..60).contains(&mm) || y < 1970 { | |
| 163 | + return None; | |
| 164 | + } | |
| 165 | + // Days from civil (Howard Hinnant). | |
| 166 | + let y2 = if m <= 2 { y - 1 } else { y }; | |
| 167 | + let era = y2 / 400; | |
| 168 | + let yoe = y2 - era * 400; | |
| 169 | + let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + day - 1; | |
| 170 | + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; | |
| 171 | + let days = era * 146_097 + doe - 719_468; | |
| 172 | + Some(days * 86_400 + hh * 3_600 + mm * 60) | |
| 108 | 173 | } |
| 109 | 174 | |
| 110 | 175 | /// Self-update, from the `[self_update]` section. When enabled, a successful push run of `repo` |
crates/forge-core/src/server_settings.rsmodified+40 -0
| @@ -121,6 +121,7 @@ use Group::{Backups, General, Integrations, Limits, Storage}; | ||
| 121 | 121 | use Kind::{Live as L, ReadOnly as R, Restart as X}; |
| 122 | 122 | |
| 123 | 123 | const REGISTRATION: &[&str] = &["closed", "invite", "open"]; |
| 124 | +const BANNER_LEVEL: &[&str] = &["info", "warning"]; | |
| 124 | 125 | const ORG_CREATION: &[&str] = &["all", "admin"]; |
| 125 | 126 | const MAIL_TRANSPORT: &[&str] = &["smtp", "log"]; |
| 126 | 127 | const BACKEND: &[&str] = &["fs", "s3", "r2"]; |
| @@ -146,6 +147,30 @@ pub static FIELDS: &[Field] = &[ | ||
| 146 | 147 | "Organization creation", |
| 147 | 148 | "Who may create an organization: all signed-in people, or admins only.", |
| 148 | 149 | ), |
| 150 | + f( | |
| 151 | + "banner.message", | |
| 152 | + General, | |
| 153 | + L, | |
| 154 | + Ty::Text, | |
| 155 | + "Announcement banner", | |
| 156 | + "One line shown under the header on every page. Empty hides it.", | |
| 157 | + ), | |
| 158 | + f( | |
| 159 | + "banner.level", | |
| 160 | + General, | |
| 161 | + L, | |
| 162 | + Ty::Choice(BANNER_LEVEL), | |
| 163 | + "Banner level", | |
| 164 | + "info or warning.", | |
| 165 | + ), | |
| 166 | + f( | |
| 167 | + "banner.expires", | |
| 168 | + General, | |
| 169 | + L, | |
| 170 | + Ty::Text, | |
| 171 | + "Banner expires (UTC)", | |
| 172 | + "As YYYY-MM-DD HH:MM. Empty keeps the banner until it is cleared.", | |
| 173 | + ), | |
| 149 | 174 | f( |
| 150 | 175 | "trusted_proxies", |
| 151 | 176 | General, |
| @@ -639,6 +664,15 @@ pub fn normalize(field: &Field, raw: &str) -> Result<String> { | ||
| 639 | 664 | "must be one line of at most 1024 characters", |
| 640 | 665 | )); |
| 641 | 666 | } |
| 667 | + if field.key == "banner.expires" | |
| 668 | + && !raw.is_empty() | |
| 669 | + && crate::config::parse_banner_expiry(raw).is_none() | |
| 670 | + { | |
| 671 | + return Err(invalid(field, "must look like 2026-12-31 18:00")); | |
| 672 | + } | |
| 673 | + if field.key == "banner.message" && raw.chars().count() > 300 { | |
| 674 | + return Err(invalid(field, "must be at most 300 characters")); | |
| 675 | + } | |
| 642 | 676 | Ok(raw.to_owned()) |
| 643 | 677 | } |
| 644 | 678 | Ty::List => { |
| @@ -714,6 +748,9 @@ pub fn get(cfg: &Config, key: &str) -> String { | ||
| 714 | 748 | .map(ToString::to_string) |
| 715 | 749 | .collect::<Vec<_>>() |
| 716 | 750 | .join(", "), |
| 751 | + "banner.message" => cfg.banner.message.clone(), | |
| 752 | + "banner.level" => cfg.banner.level.clone(), | |
| 753 | + "banner.expires" => cfg.banner.expires.clone(), | |
| 717 | 754 | "base_url" => cfg.base_url.clone(), |
| 718 | 755 | "user_content_base_url" => cfg.user_content_base_url.clone(), |
| 719 | 756 | "ssh_public_host" => cfg.ssh_public_host.clone(), |
| @@ -817,6 +854,9 @@ pub fn set(cfg: &mut Config, key: &str, raw: &str) -> Result<()> { | ||
| 817 | 854 | }) |
| 818 | 855 | .collect() |
| 819 | 856 | } |
| 857 | + "banner.message" => cfg.banner.message = s(), | |
| 858 | + "banner.level" => cfg.banner.level = s(), | |
| 859 | + "banner.expires" => cfg.banner.expires = s(), | |
| 820 | 860 | "base_url" => cfg.base_url = s(), |
| 821 | 861 | "user_content_base_url" => cfg.user_content_base_url = s(), |
| 822 | 862 | "ssh_public_host" => cfg.ssh_public_host = s(), |
crates/forge-core/src/store/health.rsadded+67 -0
| @@ -0,0 +1,67 @@ | ||
| 1 | +//! Cheap counts for the admin health page. | |
| 2 | + | |
| 3 | +use super::{Store, col_int, fetch_opt}; | |
| 4 | +use crate::error::{Error, Result}; | |
| 5 | +use crate::time::stamp_ago; | |
| 6 | + | |
| 7 | +/// Window in which a runner's last report counts as online. | |
| 8 | +pub const RUNNER_ONLINE_SECS: u64 = 90; | |
| 9 | + | |
| 10 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] | |
| 11 | +pub struct HealthCounts { | |
| 12 | + pub repos: i64, | |
| 13 | + pub users: i64, | |
| 14 | + pub queued_jobs: i64, | |
| 15 | + pub runners_online: i64, | |
| 16 | + pub runners_total: i64, | |
| 17 | +} | |
| 18 | + | |
| 19 | +impl Store { | |
| 20 | + /// Counts of repos, users, queued CI jobs and runners. Five indexed `COUNT(*)` queries. | |
| 21 | + pub async fn health_counts(&self) -> Result<HealthCounts> { | |
| 22 | + let conn = self.read_conn().await; | |
| 23 | + let since = stamp_ago(std::time::Duration::from_secs(RUNNER_ONLINE_SECS)); | |
| 24 | + let plain = |sql: &'static str| { | |
| 25 | + let conn = &conn; | |
| 26 | + async move { | |
| 27 | + Ok::<i64, Error>( | |
| 28 | + fetch_opt(conn, sql, (), |row| col_int(row, 0)) | |
| 29 | + .await? | |
| 30 | + .unwrap_or(0), | |
| 31 | + ) | |
| 32 | + } | |
| 33 | + }; | |
| 34 | + let online = fetch_opt( | |
| 35 | + &conn, | |
| 36 | + "SELECT COUNT(*) FROM ci_runners WHERE disabled = 0 AND last_seen_at > ?1", | |
| 37 | + (since,), | |
| 38 | + |row| col_int(row, 0), | |
| 39 | + ) | |
| 40 | + .await? | |
| 41 | + .unwrap_or(0); | |
| 42 | + Ok(HealthCounts { | |
| 43 | + repos: plain("SELECT COUNT(*) FROM repos").await?, | |
| 44 | + users: plain("SELECT COUNT(*) FROM users WHERE kind = 'user'").await?, | |
| 45 | + queued_jobs: plain("SELECT COUNT(*) FROM ci_jobs WHERE state = 'queued'").await?, | |
| 46 | + runners_online: online, | |
| 47 | + runners_total: plain("SELECT COUNT(*) FROM ci_runners").await?, | |
| 48 | + }) | |
| 49 | + } | |
| 50 | +} | |
| 51 | + | |
| 52 | +#[cfg(test)] | |
| 53 | +mod tests { | |
| 54 | + use super::*; | |
| 55 | + | |
| 56 | + #[tokio::test] | |
| 57 | + async fn counts_a_fresh_store() { | |
| 58 | + let dir = tempfile::tempdir().unwrap(); | |
| 59 | + let store = Store::open(&dir.path().join("f.db")).await.unwrap(); | |
| 60 | + store.create_user("tahinli", None, "h", true).await.unwrap(); | |
| 61 | + let c = store.health_counts().await.unwrap(); | |
| 62 | + assert_eq!( | |
| 63 | + (c.repos, c.users, c.queued_jobs, c.runners_online), | |
| 64 | + (0, 1, 0, 0) | |
| 65 | + ); | |
| 66 | + } | |
| 67 | +} |
crates/forge-core/src/store/migrate.rsmodified+4 -0
| @@ -91,6 +91,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ | ||
| 91 | 91 | 54, |
| 92 | 92 | include_str!("../../migrations/0054_ci_schedule_state.sql"), |
| 93 | 93 | ), |
| 94 | + ( | |
| 95 | + 55, | |
| 96 | + include_str!("../../migrations/0055_user_suspensions.sql"), | |
| 97 | + ), | |
| 94 | 98 | ]; |
| 95 | 99 | |
| 96 | 100 | /// The highest migration version this binary knows about. |
crates/forge-core/src/store/mod.rsmodified+13 -4
| @@ -11,6 +11,7 @@ pub mod contributions; | ||
| 11 | 11 | pub mod discussions; |
| 12 | 12 | pub mod edit_history_read; |
| 13 | 13 | pub mod exports; |
| 14 | +pub mod health; | |
| 14 | 15 | pub mod imports; |
| 15 | 16 | pub mod issues; |
| 16 | 17 | pub mod labels; |
| @@ -37,6 +38,7 @@ pub mod signatures; | ||
| 37 | 38 | pub mod snapshot; |
| 38 | 39 | pub mod snippets; |
| 39 | 40 | pub mod suggest; |
| 41 | +pub mod suspension; | |
| 40 | 42 | pub mod transfers; |
| 41 | 43 | pub mod ui_prefs; |
| 42 | 44 | pub mod user_delete; |
| @@ -378,7 +380,10 @@ impl Store { | ||
| 378 | 380 | let conn = self.read_conn().await; |
| 379 | 381 | fetch_opt( |
| 380 | 382 | &conn, |
| 381 | - &format!("SELECT {SESSION_COLS} FROM sessions WHERE token_hash = ?1 AND expires_at > ?2 LIMIT 1"), | |
| 383 | + &format!( | |
| 384 | + "SELECT {SESSION_COLS} FROM sessions WHERE token_hash = ?1 AND expires_at > ?2 \ | |
| 385 | + AND user_id NOT IN (SELECT user_id FROM user_suspensions) LIMIT 1" | |
| 386 | + ), | |
| 382 | 387 | (token_hash.to_string(), now_stamp()), |
| 383 | 388 | map_session, |
| 384 | 389 | ) |
| @@ -470,7 +475,10 @@ impl Store { | ||
| 470 | 475 | let conn = self.read_conn().await; |
| 471 | 476 | fetch_opt( |
| 472 | 477 | &conn, |
| 473 | - &format!("SELECT {SSH_KEY_COLS} FROM ssh_keys WHERE key_blob = ?1 LIMIT 1"), | |
| 478 | + &format!( | |
| 479 | + "SELECT {SSH_KEY_COLS} FROM ssh_keys WHERE key_blob = ?1 \ | |
| 480 | + AND user_id NOT IN (SELECT user_id FROM user_suspensions) LIMIT 1" | |
| 481 | + ), | |
| 474 | 482 | (key_blob.to_vec(),), |
| 475 | 483 | map_ssh_key, |
| 476 | 484 | ) |
| @@ -557,7 +565,8 @@ impl Store { | ||
| 557 | 565 | &conn, |
| 558 | 566 | &format!( |
| 559 | 567 | "SELECT {TOKEN_COLS} FROM access_tokens \ |
| 560 | - WHERE token_hash = ?1 AND (expires_at IS NULL OR expires_at > ?2) LIMIT 1" | |
| 568 | + WHERE token_hash = ?1 AND (expires_at IS NULL OR expires_at > ?2) \ | |
| 569 | + AND user_id NOT IN (SELECT user_id FROM user_suspensions) LIMIT 1" | |
| 561 | 570 | ), |
| 562 | 571 | (token_hash.to_string(), now_stamp()), |
| 563 | 572 | map_token, |
| @@ -1016,7 +1025,7 @@ fn col_blob(row: &Row, i: usize) -> Result<Vec<u8>> { | ||
| 1016 | 1025 | } |
| 1017 | 1026 | } |
| 1018 | 1027 | |
| 1019 | -fn col_int(row: &Row, i: usize) -> Result<i64> { | |
| 1028 | +pub(crate) fn col_int(row: &Row, i: usize) -> Result<i64> { | |
| 1020 | 1029 | match row.get_value(i).map_err(db_err)? { |
| 1021 | 1030 | Value::Integer(n) => Ok(n), |
| 1022 | 1031 | _ => Err(Error::Database(format!("column {i} is not an integer"))), |
crates/forge-core/src/store/suspension.rsadded+263 -0
| @@ -0,0 +1,263 @@ | ||
| 1 | +//! Account suspension and the admin-only account facts (migration 0059). | |
| 2 | +//! | |
| 3 | +//! A suspended user keeps their data but cannot sign in. The session, token and SSH key lookups | |
| 4 | +//! in `store/mod.rs` skip a suspended owner, so every transport stops at once. | |
| 5 | + | |
| 6 | +use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_opt}; | |
| 7 | +use crate::error::{Error, Result}; | |
| 8 | +use crate::time::now_stamp; | |
| 9 | + | |
| 10 | +/// Longest accepted suspension reason, in characters. | |
| 11 | +pub const MAX_REASON_CHARS: usize = 300; | |
| 12 | + | |
| 13 | +/// Why and when an account was suspended. | |
| 14 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 15 | +pub struct Suspension { | |
| 16 | + pub reason: String, | |
| 17 | + pub suspended_at: String, | |
| 18 | +} | |
| 19 | + | |
| 20 | +/// Facts the admin user page shows. | |
| 21 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 22 | +pub struct AccountFacts { | |
| 23 | + pub repo_count: i64, | |
| 24 | + /// RFC 3339 stamp of the last successful sign-in in the audit log. | |
| 25 | + pub last_login: Option<String>, | |
| 26 | + pub two_factor: bool, | |
| 27 | +} | |
| 28 | + | |
| 29 | +impl Store { | |
| 30 | + /// The suspension of `user_id`, if any. | |
| 31 | + pub async fn suspension(&self, user_id: &str) -> Result<Option<Suspension>> { | |
| 32 | + let conn = self.read_conn().await; | |
| 33 | + fetch_opt( | |
| 34 | + &conn, | |
| 35 | + "SELECT reason, suspended_at FROM user_suspensions WHERE user_id = ?1 LIMIT 1", | |
| 36 | + (user_id.to_string(),), | |
| 37 | + |row| { | |
| 38 | + Ok(Suspension { | |
| 39 | + reason: col_text(row, 0)?, | |
| 40 | + suspended_at: col_text(row, 1)?, | |
| 41 | + }) | |
| 42 | + }, | |
| 43 | + ) | |
| 44 | + .await | |
| 45 | + } | |
| 46 | + | |
| 47 | + /// Suspends `user_id` and signs out every session. Refused for an organization and for the | |
| 48 | + /// last administrator who is not suspended. | |
| 49 | + pub async fn suspend_user(&self, user_id: &str, reason: &str, by: Option<&str>) -> Result<()> { | |
| 50 | + let reason = reason.trim(); | |
| 51 | + if reason.chars().count() > MAX_REASON_CHARS || reason.chars().any(char::is_control) { | |
| 52 | + return Err(Error::Invalid(format!( | |
| 53 | + "the reason must be one line of at most {MAX_REASON_CHARS} characters" | |
| 54 | + ))); | |
| 55 | + } | |
| 56 | + let conn = self.inner.conn.lock().await; | |
| 57 | + let uid = user_id.to_string(); | |
| 58 | + let row = fetch_opt( | |
| 59 | + &conn, | |
| 60 | + "SELECT is_admin, kind FROM users WHERE id = ?1 LIMIT 1", | |
| 61 | + (uid.clone(),), | |
| 62 | + |row| Ok((col_int(row, 0)? != 0, col_text(row, 1)?)), | |
| 63 | + ) | |
| 64 | + .await? | |
| 65 | + .ok_or(Error::NotFound)?; | |
| 66 | + if row.1 == "org" { | |
| 67 | + return Err(Error::Invalid("an organization cannot be suspended".into())); | |
| 68 | + } | |
| 69 | + if row.0 { | |
| 70 | + let others = fetch_opt( | |
| 71 | + &conn, | |
| 72 | + "SELECT COUNT(*) FROM users WHERE is_admin = 1 AND id != ?1 \ | |
| 73 | + AND id NOT IN (SELECT user_id FROM user_suspensions)", | |
| 74 | + (uid.clone(),), | |
| 75 | + |row| col_int(row, 0), | |
| 76 | + ) | |
| 77 | + .await? | |
| 78 | + .unwrap_or(0); | |
| 79 | + if others == 0 { | |
| 80 | + return Err(Error::Conflict( | |
| 81 | + "cannot suspend the last active administrator".into(), | |
| 82 | + )); | |
| 83 | + } | |
| 84 | + } | |
| 85 | + conn.execute( | |
| 86 | + "INSERT INTO user_suspensions (user_id, reason, suspended_at, suspended_by) \ | |
| 87 | + VALUES (?1, ?2, ?3, ?4) ON CONFLICT(user_id) DO UPDATE SET reason = excluded.reason", | |
| 88 | + ( | |
| 89 | + uid.clone(), | |
| 90 | + reason.to_string(), | |
| 91 | + now_stamp(), | |
| 92 | + by.map(str::to_string), | |
| 93 | + ), | |
| 94 | + ) | |
| 95 | + .await | |
| 96 | + .map_err(db_err)?; | |
| 97 | + conn.execute("DELETE FROM sessions WHERE user_id = ?1", (uid,)) | |
| 98 | + .await | |
| 99 | + .map_err(db_err)?; | |
| 100 | + Ok(()) | |
| 101 | + } | |
| 102 | + | |
| 103 | + /// Lifts a suspension. Returns whether one existed. | |
| 104 | + pub async fn unsuspend_user(&self, user_id: &str) -> Result<bool> { | |
| 105 | + let conn = self.inner.conn.lock().await; | |
| 106 | + let n = conn | |
| 107 | + .execute( | |
| 108 | + "DELETE FROM user_suspensions WHERE user_id = ?1", | |
| 109 | + (user_id.to_string(),), | |
| 110 | + ) | |
| 111 | + .await | |
| 112 | + .map_err(db_err)?; | |
| 113 | + Ok(n > 0) | |
| 114 | + } | |
| 115 | + | |
| 116 | + /// Grants or revokes the admin flag. Revoking is refused for the last administrator. | |
| 117 | + pub async fn set_admin(&self, user_id: &str, admin: bool) -> Result<()> { | |
| 118 | + let conn = self.inner.conn.lock().await; | |
| 119 | + let uid = user_id.to_string(); | |
| 120 | + let kind = fetch_opt( | |
| 121 | + &conn, | |
| 122 | + "SELECT kind FROM users WHERE id = ?1 LIMIT 1", | |
| 123 | + (uid.clone(),), | |
| 124 | + |row| col_text(row, 0), | |
| 125 | + ) | |
| 126 | + .await? | |
| 127 | + .ok_or(Error::NotFound)?; | |
| 128 | + if kind == "org" { | |
| 129 | + return Err(Error::Invalid( | |
| 130 | + "an organization cannot be an administrator".into(), | |
| 131 | + )); | |
| 132 | + } | |
| 133 | + if !admin { | |
| 134 | + let others = fetch_opt( | |
| 135 | + &conn, | |
| 136 | + "SELECT COUNT(*) FROM users WHERE is_admin = 1 AND id != ?1 AND kind = 'user'", | |
| 137 | + (uid.clone(),), | |
| 138 | + |row| col_int(row, 0), | |
| 139 | + ) | |
| 140 | + .await? | |
| 141 | + .unwrap_or(0); | |
| 142 | + if others == 0 { | |
| 143 | + return Err(Error::Conflict( | |
| 144 | + "cannot remove the last administrator".into(), | |
| 145 | + )); | |
| 146 | + } | |
| 147 | + } | |
| 148 | + conn.execute( | |
| 149 | + "UPDATE users SET is_admin = ?2 WHERE id = ?1", | |
| 150 | + (uid, i64::from(admin)), | |
| 151 | + ) | |
| 152 | + .await | |
| 153 | + .map_err(db_err)?; | |
| 154 | + Ok(()) | |
| 155 | + } | |
| 156 | + | |
| 157 | + /// Repo count, last sign-in and 2FA state for the admin user page. | |
| 158 | + pub async fn account_facts(&self, user_id: &str) -> Result<AccountFacts> { | |
| 159 | + let conn = self.read_conn().await; | |
| 160 | + let uid = user_id.to_string(); | |
| 161 | + let repo_count = fetch_opt( | |
| 162 | + &conn, | |
| 163 | + "SELECT COUNT(*) FROM repos WHERE owner_id = ?1", | |
| 164 | + (uid.clone(),), | |
| 165 | + |row| col_int(row, 0), | |
| 166 | + ) | |
| 167 | + .await? | |
| 168 | + .unwrap_or(0); | |
| 169 | + let last_login = fetch_opt( | |
| 170 | + &conn, | |
| 171 | + "SELECT MAX(at) FROM audit_log WHERE actor_id = ?1 AND action = 'login_success'", | |
| 172 | + (uid.clone(),), | |
| 173 | + |row| col_opt_text(row, 0), | |
| 174 | + ) | |
| 175 | + .await? | |
| 176 | + .flatten(); | |
| 177 | + let two_factor = fetch_opt( | |
| 178 | + &conn, | |
| 179 | + "SELECT totp_enabled FROM users WHERE id = ?1 LIMIT 1", | |
| 180 | + (uid,), | |
| 181 | + |row| Ok(col_int(row, 0)? != 0), | |
| 182 | + ) | |
| 183 | + .await? | |
| 184 | + .unwrap_or(false); | |
| 185 | + Ok(AccountFacts { | |
| 186 | + repo_count, | |
| 187 | + last_login, | |
| 188 | + two_factor, | |
| 189 | + }) | |
| 190 | + } | |
| 191 | +} | |
| 192 | + | |
| 193 | +#[cfg(test)] | |
| 194 | +mod tests { | |
| 195 | + use super::*; | |
| 196 | + | |
| 197 | + async fn fixture() -> ( | |
| 198 | + Store, | |
| 199 | + crate::model::User, | |
| 200 | + crate::model::User, | |
| 201 | + tempfile::TempDir, | |
| 202 | + ) { | |
| 203 | + let dir = tempfile::tempdir().unwrap(); | |
| 204 | + let store = Store::open(&dir.path().join("f.db")).await.unwrap(); | |
| 205 | + let admin = store.create_user("tahinli", None, "h", true).await.unwrap(); | |
| 206 | + let other = store.create_user("carol", None, "h", false).await.unwrap(); | |
| 207 | + (store, admin, other, dir) | |
| 208 | + } | |
| 209 | + | |
| 210 | + #[tokio::test] | |
| 211 | + async fn suspension_blocks_sessions_and_lifts() { | |
| 212 | + let (store, _admin, other, _d) = fixture().await; | |
| 213 | + store | |
| 214 | + .create_session(&other.id, "th", "csrf", "2999-01-01T00:00:00Z", None) | |
| 215 | + .await | |
| 216 | + .unwrap(); | |
| 217 | + assert!(store.session_by_token_hash("th").await.unwrap().is_some()); | |
| 218 | + store.suspend_user(&other.id, "spam", None).await.unwrap(); | |
| 219 | + assert!(store.session_by_token_hash("th").await.unwrap().is_none()); | |
| 220 | + assert_eq!( | |
| 221 | + store.suspension(&other.id).await.unwrap().unwrap().reason, | |
| 222 | + "spam" | |
| 223 | + ); | |
| 224 | + assert!(store.unsuspend_user(&other.id).await.unwrap()); | |
| 225 | + assert!(store.suspension(&other.id).await.unwrap().is_none()); | |
| 226 | + } | |
| 227 | + | |
| 228 | + #[tokio::test] | |
| 229 | + async fn last_admin_cannot_be_demoted_or_suspended() { | |
| 230 | + let (store, admin, other, _d) = fixture().await; | |
| 231 | + assert!(matches!( | |
| 232 | + store.set_admin(&admin.id, false).await, | |
| 233 | + Err(Error::Conflict(_)) | |
| 234 | + )); | |
| 235 | + assert!(matches!( | |
| 236 | + store.suspend_user(&admin.id, "", None).await, | |
| 237 | + Err(Error::Conflict(_)) | |
| 238 | + )); | |
| 239 | + store.set_admin(&other.id, true).await.unwrap(); | |
| 240 | + store.set_admin(&admin.id, false).await.unwrap(); | |
| 241 | + } | |
| 242 | + | |
| 243 | + #[tokio::test] | |
| 244 | + async fn suspension_stops_tokens_and_ssh_keys() { | |
| 245 | + let (store, _admin, other, _d) = fixture().await; | |
| 246 | + store | |
| 247 | + .create_token(&other.id, "ci", "tokhash", &["repo".to_owned()], None) | |
| 248 | + .await | |
| 249 | + .unwrap(); | |
| 250 | + store | |
| 251 | + .add_ssh_key(&other.id, "laptop", "ssh-ed25519", b"blob", "SHA256:x") | |
| 252 | + .await | |
| 253 | + .unwrap(); | |
| 254 | + assert!(store.token_by_hash("tokhash").await.unwrap().is_some()); | |
| 255 | + assert!(store.ssh_key_by_blob(b"blob").await.unwrap().is_some()); | |
| 256 | + store.suspend_user(&other.id, "", None).await.unwrap(); | |
| 257 | + assert!(store.token_by_hash("tokhash").await.unwrap().is_none()); | |
| 258 | + assert!(store.ssh_key_by_blob(b"blob").await.unwrap().is_none()); | |
| 259 | + store.unsuspend_user(&other.id).await.unwrap(); | |
| 260 | + assert!(store.token_by_hash("tokhash").await.unwrap().is_some()); | |
| 261 | + assert!(store.ssh_key_by_blob(b"blob").await.unwrap().is_some()); | |
| 262 | + } | |
| 263 | +} |
crates/forge-web/src/i18n/accounts.rsadded+238 -0
| @@ -0,0 +1,238 @@ | ||
| 1 | +//! Strings for admin account tools, the announcement banner and the health page. | |
| 2 | + | |
| 3 | +use super::Lang; | |
| 4 | + | |
| 5 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 6 | +pub enum A { | |
| 7 | + Status, | |
| 8 | + Active, | |
| 9 | + Suspended, | |
| 10 | + LastLogin, | |
| 11 | + Repositories, | |
| 12 | + TwoFactor, | |
| 13 | + On, | |
| 14 | + Off, | |
| 15 | + Administrator, | |
| 16 | + Suspend, | |
| 17 | + Unsuspend, | |
| 18 | + SuspendReason, | |
| 19 | + SuspendHelp, | |
| 20 | + GrantAdmin, | |
| 21 | + RevokeAdmin, | |
| 22 | + AdminHelp, | |
| 23 | + ResetPassword, | |
| 24 | + GenerateLink, | |
| 25 | + ResetHelp, | |
| 26 | + ResetLinkReady, | |
| 27 | + Disable2fa, | |
| 28 | + Disable2faHelp, | |
| 29 | + Actions, | |
| 30 | + OkSuspended, | |
| 31 | + OkUnsuspended, | |
| 32 | + OkAdminOn, | |
| 33 | + OkAdminOff, | |
| 34 | + Ok2faDisabled, | |
| 35 | + ErrSelf, | |
| 36 | + ErrNoEmail, | |
| 37 | + AccountSuspended, | |
| 38 | + Dismiss, | |
| 39 | + Health, | |
| 40 | + DataDirectory, | |
| 41 | + BackupDirectory, | |
| 42 | + DatabaseFile, | |
| 43 | + RepoStorage, | |
| 44 | + Free, | |
| 45 | + CiQueue, | |
| 46 | + QueuedJobs, | |
| 47 | + RunnersOnline, | |
| 48 | + MailQueue, | |
| 49 | + Pending, | |
| 50 | + Failed, | |
| 51 | + LastBackup, | |
| 52 | + Replication, | |
| 53 | + Uptime, | |
| 54 | + Version, | |
| 55 | + NotConfigured, | |
| 56 | + Unavailable, | |
| 57 | + Never, | |
| 58 | + Ok, | |
| 59 | + Error, | |
| 60 | + Lagging, | |
| 61 | + HealthIntro, | |
| 62 | +} | |
| 63 | + | |
| 64 | +pub fn t(lang: Lang, key: A) -> &'static str { | |
| 65 | + use A::*; | |
| 66 | + use Lang::*; | |
| 67 | + match (key, lang) { | |
| 68 | + (Status, En) => "Status", | |
| 69 | + (Status, Tr) => "Durum", | |
| 70 | + (Active, En) => "Active", | |
| 71 | + (Active, Tr) => "Etkin", | |
| 72 | + (Suspended, En) => "Suspended", | |
| 73 | + (Suspended, Tr) => "Askıda", | |
| 74 | + (LastLogin, En) => "Last sign-in", | |
| 75 | + (LastLogin, Tr) => "Son giriş", | |
| 76 | + (Repositories, En) => "Repositories", | |
| 77 | + (Repositories, Tr) => "Depolar", | |
| 78 | + (TwoFactor, En) => "Two-factor", | |
| 79 | + (TwoFactor, Tr) => "İki adımlı doğrulama", | |
| 80 | + (On, En) => "On", | |
| 81 | + (On, Tr) => "Açık", | |
| 82 | + (Off, En) => "Off", | |
| 83 | + (Off, Tr) => "Kapalı", | |
| 84 | + (Administrator, En) => "Administrator", | |
| 85 | + (Administrator, Tr) => "Yönetici", | |
| 86 | + (Suspend, En) => "Suspend", | |
| 87 | + (Suspend, Tr) => "Askıya al", | |
| 88 | + (Unsuspend, En) => "Lift suspension", | |
| 89 | + (Unsuspend, Tr) => "Askıyı kaldır", | |
| 90 | + (SuspendReason, En) => "Reason shown on the login page", | |
| 91 | + (SuspendReason, Tr) => "Giriş sayfasında gösterilen neden", | |
| 92 | + (SuspendHelp, En) => { | |
| 93 | + "Signs the user out everywhere and stops their tokens and keys, including git over SSH and HTTP." | |
| 94 | + } | |
| 95 | + (SuspendHelp, Tr) => { | |
| 96 | + "Kullanıcının tüm oturumlarını kapatır; belirteçlerini ve anahtarlarını (SSH ve HTTP üzerinden git dahil) durdurur." | |
| 97 | + } | |
| 98 | + (GrantAdmin, En) => "Make administrator", | |
| 99 | + (GrantAdmin, Tr) => "Yönetici yap", | |
| 100 | + (RevokeAdmin, En) => "Remove administrator", | |
| 101 | + (RevokeAdmin, Tr) => "Yöneticiliği kaldır", | |
| 102 | + (AdminHelp, En) => "The last administrator cannot be demoted.", | |
| 103 | + (AdminHelp, Tr) => "Son yönetici yetkisiz bırakılamaz.", | |
| 104 | + (ResetPassword, En) => "Reset password", | |
| 105 | + (ResetPassword, Tr) => "Parolayı sıfırla", | |
| 106 | + (GenerateLink, En) => "Generate reset link", | |
| 107 | + (GenerateLink, Tr) => "Sıfırlama bağlantısı üret", | |
| 108 | + (ResetHelp, En) => { | |
| 109 | + "Makes a one-time link that works for an hour. Their current sessions are signed out." | |
| 110 | + } | |
| 111 | + (ResetHelp, Tr) => { | |
| 112 | + "Bir saat geçerli, tek kullanımlık bir bağlantı üretir. Mevcut oturumları kapatılır." | |
| 113 | + } | |
| 114 | + (ResetLinkReady, En) => "One-time reset link. It is shown only now:", | |
| 115 | + (ResetLinkReady, Tr) => "Tek kullanımlık sıfırlama bağlantısı. Yalnızca şimdi gösterilir:", | |
| 116 | + (Disable2fa, En) => "Disable two-factor", | |
| 117 | + (Disable2fa, Tr) => "İki adımlı doğrulamayı kapat", | |
| 118 | + (Disable2faHelp, En) => "For a locked-out user. Clears the secret and the recovery codes.", | |
| 119 | + (Disable2faHelp, Tr) => { | |
| 120 | + "Hesabına giremeyen kullanıcı için. Sırrı ve kurtarma kodlarını siler." | |
| 121 | + } | |
| 122 | + (Actions, En) => "Actions", | |
| 123 | + (Actions, Tr) => "İşlemler", | |
| 124 | + (OkSuspended, En) => "Account suspended.", | |
| 125 | + (OkSuspended, Tr) => "Hesap askıya alındı.", | |
| 126 | + (OkUnsuspended, En) => "Suspension lifted.", | |
| 127 | + (OkUnsuspended, Tr) => "Askı kaldırıldı.", | |
| 128 | + (OkAdminOn, En) => "Administrator rights granted.", | |
| 129 | + (OkAdminOn, Tr) => "Yönetici yetkisi verildi.", | |
| 130 | + (OkAdminOff, En) => "Administrator rights removed.", | |
| 131 | + (OkAdminOff, Tr) => "Yönetici yetkisi kaldırıldı.", | |
| 132 | + (Ok2faDisabled, En) => "Two-factor disabled.", | |
| 133 | + (Ok2faDisabled, Tr) => "İki adımlı doğrulama kapatıldı.", | |
| 134 | + (ErrSelf, En) => "You cannot do this to your own account.", | |
| 135 | + (ErrSelf, Tr) => "Bunu kendi hesabınıza yapamazsınız.", | |
| 136 | + (ErrNoEmail, En) => "Nothing to do.", | |
| 137 | + (ErrNoEmail, Tr) => "Yapılacak bir şey yok.", | |
| 138 | + (AccountSuspended, En) => "This account is suspended.", | |
| 139 | + (AccountSuspended, Tr) => "Bu hesap askıya alındı.", | |
| 140 | + (Dismiss, En) => "Dismiss", | |
| 141 | + (Dismiss, Tr) => "Kapat", | |
| 142 | + (Health, En) => "Health", | |
| 143 | + (Health, Tr) => "Sağlık", | |
| 144 | + (DataDirectory, En) => "Data directory", | |
| 145 | + (DataDirectory, Tr) => "Veri dizini", | |
| 146 | + (BackupDirectory, En) => "Backup directory", | |
| 147 | + (BackupDirectory, Tr) => "Yedek dizini", | |
| 148 | + (DatabaseFile, En) => "Database file", | |
| 149 | + (DatabaseFile, Tr) => "Veritabanı dosyası", | |
| 150 | + (RepoStorage, En) => "Repositories on disk", | |
| 151 | + (RepoStorage, Tr) => "Diskteki depolar", | |
| 152 | + (Free, En) => "free of", | |
| 153 | + (Free, Tr) => "boş, toplam", | |
| 154 | + (CiQueue, En) => "CI queue", | |
| 155 | + (CiQueue, Tr) => "CI kuyruğu", | |
| 156 | + (QueuedJobs, En) => "queued jobs", | |
| 157 | + (QueuedJobs, Tr) => "bekleyen iş", | |
| 158 | + (RunnersOnline, En) => "runners online", | |
| 159 | + (RunnersOnline, Tr) => "çalıştırıcı çevrimiçi", | |
| 160 | + (MailQueue, En) => "Mail queue", | |
| 161 | + (MailQueue, Tr) => "Posta kuyruğu", | |
| 162 | + (Pending, En) => "pending", | |
| 163 | + (Pending, Tr) => "bekleyen", | |
| 164 | + (Failed, En) => "failed", | |
| 165 | + (Failed, Tr) => "başarısız", | |
| 166 | + (LastBackup, En) => "Last backup", | |
| 167 | + (LastBackup, Tr) => "Son yedek", | |
| 168 | + (Replication, En) => "Replication", | |
| 169 | + (Replication, Tr) => "Çoğaltma", | |
| 170 | + (Uptime, En) => "Uptime", | |
| 171 | + (Uptime, Tr) => "Çalışma süresi", | |
| 172 | + (Version, En) => "Version", | |
| 173 | + (Version, Tr) => "Sürüm", | |
| 174 | + (NotConfigured, En) => "Not configured", | |
| 175 | + (NotConfigured, Tr) => "Ayarlanmamış", | |
| 176 | + (Unavailable, En) => "Unavailable", | |
| 177 | + (Unavailable, Tr) => "Alınamadı", | |
| 178 | + (Never, En) => "Never", | |
| 179 | + (Never, Tr) => "Hiç", | |
| 180 | + (Ok, En) => "OK", | |
| 181 | + (Ok, Tr) => "Tamam", | |
| 182 | + (Error, En) => "Error", | |
| 183 | + (Error, Tr) => "Hata", | |
| 184 | + (Lagging, En) => "Lagging", | |
| 185 | + (Lagging, Tr) => "Geride", | |
| 186 | + (HealthIntro, En) => "Read when the page loads. Reload the page for fresh numbers.", | |
| 187 | + (HealthIntro, Tr) => "Sayfa açılırken okunur. Güncel değerler için sayfayı yenileyin.", | |
| 188 | + } | |
| 189 | +} | |
| 190 | + | |
| 191 | +/// The login page message for a suspended account, with the admin's reason when there is one. | |
| 192 | +pub fn suspended_message(lang: Lang, reason: &str) -> String { | |
| 193 | + let base = t(lang, A::AccountSuspended); | |
| 194 | + if reason.is_empty() { | |
| 195 | + base.to_owned() | |
| 196 | + } else { | |
| 197 | + match lang { | |
| 198 | + Lang::En => format!("{base} Reason: {reason}"), | |
| 199 | + Lang::Tr => format!("{base} Neden: {reason}"), | |
| 200 | + } | |
| 201 | + } | |
| 202 | +} | |
| 203 | + | |
| 204 | +/// `3d 4h`, `5h 2m` or `7m`, for the uptime tile. | |
| 205 | +pub fn duration_short(secs: u64) -> String { | |
| 206 | + let (d, h, m) = (secs / 86_400, secs % 86_400 / 3_600, secs % 3_600 / 60); | |
| 207 | + if d > 0 { | |
| 208 | + format!("{d}d {h}h") | |
| 209 | + } else if h > 0 { | |
| 210 | + format!("{h}h {m}m") | |
| 211 | + } else { | |
| 212 | + format!("{m}m") | |
| 213 | + } | |
| 214 | +} | |
| 215 | + | |
| 216 | +#[cfg(test)] | |
| 217 | +mod tests { | |
| 218 | + use super::*; | |
| 219 | + | |
| 220 | + #[test] | |
| 221 | + fn duration_short_picks_the_two_largest_units() { | |
| 222 | + assert_eq!(duration_short(90_000), "1d 1h"); | |
| 223 | + assert_eq!(duration_short(7_500), "2h 5m"); | |
| 224 | + assert_eq!(duration_short(420), "7m"); | |
| 225 | + } | |
| 226 | + | |
| 227 | + #[test] | |
| 228 | + fn suspended_message_carries_the_reason() { | |
| 229 | + assert_eq!( | |
| 230 | + suspended_message(Lang::En, "spam"), | |
| 231 | + "This account is suspended. Reason: spam" | |
| 232 | + ); | |
| 233 | + assert_eq!( | |
| 234 | + suspended_message(Lang::En, ""), | |
| 235 | + "This account is suspended." | |
| 236 | + ); | |
| 237 | + } | |
| 238 | +} |
crates/forge-web/src/i18n/mod.rsmodified+1 -0
| @@ -18,6 +18,7 @@ use topcoat::router::request::headers; | ||
| 18 | 18 | use forge_core::User; |
| 19 | 19 | |
| 20 | 20 | pub mod accents; |
| 21 | +pub mod accounts; | |
| 21 | 22 | pub mod admin; |
| 22 | 23 | pub mod authoring; |
| 23 | 24 | pub mod browse; |
crates/forge-web/src/mail/account.rsmodified+27 -0
| @@ -76,3 +76,30 @@ pub async fn send_invite( | ||
| 76 | 76 | .await?; |
| 77 | 77 | Ok(()) |
| 78 | 78 | } |
| 79 | + | |
| 80 | +/// Queues a notice that the password changed, to the user's verified address. A user without a | |
| 81 | +/// verified address gets nothing. `stamp` keeps two changes from sharing one queue key. | |
| 82 | +pub async fn send_password_changed( | |
| 83 | + state: &AppState, | |
| 84 | + user: &User, | |
| 85 | + stamp: &str, | |
| 86 | +) -> forge_core::Result<()> { | |
| 87 | + let Some(address) = user.email.as_deref() else { | |
| 88 | + return Ok(()); | |
| 89 | + }; | |
| 90 | + if !state.store.email_is_verified(&user.id).await? { | |
| 91 | + return Ok(()); | |
| 92 | + } | |
| 93 | + let (subject, body) = templates::password_changed(&user.username); | |
| 94 | + enqueue( | |
| 95 | + state, | |
| 96 | + &format!("pwchanged:{}:{stamp}", user.id), | |
| 97 | + MailKind::Other, | |
| 98 | + Some(&user.id), | |
| 99 | + address, | |
| 100 | + &subject, | |
| 101 | + &body, | |
| 102 | + ) | |
| 103 | + .await?; | |
| 104 | + Ok(()) | |
| 105 | +} |
crates/forge-web/src/mail/templates.rsmodified+12 -0
| @@ -133,6 +133,18 @@ pub fn password_reset(username: &str, link: &str) -> (String, String) { | ||
| 133 | 133 | ) |
| 134 | 134 | } |
| 135 | 135 | |
| 136 | +/// The notice sent after a password change. | |
| 137 | +pub fn password_changed(username: &str) -> (String, String) { | |
| 138 | + ( | |
| 139 | + "Your forge password was changed".to_owned(), | |
| 140 | + format!( | |
| 141 | + "Hi {username},\n\nThe password of your forge account was just changed and your \ | |
| 142 | + other sessions were signed out. If that was you, nothing more to do. If it was \ | |
| 143 | + not you, reset your password now and contact the administrator.\n" | |
| 144 | + ), | |
| 145 | + ) | |
| 146 | +} | |
| 147 | + | |
| 136 | 148 | /// The email verification mail. The link works once and for 24 hours. |
| 137 | 149 | pub fn email_verify(username: &str, link: &str) -> (String, String) { |
| 138 | 150 | ( |
crates/forge-web/src/pages/account_tools_tests.rsadded+347 -0
| @@ -0,0 +1,347 @@ | ||
| 1 | +//! Tests for admin account tools: suspension, admin flag, reset link, 2FA reset, the announcement | |
| 2 | +//! banner and the health page. | |
| 3 | + | |
| 4 | +use forge_core::Store; | |
| 5 | +use forge_core::config::BannerConfig; | |
| 6 | +use topcoat::router::request::Request; | |
| 7 | +use topcoat::router::{Body, Router, to_bytes}; | |
| 8 | + | |
| 9 | +use crate::auth::SESSION_COOKIE; | |
| 10 | +use crate::test_support::{app_router, create_session, test_state}; | |
| 11 | + | |
| 12 | +const ADMIN_TOKEN: &str = "tools-admin-session"; | |
| 13 | +const USER_TOKEN: &str = "tools-user-session"; | |
| 14 | +const CSRF: &str = "tools-csrf"; | |
| 15 | + | |
| 16 | +struct Fx { | |
| 17 | + store: Store, | |
| 18 | + router: Router, | |
| 19 | + user_id: String, | |
| 20 | + admin_id: String, | |
| 21 | +} | |
| 22 | + | |
| 23 | +async fn fixture(dir: &std::path::Path, banner: Option<BannerConfig>) -> Fx { | |
| 24 | + let mut state = test_state(dir).await; | |
| 25 | + if let Some(banner) = banner { | |
| 26 | + let mut config = (*state.config).clone(); | |
| 27 | + config.banner = banner; | |
| 28 | + state.set_config(config); | |
| 29 | + } | |
| 30 | + let store = state.store.clone(); | |
| 31 | + let admin = store.create_user("root", None, "h", true).await.unwrap(); | |
| 32 | + let user = store | |
| 33 | + .create_user("tahinli", None, "h", false) | |
| 34 | + .await | |
| 35 | + .unwrap(); | |
| 36 | + create_session(&store, &admin.id, ADMIN_TOKEN, CSRF).await; | |
| 37 | + create_session(&store, &user.id, USER_TOKEN, CSRF).await; | |
| 38 | + Fx { | |
| 39 | + store, | |
| 40 | + router: app_router(state), | |
| 41 | + user_id: user.id, | |
| 42 | + admin_id: admin.id, | |
| 43 | + } | |
| 44 | +} | |
| 45 | + | |
| 46 | +async fn send( | |
| 47 | + router: &Router, | |
| 48 | + method: &str, | |
| 49 | + uri: &str, | |
| 50 | + token: Option<&str>, | |
| 51 | + form: Option<String>, | |
| 52 | +) -> (u16, String) { | |
| 53 | + let mut builder = Request::builder().method(method).uri(uri); | |
| 54 | + if let Some(token) = token { | |
| 55 | + builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}")); | |
| 56 | + } | |
| 57 | + let body = match form { | |
| 58 | + Some(form) => { | |
| 59 | + builder = builder.header("content-type", "application/x-www-form-urlencoded"); | |
| 60 | + Body::from(form) | |
| 61 | + } | |
| 62 | + None => Body::empty(), | |
| 63 | + }; | |
| 64 | + let res = router.handle(builder.body(body).unwrap()).await; | |
| 65 | + let status = res.status().as_u16(); | |
| 66 | + let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap(); | |
| 67 | + (status, String::from_utf8_lossy(&bytes).into_owned()) | |
| 68 | +} | |
| 69 | + | |
| 70 | +fn csrf(extra: &str) -> Option<String> { | |
| 71 | + Some(format!("csrf={CSRF}{extra}")) | |
| 72 | +} | |
| 73 | + | |
| 74 | +#[tokio::test] | |
| 75 | +async fn admin_pages_are_404_for_non_admins() { | |
| 76 | + let dir = tempfile::tempdir().unwrap(); | |
| 77 | + let fx = fixture(dir.path(), None).await; | |
| 78 | + let detail = format!("/admin/users/{}", fx.user_id); | |
| 79 | + for uri in ["/admin/health", detail.as_str()] { | |
| 80 | + assert_eq!( | |
| 81 | + send(&fx.router, "GET", uri, Some(USER_TOKEN), None).await.0, | |
| 82 | + 404 | |
| 83 | + ); | |
| 84 | + assert_eq!(send(&fx.router, "GET", uri, None, None).await.0, 404); | |
| 85 | + assert_eq!( | |
| 86 | + send(&fx.router, "GET", uri, Some(ADMIN_TOKEN), None) | |
| 87 | + .await | |
| 88 | + .0, | |
| 89 | + 200 | |
| 90 | + ); | |
| 91 | + } | |
| 92 | + let suspend = format!("{detail}/suspend"); | |
| 93 | + assert_eq!( | |
| 94 | + send(&fx.router, "POST", &suspend, Some(USER_TOKEN), csrf("")) | |
| 95 | + .await | |
| 96 | + .0, | |
| 97 | + 404 | |
| 98 | + ); | |
| 99 | +} | |
| 100 | + | |
| 101 | +#[tokio::test] | |
| 102 | +async fn suspending_needs_csrf_and_is_audited() { | |
| 103 | + let dir = tempfile::tempdir().unwrap(); | |
| 104 | + let fx = fixture(dir.path(), None).await; | |
| 105 | + let uri = format!("/admin/users/{}/suspend", fx.user_id); | |
| 106 | + let (status, _) = send( | |
| 107 | + &fx.router, | |
| 108 | + "POST", | |
| 109 | + &uri, | |
| 110 | + Some(ADMIN_TOKEN), | |
| 111 | + Some("csrf=wrong&reason=spam".into()), | |
| 112 | + ) | |
| 113 | + .await; | |
| 114 | + assert_eq!(status, 403); | |
| 115 | + assert!(fx.store.suspension(&fx.user_id).await.unwrap().is_none()); | |
| 116 | + | |
| 117 | + let (status, _) = send( | |
| 118 | + &fx.router, | |
| 119 | + "POST", | |
| 120 | + &uri, | |
| 121 | + Some(ADMIN_TOKEN), | |
| 122 | + csrf("&reason=spam"), | |
| 123 | + ) | |
| 124 | + .await; | |
| 125 | + assert_eq!(status, 303); | |
| 126 | + let suspension = fx.store.suspension(&fx.user_id).await.unwrap().unwrap(); | |
| 127 | + assert_eq!(suspension.reason, "spam"); | |
| 128 | + // The user's session is gone and a settings page now bounces them. | |
| 129 | + let (status, _) = send( | |
| 130 | + &fx.router, | |
| 131 | + "GET", | |
| 132 | + "/settings/security", | |
| 133 | + Some(USER_TOKEN), | |
| 134 | + None, | |
| 135 | + ) | |
| 136 | + .await; | |
| 137 | + assert_ne!(status, 200); | |
| 138 | + let page = send( | |
| 139 | + &fx.router, | |
| 140 | + "GET", | |
| 141 | + &format!("/admin/users/{}", fx.user_id), | |
| 142 | + Some(ADMIN_TOKEN), | |
| 143 | + None, | |
| 144 | + ) | |
| 145 | + .await | |
| 146 | + .1; | |
| 147 | + assert!(page.contains("spam")); | |
| 148 | + | |
| 149 | + let (status, _) = send( | |
| 150 | + &fx.router, | |
| 151 | + "POST", | |
| 152 | + &format!("/admin/users/{}/unsuspend", fx.user_id), | |
| 153 | + Some(ADMIN_TOKEN), | |
| 154 | + csrf(""), | |
| 155 | + ) | |
| 156 | + .await; | |
| 157 | + assert_eq!(status, 303); | |
| 158 | + assert!(fx.store.suspension(&fx.user_id).await.unwrap().is_none()); | |
| 159 | +} | |
| 160 | + | |
| 161 | +#[tokio::test] | |
| 162 | +async fn the_last_admin_cannot_be_demoted_or_suspended_from_the_page() { | |
| 163 | + let dir = tempfile::tempdir().unwrap(); | |
| 164 | + let fx = fixture(dir.path(), None).await; | |
| 165 | + let base = format!("/admin/users/{}", fx.admin_id); | |
| 166 | + let (status, body) = send( | |
| 167 | + &fx.router, | |
| 168 | + "POST", | |
| 169 | + &format!("{base}/admin"), | |
| 170 | + Some(ADMIN_TOKEN), | |
| 171 | + csrf("&admin=0"), | |
| 172 | + ) | |
| 173 | + .await; | |
| 174 | + assert_eq!(status, 200); | |
| 175 | + assert!(body.contains("last administrator"), "{body}"); | |
| 176 | + let me = fx.store.user_by_id(&fx.admin_id).await.unwrap().unwrap(); | |
| 177 | + assert!(me.is_admin); | |
| 178 | +} | |
| 179 | + | |
| 180 | +#[tokio::test] | |
| 181 | +async fn reset_link_is_shown_once_and_signs_the_user_out() { | |
| 182 | + let dir = tempfile::tempdir().unwrap(); | |
| 183 | + let fx = fixture(dir.path(), None).await; | |
| 184 | + let (status, body) = send( | |
| 185 | + &fx.router, | |
| 186 | + "POST", | |
| 187 | + &format!("/admin/users/{}/reset-link", fx.user_id), | |
| 188 | + Some(ADMIN_TOKEN), | |
| 189 | + csrf(""), | |
| 190 | + ) | |
| 191 | + .await; | |
| 192 | + assert_eq!(status, 200); | |
| 193 | + let at = body.find("https://forge.test/reset/").expect("reset link"); | |
| 194 | + let token: String = body[at + "https://forge.test/reset/".len()..] | |
| 195 | + .chars() | |
| 196 | + .take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_') | |
| 197 | + .collect(); | |
| 198 | + assert!(fx.store.reset_token_is_live(&token).await.unwrap()); | |
| 199 | + assert!( | |
| 200 | + fx.store | |
| 201 | + .list_sessions(&fx.user_id) | |
| 202 | + .await | |
| 203 | + .unwrap() | |
| 204 | + .is_empty() | |
| 205 | + ); | |
| 206 | +} | |
| 207 | + | |
| 208 | +#[tokio::test] | |
| 209 | +async fn disabling_two_factor_clears_it() { | |
| 210 | + let dir = tempfile::tempdir().unwrap(); | |
| 211 | + let fx = fixture(dir.path(), None).await; | |
| 212 | + fx.store | |
| 213 | + .set_totp_secret(&fx.user_id, "sealed") | |
| 214 | + .await | |
| 215 | + .unwrap(); | |
| 216 | + fx.store | |
| 217 | + .enable_totp(&fx.user_id, 1, &["h1".to_owned()]) | |
| 218 | + .await | |
| 219 | + .unwrap(); | |
| 220 | + let (status, _) = send( | |
| 221 | + &fx.router, | |
| 222 | + "POST", | |
| 223 | + &format!("/admin/users/{}/disable-2fa", fx.user_id), | |
| 224 | + Some(ADMIN_TOKEN), | |
| 225 | + csrf(""), | |
| 226 | + ) | |
| 227 | + .await; | |
| 228 | + assert_eq!(status, 303); | |
| 229 | + assert!( | |
| 230 | + !fx.store | |
| 231 | + .account_facts(&fx.user_id) | |
| 232 | + .await | |
| 233 | + .unwrap() | |
| 234 | + .two_factor | |
| 235 | + ); | |
| 236 | +} | |
| 237 | + | |
| 238 | +#[tokio::test] | |
| 239 | +async fn suspended_user_sees_the_reason_on_the_login_page() { | |
| 240 | + let dir = tempfile::tempdir().unwrap(); | |
| 241 | + let state = test_state(dir.path()).await; | |
| 242 | + let hash = crate::auth::hash_password_async("correct horse battery".into()) | |
| 243 | + .await | |
| 244 | + .unwrap(); | |
| 245 | + let store = state.store.clone(); | |
| 246 | + let admin = store.create_user("root", None, &hash, true).await.unwrap(); | |
| 247 | + let user = store | |
| 248 | + .create_user("tahinli", None, &hash, false) | |
| 249 | + .await | |
| 250 | + .unwrap(); | |
| 251 | + store | |
| 252 | + .suspend_user(&user.id, "abuse of CI", Some(&admin.id)) | |
| 253 | + .await | |
| 254 | + .unwrap(); | |
| 255 | + let router = app_router(state); | |
| 256 | + let req = Request::builder() | |
| 257 | + .method("GET") | |
| 258 | + .uri("/login") | |
| 259 | + .body(Body::empty()) | |
| 260 | + .unwrap(); | |
| 261 | + let res = router.handle(req).await; | |
| 262 | + let cookie = res | |
| 263 | + .headers() | |
| 264 | + .get_all("set-cookie") | |
| 265 | + .iter() | |
| 266 | + .filter_map(|v| v.to_str().ok()) | |
| 267 | + .find(|raw| raw.starts_with("__Host-forge_precsrf")) | |
| 268 | + .map(|raw| raw.split(';').next().unwrap().to_owned()) | |
| 269 | + .unwrap(); | |
| 270 | + let html = | |
| 271 | + String::from_utf8_lossy(&to_bytes(res.into_body(), usize::MAX).await.unwrap()).into_owned(); | |
| 272 | + let marker = "name=\"precsrf\" value=\""; | |
| 273 | + let start = html.find(marker).unwrap() + marker.len(); | |
| 274 | + let precsrf = &html[start..start + html[start..].find('"').unwrap()]; | |
| 275 | + let form = | |
| 276 | + format!("username=tahinli&password=correct%20horse%20battery&next=%2F&precsrf={precsrf}"); | |
| 277 | + let req = Request::builder() | |
| 278 | + .method("POST") | |
| 279 | + .uri("/login") | |
| 280 | + .header("cookie", cookie) | |
| 281 | + .header("content-type", "application/x-www-form-urlencoded") | |
| 282 | + .body(Body::from(form)) | |
| 283 | + .unwrap(); | |
| 284 | + let res = router.handle(req).await; | |
| 285 | + assert_eq!(res.status().as_u16(), 200); | |
| 286 | + let html = | |
| 287 | + String::from_utf8_lossy(&to_bytes(res.into_body(), usize::MAX).await.unwrap()).into_owned(); | |
| 288 | + assert!(html.contains("abuse of CI"), "{html}"); | |
| 289 | + assert!(store.list_sessions(&user.id).await.unwrap().is_empty()); | |
| 290 | +} | |
| 291 | + | |
| 292 | +#[tokio::test] | |
| 293 | +async fn banner_shows_on_pages_and_a_dismissal_hides_it() { | |
| 294 | + let dir = tempfile::tempdir().unwrap(); | |
| 295 | + let banner = BannerConfig { | |
| 296 | + message: "Maintenance tonight".into(), | |
| 297 | + level: "warning".into(), | |
| 298 | + expires: String::new(), | |
| 299 | + }; | |
| 300 | + let fx = fixture(dir.path(), Some(banner)).await; | |
| 301 | + for token in [None, Some(USER_TOKEN)] { | |
| 302 | + let (status, body) = send(&fx.router, "GET", "/explore", token, None).await; | |
| 303 | + assert_eq!(status, 200); | |
| 304 | + assert!(body.contains("site-banner warning"), "{body}"); | |
| 305 | + assert!(body.contains("Maintenance tonight")); | |
| 306 | + } | |
| 307 | + let hash = crate::pages::banner::banner_hash("Maintenance tonight", "warning"); | |
| 308 | + let req = Request::builder() | |
| 309 | + .method("GET") | |
| 310 | + .uri("/explore") | |
| 311 | + .header("cookie", format!("forge_banner={hash}")) | |
| 312 | + .body(Body::empty()) | |
| 313 | + .unwrap(); | |
| 314 | + let res = fx.router.handle(req).await; | |
| 315 | + let body = | |
| 316 | + String::from_utf8_lossy(&to_bytes(res.into_body(), usize::MAX).await.unwrap()).into_owned(); | |
| 317 | + assert!(!body.contains("Maintenance tonight")); | |
| 318 | + | |
| 319 | + let req = Request::builder() | |
| 320 | + .method("POST") | |
| 321 | + .uri("/-/banner/dismiss") | |
| 322 | + .header("content-type", "application/x-www-form-urlencoded") | |
| 323 | + .body(Body::from(format!("hash={hash}&back=%2Fexplore"))) | |
| 324 | + .unwrap(); | |
| 325 | + let res = fx.router.handle(req).await; | |
| 326 | + assert_eq!(res.status().as_u16(), 303); | |
| 327 | + let set = res | |
| 328 | + .headers() | |
| 329 | + .get_all("set-cookie") | |
| 330 | + .iter() | |
| 331 | + .filter_map(|v| v.to_str().ok()) | |
| 332 | + .any(|c| c.starts_with(&format!("forge_banner={hash}"))); | |
| 333 | + assert!(set); | |
| 334 | +} | |
| 335 | + | |
| 336 | +#[tokio::test] | |
| 337 | +async fn expired_banner_is_not_shown() { | |
| 338 | + let dir = tempfile::tempdir().unwrap(); | |
| 339 | + let banner = BannerConfig { | |
| 340 | + message: "Old news".into(), | |
| 341 | + level: "info".into(), | |
| 342 | + expires: "2020-01-01 00:00".into(), | |
| 343 | + }; | |
| 344 | + let fx = fixture(dir.path(), Some(banner)).await; | |
| 345 | + let (_, body) = send(&fx.router, "GET", "/explore", None, None).await; | |
| 346 | + assert!(!body.contains("Old news")); | |
| 347 | +} |
crates/forge-web/src/pages/admin_health.rsadded+332 -0
| @@ -0,0 +1,332 @@ | ||
| 1 | +//! Page: instance health for admins (`/admin/health`). A compact grid of tiles, read when the page | |
| 2 | +//! loads. Every number is a cheap query or a short external probe (`df`, `du`), so there is no | |
| 3 | +//! polling; reloading the page, or opening it again, reads fresh values. Non-admins get 404. | |
| 4 | + | |
| 5 | +use std::path::Path; | |
| 6 | +use std::time::Duration; | |
| 7 | + | |
| 8 | +use forge_core::mail::MailState; | |
| 9 | +use forge_core::store::backup_runs::RunKind; | |
| 10 | +use forge_core::store::replication::DB_SUBJECT; | |
| 11 | +use forge_core::time::stamp_to_unix; | |
| 12 | +use forge_core::tz::format_in_tz; | |
| 13 | +use tokio::process::Command; | |
| 14 | +use topcoat::Result; | |
| 15 | +use topcoat::context::{Cx, app_context}; | |
| 16 | +use topcoat::router::page; | |
| 17 | +use topcoat::view::{View, component, view}; | |
| 18 | + | |
| 19 | +use crate::i18n::accounts::{A, duration_short, t as at}; | |
| 20 | +use crate::i18n::{self, Lang}; | |
| 21 | +use crate::pages::admin_users::admin_only; | |
| 22 | +use crate::state::AppState; | |
| 23 | +use crate::views::{human_size, now_unix, relative_time, shell}; | |
| 24 | + | |
| 25 | +/// One cell of the grid. | |
| 26 | +struct Tile { | |
| 27 | + title: &'static str, | |
| 28 | + big: String, | |
| 29 | + sub: String, | |
| 30 | + /// `""`, `ok` or `bad`. | |
| 31 | + tone: &'static str, | |
| 32 | + /// Percent of a meter to fill, for disk tiles. | |
| 33 | + meter: Option<u8>, | |
| 34 | +} | |
| 35 | + | |
| 36 | +fn tile(title: &'static str, big: impl Into<String>, sub: impl Into<String>) -> Tile { | |
| 37 | + Tile { | |
| 38 | + title, | |
| 39 | + big: big.into(), | |
| 40 | + sub: sub.into(), | |
| 41 | + tone: "", | |
| 42 | + meter: None, | |
| 43 | + } | |
| 44 | +} | |
| 45 | + | |
| 46 | +/// `(total, available)` bytes from `df -Pk <path>` output. | |
| 47 | +fn parse_df(output: &str) -> Option<(u64, u64)> { | |
| 48 | + let line = output.lines().nth(1)?; | |
| 49 | + let fields: Vec<&str> = line.split_whitespace().collect(); | |
| 50 | + let total: u64 = fields.get(1)?.parse().ok()?; | |
| 51 | + let avail: u64 = fields.get(3)?.parse().ok()?; | |
| 52 | + Some((total.saturating_mul(1024), avail.saturating_mul(1024))) | |
| 53 | +} | |
| 54 | + | |
| 55 | +/// Kilobytes from `du -sk <path>` output, as bytes. | |
| 56 | +fn parse_du(output: &str) -> Option<u64> { | |
| 57 | + let kb: u64 = output.split_whitespace().next()?.parse().ok()?; | |
| 58 | + Some(kb.saturating_mul(1024)) | |
| 59 | +} | |
| 60 | + | |
| 61 | +async fn probe(program: &str, args: &[&str], path: &Path, limit: Duration) -> Option<String> { | |
| 62 | + let run = Command::new(program) | |
| 63 | + .args(args) | |
| 64 | + .arg(path) | |
| 65 | + .stdin(std::process::Stdio::null()) | |
| 66 | + .kill_on_drop(true) | |
| 67 | + .output(); | |
| 68 | + let output = tokio::time::timeout(limit, run).await.ok()?.ok()?; | |
| 69 | + // `du` exits non-zero on one unreadable entry but still prints a total. | |
| 70 | + String::from_utf8(output.stdout).ok() | |
| 71 | +} | |
| 72 | + | |
| 73 | +async fn disk(path: &Path) -> Option<(u64, u64)> { | |
| 74 | + parse_df(&probe("df", &["-Pk"], path, Duration::from_secs(3)).await?) | |
| 75 | +} | |
| 76 | + | |
| 77 | +async fn tree_size(path: &Path) -> Option<u64> { | |
| 78 | + parse_du(&probe("du", &["-sk"], path, Duration::from_secs(4)).await?) | |
| 79 | +} | |
| 80 | + | |
| 81 | +/// Seconds since the process started, from `/proc` (Linux). `None` elsewhere. | |
| 82 | +fn uptime_secs() -> Option<u64> { | |
| 83 | + let stat = std::fs::read_to_string("/proc/self/stat").ok()?; | |
| 84 | + // Fields after the `)` that closes the command name; starttime is field 22 overall. | |
| 85 | + let rest = stat.rsplit_once(')')?.1; | |
| 86 | + let start_ticks: f64 = rest.split_whitespace().nth(19)?.parse().ok()?; | |
| 87 | + let system: f64 = std::fs::read_to_string("/proc/uptime") | |
| 88 | + .ok()? | |
| 89 | + .split_whitespace() | |
| 90 | + .next()? | |
| 91 | + .parse() | |
| 92 | + .ok()?; | |
| 93 | + // The kernel's clock tick is 100 Hz on every Linux target this runs on. | |
| 94 | + Some((system - start_ticks / 100.0).max(0.0) as u64) | |
| 95 | +} | |
| 96 | + | |
| 97 | +fn disk_tile(lang: Lang, title: &'static str, space: Option<(u64, u64)>, label: &str) -> Tile { | |
| 98 | + match space { | |
| 99 | + Some((total, avail)) => { | |
| 100 | + let used = total.saturating_sub(avail); | |
| 101 | + let pct = used | |
| 102 | + .saturating_mul(100) | |
| 103 | + .checked_div(total) | |
| 104 | + .map_or(0, |p| u8::try_from(p).unwrap_or(100)); | |
| 105 | + Tile { | |
| 106 | + title, | |
| 107 | + big: human_size(lang, avail), | |
| 108 | + sub: format!( | |
| 109 | + "{} {} - {label}", | |
| 110 | + at(lang, A::Free), | |
| 111 | + human_size(lang, total) | |
| 112 | + ), | |
| 113 | + tone: if pct >= 90 { "bad" } else { "" }, | |
| 114 | + meter: Some(pct), | |
| 115 | + } | |
| 116 | + } | |
| 117 | + None => tile(title, at(lang, A::Unavailable), label), | |
| 118 | + } | |
| 119 | +} | |
| 120 | + | |
| 121 | +async fn tiles(state: &AppState, lang: Lang, tz: &str) -> Result<Vec<Tile>> { | |
| 122 | + let live = state.live(); | |
| 123 | + let now = now_unix(); | |
| 124 | + let data_dir = live.data_dir.clone(); | |
| 125 | + let repos_dir = data_dir.join("repos"); | |
| 126 | + let backup_dir = live.backup.dir.clone(); | |
| 127 | + let database = live.database.clone(); | |
| 128 | + let backup_on = !backup_dir.as_os_str().is_empty(); | |
| 129 | + let (data_space, repo_bytes, backup_space) = | |
| 130 | + tokio::join!(disk(&data_dir), tree_size(&repos_dir), async { | |
| 131 | + if backup_on { | |
| 132 | + disk(&backup_dir).await | |
| 133 | + } else { | |
| 134 | + None | |
| 135 | + } | |
| 136 | + }); | |
| 137 | + let counts = state.store.health_counts().await?; | |
| 138 | + let mail = state | |
| 139 | + .store | |
| 140 | + .mail_state_counts(&forge_core::time::now_stamp()) | |
| 141 | + .await?; | |
| 142 | + let mail_n = |states: &[MailState]| -> u32 { | |
| 143 | + mail.iter() | |
| 144 | + .filter(|(s, _)| states.contains(s)) | |
| 145 | + .map(|(_, n)| *n) | |
| 146 | + .sum() | |
| 147 | + }; | |
| 148 | + let pending = mail_n(&[MailState::Queued, MailState::Retrying, MailState::Sending]); | |
| 149 | + let failed = mail_n(&[MailState::Failed]); | |
| 150 | + let db_bytes = std::fs::metadata(&database).map(|m| m.len()).ok(); | |
| 151 | + | |
| 152 | + let mut out = Vec::new(); | |
| 153 | + out.push(disk_tile( | |
| 154 | + lang, | |
| 155 | + at(lang, A::DataDirectory), | |
| 156 | + data_space, | |
| 157 | + &data_dir.to_string_lossy(), | |
| 158 | + )); | |
| 159 | + out.push(if backup_on { | |
| 160 | + disk_tile( | |
| 161 | + lang, | |
| 162 | + at(lang, A::BackupDirectory), | |
| 163 | + backup_space, | |
| 164 | + &backup_dir.to_string_lossy(), | |
| 165 | + ) | |
| 166 | + } else { | |
| 167 | + tile(at(lang, A::BackupDirectory), at(lang, A::NotConfigured), "") | |
| 168 | + }); | |
| 169 | + out.push(tile( | |
| 170 | + at(lang, A::DatabaseFile), | |
| 171 | + db_bytes.map_or_else( | |
| 172 | + || at(lang, A::Unavailable).to_owned(), | |
| 173 | + |b| human_size(lang, b), | |
| 174 | + ), | |
| 175 | + database.to_string_lossy(), | |
| 176 | + )); | |
| 177 | + out.push(tile( | |
| 178 | + at(lang, A::Repositories), | |
| 179 | + counts.repos.to_string(), | |
| 180 | + match repo_bytes { | |
| 181 | + Some(b) => format!("{}: {}", at(lang, A::RepoStorage), human_size(lang, b)), | |
| 182 | + None => at(lang, A::Unavailable).to_owned(), | |
| 183 | + }, | |
| 184 | + )); | |
| 185 | + out.push(tile( | |
| 186 | + at(lang, A::CiQueue), | |
| 187 | + format!("{} {}", counts.queued_jobs, at(lang, A::QueuedJobs)), | |
| 188 | + format!( | |
| 189 | + "{} / {} {}", | |
| 190 | + counts.runners_online, | |
| 191 | + counts.runners_total, | |
| 192 | + at(lang, A::RunnersOnline) | |
| 193 | + ), | |
| 194 | + )); | |
| 195 | + let mut mail_tile = tile( | |
| 196 | + at(lang, A::MailQueue), | |
| 197 | + format!("{pending} {}", at(lang, A::Pending)), | |
| 198 | + format!("{failed} {}", at(lang, A::Failed)), | |
| 199 | + ); | |
| 200 | + if failed > 0 { | |
| 201 | + mail_tile.tone = "bad"; | |
| 202 | + } | |
| 203 | + out.push(mail_tile); | |
| 204 | + | |
| 205 | + let backup = if backup_on { | |
| 206 | + state.store.last_run(RunKind::Backup).await? | |
| 207 | + } else { | |
| 208 | + None | |
| 209 | + }; | |
| 210 | + out.push(match backup { | |
| 211 | + Some(run) => { | |
| 212 | + let at_unix = stamp_to_unix(&run.started_at).unwrap_or(0); | |
| 213 | + let mut t = tile( | |
| 214 | + at(lang, A::LastBackup), | |
| 215 | + match run.ok { | |
| 216 | + Some(true) => at(lang, A::Ok), | |
| 217 | + Some(false) => at(lang, A::Failed), | |
| 218 | + None => at(lang, A::Pending), | |
| 219 | + }, | |
| 220 | + format!( | |
| 221 | + "{} ({})", | |
| 222 | + format_in_tz(at_unix, tz), | |
| 223 | + relative_time(lang, at_unix, now) | |
| 224 | + ), | |
| 225 | + ); | |
| 226 | + t.tone = match run.ok { | |
| 227 | + Some(true) => "ok", | |
| 228 | + Some(false) => "bad", | |
| 229 | + None => "", | |
| 230 | + }; | |
| 231 | + t | |
| 232 | + } | |
| 233 | + None if backup_on => tile(at(lang, A::LastBackup), at(lang, A::Never), ""), | |
| 234 | + None => tile(at(lang, A::LastBackup), at(lang, A::NotConfigured), ""), | |
| 235 | + }); | |
| 236 | + | |
| 237 | + let replicating = !live.replication.target.trim().is_empty(); | |
| 238 | + out.push(if replicating { | |
| 239 | + match state.store.replication_status(DB_SUBJECT).await? { | |
| 240 | + Some(status) => { | |
| 241 | + let ok_unix = status.last_ok_at.as_deref().and_then(stamp_to_unix); | |
| 242 | + let window = live.replication.db_snapshot_minutes.saturating_mul(120); | |
| 243 | + let lagging = ok_unix.is_none_or(|t| (now - t).max(0) as u64 > window); | |
| 244 | + let errored = status.last_error.is_some(); | |
| 245 | + let mut t = tile( | |
| 246 | + at(lang, A::Replication), | |
| 247 | + if errored { | |
| 248 | + at(lang, A::Error) | |
| 249 | + } else if lagging { | |
| 250 | + at(lang, A::Lagging) | |
| 251 | + } else { | |
| 252 | + at(lang, A::Ok) | |
| 253 | + }, | |
| 254 | + ok_unix.map_or_else( | |
| 255 | + || at(lang, A::Never).to_owned(), | |
| 256 | + |t| relative_time(lang, t, now), | |
| 257 | + ), | |
| 258 | + ); | |
| 259 | + t.tone = if errored || lagging { "bad" } else { "ok" }; | |
| 260 | + t | |
| 261 | + } | |
| 262 | + None => tile(at(lang, A::Replication), at(lang, A::Never), ""), | |
| 263 | + } | |
| 264 | + } else { | |
| 265 | + tile(at(lang, A::Replication), at(lang, A::NotConfigured), "") | |
| 266 | + }); | |
| 267 | + out.push(tile( | |
| 268 | + at(lang, A::Uptime), | |
| 269 | + uptime_secs().map_or_else(|| at(lang, A::Unavailable).to_owned(), duration_short), | |
| 270 | + "", | |
| 271 | + )); | |
| 272 | + out.push(tile( | |
| 273 | + at(lang, A::Version), | |
| 274 | + env!("CARGO_PKG_VERSION"), | |
| 275 | + env!("FORGE_BUILD_SHA"), | |
| 276 | + )); | |
| 277 | + Ok(out) | |
| 278 | +} | |
| 279 | + | |
| 280 | +#[component] | |
| 281 | +async fn health_view(lang: Lang, tiles: Vec<Tile>) -> Result<impl View> { | |
| 282 | + Ok(view! { | |
| 283 | + <section class="page-head"> | |
| 284 | + <h1>(at(lang, A::Health))</h1> | |
| 285 | + <p class="muted">(at(lang, A::HealthIntro))</p> | |
| 286 | + </section> | |
| 287 | + <div class="health-grid"> | |
| 288 | + for t in tiles.into_iter() { | |
| 289 | + <section class=(format!("tile {}", t.tone))> | |
| 290 | + <h2>(t.title)</h2> | |
| 291 | + <div class="big">(t.big.as_str())</div> | |
| 292 | + if !t.sub.is_empty() { | |
| 293 | + <div class="sub">(t.sub.as_str())</div> | |
| 294 | + } | |
| 295 | + if let Some(pct) = t.meter { | |
| 296 | + <progress class="meter" max="100" value=(pct.to_string())></progress> | |
| 297 | + } | |
| 298 | + </section> | |
| 299 | + } | |
| 300 | + </div> | |
| 301 | + }) | |
| 302 | +} | |
| 303 | + | |
| 304 | +#[page("/admin/health")] | |
| 305 | +async fn health_page(cx: &Cx) -> Result<impl View> { | |
| 306 | + let viewer = admin_only(cx).await?; | |
| 307 | + let lang = i18n::lang(cx, Some(&viewer.0)); | |
| 308 | + let state = app_context::<AppState>(cx); | |
| 309 | + let tiles = tiles(state, lang, &viewer.0.timezone).await?; | |
| 310 | + let title = at(lang, A::Health); | |
| 311 | + Ok(view! { | |
| 312 | + shell(title: title, viewer: Some(&viewer), health_view(lang: lang, tiles: tiles)) | |
| 313 | + }) | |
| 314 | +} | |
| 315 | + | |
| 316 | +#[cfg(test)] | |
| 317 | +mod tests { | |
| 318 | + use super::*; | |
| 319 | + | |
| 320 | + #[test] | |
| 321 | + fn df_output_parses_to_bytes() { | |
| 322 | + let out = "Filesystem 1024-blocks Used Available Capacity Mounted on\n/dev/sda1 1000 400 600 40% /\n"; | |
| 323 | + assert_eq!(parse_df(out), Some((1000 * 1024, 600 * 1024))); | |
| 324 | + assert_eq!(parse_df("garbage"), None); | |
| 325 | + } | |
| 326 | + | |
| 327 | + #[test] | |
| 328 | + fn du_output_parses_to_bytes() { | |
| 329 | + assert_eq!(parse_du("12\t/data/repos\n"), Some(12 * 1024)); | |
| 330 | + assert_eq!(parse_du(""), None); | |
| 331 | + } | |
| 332 | +} |
crates/forge-web/src/pages/admin_user_detail.rsadded+421 -0
| @@ -0,0 +1,421 @@ | ||
| 1 | +//! Page: one account for admins (`/admin/users/{id}`). Facts, suspend or lift, admin flag, a | |
| 2 | +//! one-time password reset link and disabling two-factor for a locked-out user. Every action is | |
| 3 | +//! audited. Non-admins get 404, like the rest of the admin area. | |
| 4 | + | |
| 5 | +use forge_core::names::normalize_name; | |
| 6 | +use forge_core::store::suspension::{AccountFacts, Suspension}; | |
| 7 | +use forge_core::store::user_delete::GHOST_USERNAME; | |
| 8 | +use forge_core::tz::format_in_tz; | |
| 9 | +use forge_core::{AuditAction, User}; | |
| 10 | +use serde::Deserialize; | |
| 11 | +use topcoat::Result; | |
| 12 | +use topcoat::context::{Cx, app_context}; | |
| 13 | +use topcoat::router::content::Form; | |
| 14 | +use topcoat::router::error::{forbidden, not_found, see_other}; | |
| 15 | +use topcoat::router::{page, path_param_segment, query_params}; | |
| 16 | +use topcoat::view::{View, component, view}; | |
| 17 | + | |
| 18 | +use crate::audit::{self, Actor, Target}; | |
| 19 | +use crate::auth::{check_csrf, two_factor_enabled}; | |
| 20 | +use crate::i18n::accounts::{A, t as at}; | |
| 21 | +use crate::i18n::admin::{self as g, K}; | |
| 22 | +use crate::i18n::{self, Key, Lang}; | |
| 23 | +use crate::pages::admin_users::admin_only; | |
| 24 | +use crate::pages::issues_list::stamp_unix; | |
| 25 | +use crate::state::AppState; | |
| 26 | +use crate::views::{alert, enc, shell, user_facing_message}; | |
| 27 | + | |
| 28 | +#[query_params(error = bad_request)] | |
| 29 | +pub(crate) struct DoneQuery { | |
| 30 | + done: Option<String>, | |
| 31 | +} | |
| 32 | + | |
| 33 | +#[derive(Deserialize)] | |
| 34 | +struct ActionForm { | |
| 35 | + #[serde(default)] | |
| 36 | + csrf: String, | |
| 37 | + #[serde(default)] | |
| 38 | + reason: String, | |
| 39 | + /// `1` grants administrator rights, anything else removes them. | |
| 40 | + #[serde(default)] | |
| 41 | + admin: String, | |
| 42 | +} | |
| 43 | + | |
| 44 | +struct Detail { | |
| 45 | + target: User, | |
| 46 | + facts: AccountFacts, | |
| 47 | + suspension: Option<Suspension>, | |
| 48 | +} | |
| 49 | + | |
| 50 | +/// What the page says above the facts after an action. | |
| 51 | +#[derive(Default)] | |
| 52 | +struct Notice { | |
| 53 | + done: Option<&'static str>, | |
| 54 | + error: Option<String>, | |
| 55 | + link: Option<String>, | |
| 56 | +} | |
| 57 | + | |
| 58 | +#[derive(Clone, Copy)] | |
| 59 | +enum Action { | |
| 60 | + Suspend, | |
| 61 | + Unsuspend, | |
| 62 | + SetAdmin, | |
| 63 | + ResetLink, | |
| 64 | + Disable2fa, | |
| 65 | +} | |
| 66 | + | |
| 67 | +fn is_ghost(user: &User) -> bool { | |
| 68 | + normalize_name(&user.username) == GHOST_USERNAME | |
| 69 | +} | |
| 70 | + | |
| 71 | +async fn load(cx: &Cx) -> Result<Detail> { | |
| 72 | + let store = &app_context::<AppState>(cx).store; | |
| 73 | + let id = path_param_segment(cx, "user_id").to_owned(); | |
| 74 | + let Some(target) = store.user_by_id(&id).await? else { | |
| 75 | + return Err(not_found().into()); | |
| 76 | + }; | |
| 77 | + if target.is_org() || is_ghost(&target) { | |
| 78 | + return Err(not_found().into()); | |
| 79 | + } | |
| 80 | + Ok(Detail { | |
| 81 | + facts: store.account_facts(&target.id).await?, | |
| 82 | + suspension: store.suspension(&target.id).await?, | |
| 83 | + target, | |
| 84 | + }) | |
| 85 | +} | |
| 86 | + | |
| 87 | +fn done_text(lang: Lang, done: &str) -> Option<&'static str> { | |
| 88 | + Some(match done { | |
| 89 | + "suspended" => at(lang, A::OkSuspended), | |
| 90 | + "unsuspended" => at(lang, A::OkUnsuspended), | |
| 91 | + "admin_on" => at(lang, A::OkAdminOn), | |
| 92 | + "admin_off" => at(lang, A::OkAdminOff), | |
| 93 | + "tfa_off" => at(lang, A::Ok2faDisabled), | |
| 94 | + _ => return None, | |
| 95 | + }) | |
| 96 | +} | |
| 97 | + | |
| 98 | +fn when(stamp: Option<&str>, tz: &str, lang: Lang) -> String { | |
| 99 | + match stamp { | |
| 100 | + Some(s) => format_in_tz(stamp_unix(s), tz), | |
| 101 | + None => at(lang, A::Never).to_owned(), | |
| 102 | + } | |
| 103 | +} | |
| 104 | + | |
| 105 | +#[component] | |
| 106 | +async fn detail_body( | |
| 107 | + lang: Lang, | |
| 108 | + csrf: &str, | |
| 109 | + tz: &str, | |
| 110 | + viewer_id: &str, | |
| 111 | + detail: Detail, | |
| 112 | + notice: Notice, | |
| 113 | +) -> Result<impl View> { | |
| 114 | + let Detail { | |
| 115 | + target, | |
| 116 | + facts, | |
| 117 | + suspension, | |
| 118 | + } = detail; | |
| 119 | + let base = format!("/admin/users/{}", enc(&target.id)); | |
| 120 | + let own = target.id == viewer_id; | |
| 121 | + let created = format_in_tz(stamp_unix(&target.created_at), tz); | |
| 122 | + let last_login = when(facts.last_login.as_deref(), tz, lang); | |
| 123 | + let repos = facts.repo_count.to_string(); | |
| 124 | + let suspended = suspension.is_some(); | |
| 125 | + let status = if suspended { | |
| 126 | + at(lang, A::Suspended) | |
| 127 | + } else { | |
| 128 | + at(lang, A::Active) | |
| 129 | + }; | |
| 130 | + let tfa = if facts.two_factor { | |
| 131 | + at(lang, A::On) | |
| 132 | + } else { | |
| 133 | + at(lang, A::Off) | |
| 134 | + }; | |
| 135 | + let role = if target.is_admin { | |
| 136 | + at(lang, A::Administrator) | |
| 137 | + } else { | |
| 138 | + g::t(lang, K::RoleUser) | |
| 139 | + }; | |
| 140 | + let reason = suspension | |
| 141 | + .as_ref() | |
| 142 | + .map(|s| s.reason.clone()) | |
| 143 | + .unwrap_or_default(); | |
| 144 | + let email = target.email.clone().unwrap_or_default(); | |
| 145 | + let is_admin = target.is_admin; | |
| 146 | + let tfa_on = facts.two_factor; | |
| 147 | + let suspend_action = format!("{base}/suspend"); | |
| 148 | + let unsuspend_action = format!("{base}/unsuspend"); | |
| 149 | + let admin_action = format!("{base}/admin"); | |
| 150 | + let reset_action = format!("{base}/reset-link"); | |
| 151 | + let tfa_action = format!("{base}/disable-2fa"); | |
| 152 | + let delete_href = format!("{base}/delete"); | |
| 153 | + let Notice { done, error, link } = notice; | |
| 154 | + Ok(view! { | |
| 155 | + <section class="page-head"> | |
| 156 | + <h1>(target.username.as_str())</h1> | |
| 157 | + </section> | |
| 158 | + <section class="card"> | |
| 159 | + if let Some(message) = done { | |
| 160 | + <p class="notice" role="status">(message)</p> | |
| 161 | + } | |
| 162 | + if let Some(message) = error { | |
| 163 | + alert(message: message.as_str()) | |
| 164 | + } | |
| 165 | + if let Some(link) = link { | |
| 166 | + <p>(at(lang, A::ResetLinkReady))</p> | |
| 167 | + <code class="reset-link">(link.as_str())</code> | |
| 168 | + } | |
| 169 | + <dl class="kv-grid"> | |
| 170 | + <div><dt>(at(lang, A::Status))</dt><dd>(status)</dd></div> | |
| 171 | + <div><dt>(i18n::t(lang, Key::Email))</dt><dd>(email.as_str())</dd></div> | |
| 172 | + <div><dt>(g::t(lang, K::Role))</dt><dd>(role)</dd></div> | |
| 173 | + <div><dt>(i18n::t(lang, Key::Created))</dt><dd>(created.as_str())</dd></div> | |
| 174 | + <div><dt>(at(lang, A::LastLogin))</dt><dd>(last_login.as_str())</dd></div> | |
| 175 | + <div><dt>(at(lang, A::Repositories))</dt><dd>(repos.as_str())</dd></div> | |
| 176 | + <div><dt>(at(lang, A::TwoFactor))</dt><dd>(tfa)</dd></div> | |
| 177 | + </dl> | |
| 178 | + </section> | |
| 179 | + <section class="card"> | |
| 180 | + <h2>(at(lang, A::Actions))</h2> | |
| 181 | + <div class="action-grid"> | |
| 182 | + <div class="action-box"> | |
| 183 | + <h3>(if suspended { at(lang, A::Unsuspend) } else { at(lang, A::Suspend) })</h3> | |
| 184 | + if suspended { | |
| 185 | + <p class="muted small">(reason.as_str())</p> | |
| 186 | + <form method="post" action=(unsuspend_action.as_str())> | |
| 187 | + <input type="hidden" name="csrf" value=(csrf)> | |
| 188 | + <button type="submit">(at(lang, A::Unsuspend))</button> | |
| 189 | + </form> | |
| 190 | + } else if own { | |
| 191 | + <p class="muted small">(at(lang, A::ErrSelf))</p> | |
| 192 | + } else { | |
| 193 | + <p class="muted small">(at(lang, A::SuspendHelp))</p> | |
| 194 | + <form method="post" action=(suspend_action.as_str())> | |
| 195 | + <input type="hidden" name="csrf" value=(csrf)> | |
| 196 | + <label> | |
| 197 | + <span>(at(lang, A::SuspendReason))</span> | |
| 198 | + <input type="text" name="reason" maxlength="300" autocomplete="off"> | |
| 199 | + </label> | |
| 200 | + <button type="submit" class="danger">(at(lang, A::Suspend))</button> | |
| 201 | + </form> | |
| 202 | + } | |
| 203 | + </div> | |
| 204 | + <div class="action-box"> | |
| 205 | + <h3>(at(lang, A::Administrator))</h3> | |
| 206 | + <p class="muted small">(at(lang, A::AdminHelp))</p> | |
| 207 | + <form method="post" action=(admin_action.as_str())> | |
| 208 | + <input type="hidden" name="csrf" value=(csrf)> | |
| 209 | + <input type="hidden" name="admin" value=(if is_admin { "0" } else { "1" })> | |
| 210 | + <button type="submit">(if is_admin { at(lang, A::RevokeAdmin) } else { at(lang, A::GrantAdmin) })</button> | |
| 211 | + </form> | |
| 212 | + </div> | |
| 213 | + <div class="action-box"> | |
| 214 | + <h3>(at(lang, A::ResetPassword))</h3> | |
| 215 | + <p class="muted small">(at(lang, A::ResetHelp))</p> | |
| 216 | + <form method="post" action=(reset_action.as_str())> | |
| 217 | + <input type="hidden" name="csrf" value=(csrf)> | |
| 218 | + <button type="submit">(at(lang, A::GenerateLink))</button> | |
| 219 | + </form> | |
| 220 | + </div> | |
| 221 | + <div class="action-box"> | |
| 222 | + <h3>(at(lang, A::Disable2fa))</h3> | |
| 223 | + <p class="muted small">(at(lang, A::Disable2faHelp))</p> | |
| 224 | + if tfa_on { | |
| 225 | + <form method="post" action=(tfa_action.as_str())> | |
| 226 | + <input type="hidden" name="csrf" value=(csrf)> | |
| 227 | + <button type="submit" class="danger">(at(lang, A::Disable2fa))</button> | |
| 228 | + </form> | |
| 229 | + } else { | |
| 230 | + <p class="small">(at(lang, A::Off))</p> | |
| 231 | + } | |
| 232 | + </div> | |
| 233 | + </div> | |
| 234 | + <p class="link-row"> | |
| 235 | + <a href="/admin/users">(g::t(lang, K::BackToUsers))</a> | |
| 236 | + if !own { | |
| 237 | + <a class="danger" href=(delete_href.as_str())>(i18n::t(lang, Key::Delete))</a> | |
| 238 | + } | |
| 239 | + </p> | |
| 240 | + </section> | |
| 241 | + }) | |
| 242 | +} | |
| 243 | + | |
| 244 | +#[page("/admin/users/{user_id}")] | |
| 245 | +async fn detail_page(cx: &Cx) -> Result<impl View> { | |
| 246 | + let viewer = admin_only(cx).await?; | |
| 247 | + let lang = i18n::lang(cx, Some(&viewer.0)); | |
| 248 | + let query = query_params::<DoneQuery>(cx)?; | |
| 249 | + let detail = load(cx).await?; | |
| 250 | + let notice = Notice { | |
| 251 | + done: query.done.as_deref().and_then(|d| done_text(lang, d)), | |
| 252 | + ..Notice::default() | |
| 253 | + }; | |
| 254 | + let csrf = viewer.1.csrf_token.clone(); | |
| 255 | + let title = detail.target.username.clone(); | |
| 256 | + Ok(view! { | |
| 257 | + shell(title: title.as_str(), viewer: Some(&viewer), detail_body(lang: lang, csrf: csrf.as_str(), tz: viewer.0.timezone.as_str(), viewer_id: viewer.0.id.as_str(), detail: detail, notice: notice)) | |
| 258 | + }) | |
| 259 | +} | |
| 260 | + | |
| 261 | +/// Outcome of an action: a redirect key on success, or a message to show on the page. | |
| 262 | +enum Outcome { | |
| 263 | + Done(&'static str), | |
| 264 | + Link(String), | |
| 265 | + Refused(String), | |
| 266 | +} | |
| 267 | + | |
| 268 | +async fn perform(cx: &Cx, form: &ActionForm, action: Action) -> Result<(Outcome, Detail)> { | |
| 269 | + let viewer = admin_only(cx).await?; | |
| 270 | + if !check_csrf(&viewer.1, &form.csrf) { | |
| 271 | + return Err(forbidden().into()); | |
| 272 | + } | |
| 273 | + let lang = i18n::lang(cx, Some(&viewer.0)); | |
| 274 | + let state = app_context::<AppState>(cx); | |
| 275 | + let store = &state.store; | |
| 276 | + let detail = load(cx).await?; | |
| 277 | + let target = &detail.target; | |
| 278 | + let audit = |action: AuditAction, data: serde_json::Value| { | |
| 279 | + audit::record( | |
| 280 | + store, | |
| 281 | + Some(cx), | |
| 282 | + Actor::User(&viewer.0), | |
| 283 | + action, | |
| 284 | + Target { | |
| 285 | + kind: "user", | |
| 286 | + id: &target.id, | |
| 287 | + name: &target.username, | |
| 288 | + }, | |
| 289 | + data, | |
| 290 | + ) | |
| 291 | + }; | |
| 292 | + let refused = |e: forge_core::Error| -> Result<Outcome> { | |
| 293 | + match user_facing_message(&e) { | |
| 294 | + Some(message) => Ok(Outcome::Refused(message)), | |
| 295 | + None => Err(e.into()), | |
| 296 | + } | |
| 297 | + }; | |
| 298 | + let outcome = match action { | |
| 299 | + Action::Suspend => { | |
| 300 | + if target.id == viewer.0.id { | |
| 301 | + Outcome::Refused(at(lang, A::ErrSelf).to_owned()) | |
| 302 | + } else { | |
| 303 | + match store | |
| 304 | + .suspend_user(&target.id, &form.reason, Some(&viewer.0.id)) | |
| 305 | + .await | |
| 306 | + { | |
| 307 | + Ok(()) => { | |
| 308 | + audit( | |
| 309 | + AuditAction::UserSuspended, | |
| 310 | + serde_json::json!({ "reason": form.reason.trim() }), | |
| 311 | + ) | |
| 312 | + .await; | |
| 313 | + Outcome::Done("suspended") | |
| 314 | + } | |
| 315 | + Err(e) => refused(e)?, | |
| 316 | + } | |
| 317 | + } | |
| 318 | + } | |
| 319 | + Action::Unsuspend => { | |
| 320 | + if store.unsuspend_user(&target.id).await? { | |
| 321 | + audit(AuditAction::UserUnsuspended, serde_json::Value::Null).await; | |
| 322 | + } | |
| 323 | + Outcome::Done("unsuspended") | |
| 324 | + } | |
| 325 | + Action::SetAdmin => { | |
| 326 | + let grant = form.admin == "1"; | |
| 327 | + match store.set_admin(&target.id, grant).await { | |
| 328 | + Ok(()) => { | |
| 329 | + let kind = if grant { | |
| 330 | + AuditAction::AdminGranted | |
| 331 | + } else { | |
| 332 | + AuditAction::AdminRevoked | |
| 333 | + }; | |
| 334 | + audit(kind, serde_json::Value::Null).await; | |
| 335 | + Outcome::Done(if grant { "admin_on" } else { "admin_off" }) | |
| 336 | + } | |
| 337 | + Err(e) => refused(e)?, | |
| 338 | + } | |
| 339 | + } | |
| 340 | + Action::ResetLink => { | |
| 341 | + let token = store.create_reset_token(&target.id).await?; | |
| 342 | + store.delete_user_sessions(&target.id).await?; | |
| 343 | + audit( | |
| 344 | + AuditAction::PasswordResetByAdmin, | |
| 345 | + serde_json::json!({ "method": "link" }), | |
| 346 | + ) | |
| 347 | + .await; | |
| 348 | + let base = state.config.base_url.trim_end_matches('/'); | |
| 349 | + Outcome::Link(format!("{base}/reset/{token}")) | |
| 350 | + } | |
| 351 | + Action::Disable2fa => { | |
| 352 | + if two_factor_enabled(store, &target.id).await? { | |
| 353 | + store.disable_totp(&target.id).await?; | |
| 354 | + audit(AuditAction::TotpDisabledByAdmin, serde_json::Value::Null).await; | |
| 355 | + Outcome::Done("tfa_off") | |
| 356 | + } else { | |
| 357 | + Outcome::Refused(at(lang, A::ErrNoEmail).to_owned()) | |
| 358 | + } | |
| 359 | + } | |
| 360 | + }; | |
| 361 | + let detail = if matches!(outcome, Outcome::Done(_)) { | |
| 362 | + detail | |
| 363 | + } else { | |
| 364 | + // Reload so a refused or link outcome shows the current state. | |
| 365 | + load(cx).await? | |
| 366 | + }; | |
| 367 | + Ok((outcome, detail)) | |
| 368 | +} | |
| 369 | + | |
| 370 | +/// Redirects to the detail page after a success, or renders it with a message. | |
| 371 | +async fn respond(cx: &Cx, form: ActionForm, action: Action) -> Result<impl View> { | |
| 372 | + // `view!` expects the `__cx` binding that `#[page]` provides. | |
| 373 | + let __cx = cx; | |
| 374 | + let (outcome, detail) = perform(cx, &form, action).await?; | |
| 375 | + let viewer = admin_only(cx).await?; | |
| 376 | + let lang = i18n::lang(cx, Some(&viewer.0)); | |
| 377 | + let notice = match outcome { | |
| 378 | + Outcome::Done(key) => { | |
| 379 | + let id = enc(&detail.target.id).to_string(); | |
| 380 | + return Err(see_other(format!("/admin/users/{id}?done={key}")).into()); | |
| 381 | + } | |
| 382 | + Outcome::Link(link) => Notice { | |
| 383 | + link: Some(link), | |
| 384 | + ..Notice::default() | |
| 385 | + }, | |
| 386 | + Outcome::Refused(message) => Notice { | |
| 387 | + error: Some(message), | |
| 388 | + ..Notice::default() | |
| 389 | + }, | |
| 390 | + }; | |
| 391 | + let csrf = viewer.1.csrf_token.clone(); | |
| 392 | + let title = detail.target.username.clone(); | |
| 393 | + Ok(view! { | |
| 394 | + shell(title: title.as_str(), viewer: Some(&viewer), detail_body(lang: lang, csrf: csrf.as_str(), tz: viewer.0.timezone.as_str(), viewer_id: viewer.0.id.as_str(), detail: detail, notice: notice)) | |
| 395 | + }) | |
| 396 | +} | |
| 397 | + | |
| 398 | +#[page(POST "/admin/users/{user_id}/suspend")] | |
| 399 | +async fn suspend(cx: &Cx, Form(form): Form<ActionForm>) -> Result<impl View> { | |
| 400 | + respond(cx, form, Action::Suspend).await | |
| 401 | +} | |
| 402 | + | |
| 403 | +#[page(POST "/admin/users/{user_id}/unsuspend")] | |
| 404 | +async fn unsuspend(cx: &Cx, Form(form): Form<ActionForm>) -> Result<impl View> { | |
| 405 | + respond(cx, form, Action::Unsuspend).await | |
| 406 | +} | |
| 407 | + | |
| 408 | +#[page(POST "/admin/users/{user_id}/admin")] | |
| 409 | +async fn set_admin(cx: &Cx, Form(form): Form<ActionForm>) -> Result<impl View> { | |
| 410 | + respond(cx, form, Action::SetAdmin).await | |
| 411 | +} | |
| 412 | + | |
| 413 | +#[page(POST "/admin/users/{user_id}/reset-link")] | |
| 414 | +async fn reset_link(cx: &Cx, Form(form): Form<ActionForm>) -> Result<impl View> { | |
| 415 | + respond(cx, form, Action::ResetLink).await | |
| 416 | +} | |
| 417 | + | |
| 418 | +#[page(POST "/admin/users/{user_id}/disable-2fa")] | |
| 419 | +async fn disable_2fa(cx: &Cx, Form(form): Form<ActionForm>) -> Result<impl View> { | |
| 420 | + respond(cx, form, Action::Disable2fa).await | |
| 421 | +} |
crates/forge-web/src/pages/admin_users.rsmodified+7 -1
| @@ -73,7 +73,13 @@ async fn users_view( | ||
| 73 | 73 | <tbody> |
| 74 | 74 | for user in users.into_iter() { |
| 75 | 75 | <tr> |
| 76 | - <td class="nowrap">(user.username.clone())</td> | |
| 76 | + <td class="nowrap"> | |
| 77 | + if user.is_org() || is_ghost(&user) { | |
| 78 | + (user.username.clone()) | |
| 79 | + } else { | |
| 80 | + <a href=(format!("/admin/users/{}", enc(&user.id)))>(user.username.clone())</a> | |
| 81 | + } | |
| 82 | + </td> | |
| 77 | 83 | <td>(user.email.clone().unwrap_or_default())</td> |
| 78 | 84 | <td>(if user.is_org() { g::t(lang, K::RoleOrganization) } else if user.is_admin { g::t(lang, K::RoleAdmin) } else { g::t(lang, K::RoleUser) })</td> |
| 79 | 85 | <td class="small nowrap">(format_in_tz(stamp_unix(&user.created_at), tz))</td> |
crates/forge-web/src/pages/banner.rsadded+133 -0
| @@ -0,0 +1,133 @@ | ||
| 1 | +//! The site announcement banner. The admin sets it in the server settings (`banner.*`, live), and | |
| 2 | +//! the shell shows it under the header on every page. A visitor dismisses it with | |
| 3 | +//! `POST /-/banner/dismiss`, which stores the hash of the message in the `forge_banner` cookie, so a | |
| 4 | +//! changed message shows again. | |
| 5 | + | |
| 6 | +use std::time::Duration; | |
| 7 | + | |
| 8 | +use forge_core::config::BannerConfig; | |
| 9 | +use forge_core::token::hash_token; | |
| 10 | +use serde::Deserialize; | |
| 11 | +use topcoat::Result; | |
| 12 | +use topcoat::context::{Cx, try_app_context}; | |
| 13 | +use topcoat::cookie::{Cookie, Cookies, SameSite, cookies, time}; | |
| 14 | +use topcoat::router::content::Form; | |
| 15 | +use topcoat::router::error::{SeeOther, see_other}; | |
| 16 | +use topcoat::router::route; | |
| 17 | + | |
| 18 | +use crate::pages::theme_cookie::safe_back; | |
| 19 | +use crate::state::AppState; | |
| 20 | + | |
| 21 | +/// Name of the dismissal cookie. | |
| 22 | +pub const BANNER_COOKIE: &str = "forge_banner"; | |
| 23 | + | |
| 24 | +const BANNER_COOKIE_TTL: Duration = Duration::from_secs(365 * 24 * 60 * 60); | |
| 25 | + | |
| 26 | +/// What the shell draws. | |
| 27 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 28 | +pub struct BannerView { | |
| 29 | + pub message: String, | |
| 30 | + pub warning: bool, | |
| 31 | + pub hash: String, | |
| 32 | +} | |
| 33 | + | |
| 34 | +/// Short stable id of a message and level. | |
| 35 | +pub fn banner_hash(message: &str, level: &str) -> String { | |
| 36 | + hash_token(&format!("{level}\n{message}"))[..16].to_owned() | |
| 37 | +} | |
| 38 | + | |
| 39 | +/// The banner to show at `now`, or `None` when it is off, expired or dismissed (`dismissed` is the | |
| 40 | +/// cookie value). | |
| 41 | +pub fn view_for(config: &BannerConfig, now: i64, dismissed: Option<&str>) -> Option<BannerView> { | |
| 42 | + if !config.active_at(now) { | |
| 43 | + return None; | |
| 44 | + } | |
| 45 | + let message = config.message.trim().to_owned(); | |
| 46 | + let hash = banner_hash(&message, &config.level); | |
| 47 | + if dismissed == Some(hash.as_str()) { | |
| 48 | + return None; | |
| 49 | + } | |
| 50 | + Some(BannerView { | |
| 51 | + message, | |
| 52 | + warning: config.level == "warning", | |
| 53 | + hash, | |
| 54 | + }) | |
| 55 | +} | |
| 56 | + | |
| 57 | +/// The banner for this request, read from the live settings and the cookie. | |
| 58 | +pub fn current(cx: &Cx) -> Option<BannerView> { | |
| 59 | + let state = try_app_context::<AppState>(cx)?; | |
| 60 | + let live = state.live(); | |
| 61 | + if live.banner.message.trim().is_empty() { | |
| 62 | + return None; | |
| 63 | + } | |
| 64 | + let cookie = cookies(cx).get(BANNER_COOKIE).map(|c| c.value().to_owned()); | |
| 65 | + view_for(&live.banner, crate::views::now_unix(), cookie.as_deref()) | |
| 66 | +} | |
| 67 | + | |
| 68 | +#[derive(Deserialize)] | |
| 69 | +struct DismissForm { | |
| 70 | + #[serde(default)] | |
| 71 | + hash: String, | |
| 72 | + #[serde(default)] | |
| 73 | + back: String, | |
| 74 | +} | |
| 75 | + | |
| 76 | +#[route(POST "/-/banner/dismiss")] | |
| 77 | +async fn dismiss(cx: &Cx, Form(form): Form<DismissForm>) -> Result<SeeOther> { | |
| 78 | + let hash_ok = form.hash.len() == 16 && form.hash.bytes().all(|b| b.is_ascii_hexdigit()); | |
| 79 | + if hash_ok { | |
| 80 | + let max_age = | |
| 81 | + time::Duration::seconds(i64::try_from(BANNER_COOKIE_TTL.as_secs()).unwrap_or(i64::MAX)); | |
| 82 | + cookies(cx).add( | |
| 83 | + Cookie::build((BANNER_COOKIE, form.hash)) | |
| 84 | + .path("/") | |
| 85 | + .secure(true) | |
| 86 | + .http_only(true) | |
| 87 | + .same_site(SameSite::Lax) | |
| 88 | + .max_age(max_age) | |
| 89 | + .build(), | |
| 90 | + ); | |
| 91 | + } | |
| 92 | + Ok(see_other(safe_back(&form.back))) | |
| 93 | +} | |
| 94 | + | |
| 95 | +#[cfg(test)] | |
| 96 | +mod tests { | |
| 97 | + use super::*; | |
| 98 | + | |
| 99 | + fn config(message: &str, level: &str, expires: &str) -> BannerConfig { | |
| 100 | + BannerConfig { | |
| 101 | + message: message.into(), | |
| 102 | + level: level.into(), | |
| 103 | + expires: expires.into(), | |
| 104 | + } | |
| 105 | + } | |
| 106 | + | |
| 107 | + #[test] | |
| 108 | + fn empty_and_expired_banners_are_hidden() { | |
| 109 | + assert!(view_for(&config("", "info", ""), 0, None).is_none()); | |
| 110 | + let expiry = forge_core::config::parse_banner_expiry("2026-12-31 18:00").unwrap(); | |
| 111 | + let cfg = config("maintenance", "warning", "2026-12-31 18:00"); | |
| 112 | + assert!(view_for(&cfg, expiry - 1, None).is_some()); | |
| 113 | + assert!(view_for(&cfg, expiry, None).is_none()); | |
| 114 | + } | |
| 115 | + | |
| 116 | + #[test] | |
| 117 | + fn a_dismissed_hash_hides_only_that_message() { | |
| 118 | + let cfg = config("maintenance tonight", "info", ""); | |
| 119 | + let shown = view_for(&cfg, 0, None).unwrap(); | |
| 120 | + assert!(view_for(&cfg, 0, Some(&shown.hash)).is_none()); | |
| 121 | + let changed = config("maintenance tomorrow", "info", ""); | |
| 122 | + assert!(view_for(&changed, 0, Some(&shown.hash)).is_some()); | |
| 123 | + } | |
| 124 | + | |
| 125 | + #[test] | |
| 126 | + fn expiry_parses_utc_minutes() { | |
| 127 | + assert_eq!( | |
| 128 | + forge_core::config::parse_banner_expiry("1970-01-02 00:01"), | |
| 129 | + Some(86_400 + 60) | |
| 130 | + ); | |
| 131 | + assert!(forge_core::config::parse_banner_expiry("tomorrow").is_none()); | |
| 132 | + } | |
| 133 | +} |
crates/forge-web/src/pages/login.rsmodified+31 -3
| @@ -154,7 +154,10 @@ async fn login_submit(cx: &Cx, Form(form): Form<LoginForm>) -> Result<impl View> | ||
| 154 | 154 | json!({ "reason": "throttled" }), |
| 155 | 155 | ) |
| 156 | 156 | .await; |
| 157 | - (StatusCode::TOO_MANY_REQUESTS, t(lang, Key::ErrThrottled)) | |
| 157 | + ( | |
| 158 | + StatusCode::TOO_MANY_REQUESTS, | |
| 159 | + t(lang, Key::ErrThrottled).to_owned(), | |
| 160 | + ) | |
| 158 | 161 | } else { |
| 159 | 162 | // The store folds the name, so the lookup is case-insensitive. |
| 160 | 163 | // An organization is treated like an unknown name: it never signs in. |
| @@ -169,7 +172,32 @@ async fn login_submit(cx: &Cx, Form(form): Form<LoginForm>) -> Result<impl View> | ||
| 169 | 172 | }; |
| 170 | 173 | let password_ok = verify_password_async(form.password.clone(), hash).await?; |
| 171 | 174 | |
| 175 | + // Only someone who knows the password learns that the account is suspended. | |
| 176 | + let suspension = match &user { | |
| 177 | + Some(user) if password_ok => state.store.suspension(&user.id).await?, | |
| 178 | + _ => None, | |
| 179 | + }; | |
| 172 | 180 | match user { |
| 181 | + Some(user) if password_ok && suspension.is_some() => { | |
| 182 | + let reason = suspension.map(|s| s.reason).unwrap_or_default(); | |
| 183 | + audit::record( | |
| 184 | + &state.store, | |
| 185 | + Some(cx), | |
| 186 | + Actor::Anonymous, | |
| 187 | + AuditAction::LoginFailed, | |
| 188 | + Target { | |
| 189 | + kind: "user", | |
| 190 | + id: &user.id, | |
| 191 | + name: &user.username, | |
| 192 | + }, | |
| 193 | + json!({ "reason": "suspended" }), | |
| 194 | + ) | |
| 195 | + .await; | |
| 196 | + ( | |
| 197 | + StatusCode::OK, | |
| 198 | + crate::i18n::accounts::suspended_message(lang, &reason), | |
| 199 | + ) | |
| 200 | + } | |
| 173 | 201 | Some(user) if password_ok => { |
| 174 | 202 | limiter.clear(&user_key); |
| 175 | 203 | // With two-factor on, no session yet: park the login until the code is checked. |
| @@ -215,7 +243,7 @@ async fn login_submit(cx: &Cx, Form(form): Form<LoginForm>) -> Result<impl View> | ||
| 215 | 243 | serde_json::Value::Null, |
| 216 | 244 | ) |
| 217 | 245 | .await; |
| 218 | - (StatusCode::OK, t(lang, Key::ErrInvalidLogin)) | |
| 246 | + (StatusCode::OK, t(lang, Key::ErrInvalidLogin).to_owned()) | |
| 219 | 247 | } |
| 220 | 248 | } |
| 221 | 249 | }; |
| @@ -227,7 +255,7 @@ async fn login_submit(cx: &Cx, Form(form): Form<LoginForm>) -> Result<impl View> | ||
| 227 | 255 | Ok(view! { |
| 228 | 256 | (status) |
| 229 | 257 | (headers) |
| 230 | - shell(title: t(lang, Key::LogIn), viewer: None, login_form(lang: lang, next: next.as_str(), username: username.as_str(), precsrf: precsrf.as_str(), error: Some(message.to_owned()))) | |
| 258 | + shell(title: t(lang, Key::LogIn), viewer: None, login_form(lang: lang, next: next.as_str(), username: username.as_str(), precsrf: precsrf.as_str(), error: Some(message))) | |
| 231 | 259 | }) |
| 232 | 260 | } |
| 233 | 261 |
crates/forge-web/src/pages/mod.rsmodified+5 -0
| @@ -1,10 +1,14 @@ | ||
| 1 | 1 | //! Server-rendered pages. |
| 2 | 2 | |
| 3 | +#[cfg(test)] | |
| 4 | +mod account_tools_tests; | |
| 3 | 5 | pub mod admin_backups; |
| 6 | +pub mod admin_health; | |
| 4 | 7 | pub mod admin_mail; |
| 5 | 8 | pub mod admin_replication; |
| 6 | 9 | pub mod admin_runners; |
| 7 | 10 | pub mod admin_server; |
| 11 | +pub mod admin_user_detail; | |
| 8 | 12 | pub mod admin_users; |
| 9 | 13 | pub mod archive; |
| 10 | 14 | pub mod assets; |
| @@ -13,6 +17,7 @@ pub mod authoring; | ||
| 13 | 17 | #[cfg(test)] |
| 14 | 18 | mod authoring_tests; |
| 15 | 19 | pub mod avatars; |
| 20 | +pub mod banner; | |
| 16 | 21 | pub mod blame; |
| 17 | 22 | pub mod blob; |
| 18 | 23 | pub mod branches; |
crates/forge-web/src/pages/settings_security.rsmodified+10 -0
| @@ -726,6 +726,15 @@ async fn password_change(cx: &Cx, Form(form): Form<PasswordForm>) -> Result<impl | ||
| 726 | 726 | serde_json::Value::Null, |
| 727 | 727 | ) |
| 728 | 728 | .await; |
| 729 | + if let Err(e) = crate::mail::account::send_password_changed( | |
| 730 | + state, | |
| 731 | + &viewer.0, | |
| 732 | + &forge_core::time::now_stamp(), | |
| 733 | + ) | |
| 734 | + .await | |
| 735 | + { | |
| 736 | + tracing::warn!(error = %e, "could not queue the password change notice"); | |
| 737 | + } | |
| 729 | 738 | Err(see_other("/settings/security?saved=password").into()) |
| 730 | 739 | } |
| 731 | 740 | |
| @@ -1047,6 +1056,7 @@ mod tests { | ||
| 1047 | 1056 | mail: Default::default(), |
| 1048 | 1057 | orgs: Default::default(), |
| 1049 | 1058 | self_update: Default::default(), |
| 1059 | + banner: Default::default(), | |
| 1050 | 1060 | }; |
| 1051 | 1061 | let config = Arc::new(config); |
| 1052 | 1062 | let state = AppState { |
crates/forge-web/src/test_support.rsmodified+1 -0
| @@ -53,6 +53,7 @@ pub fn test_config(dir: &Path) -> Config { | ||
| 53 | 53 | mail: Default::default(), |
| 54 | 54 | orgs: Default::default(), |
| 55 | 55 | self_update: Default::default(), |
| 56 | + banner: Default::default(), | |
| 56 | 57 | } |
| 57 | 58 | } |
| 58 | 59 |
crates/forge-web/src/views/mod.rsmodified+24 -0
| @@ -163,6 +163,9 @@ pub async fn shell( | ||
| 163 | 163 | let theme_csrf = viewer.map(|(_, session)| session.csrf_token.clone()); |
| 164 | 164 | let back = uri(__cx).path_and_query().map(|p| p.as_str().to_owned()); |
| 165 | 165 | let lang = i18n::lang(__cx, viewer.map(|(user, _)| user)); |
| 166 | + let banner = crate::pages::banner::current(__cx); | |
| 167 | + let banner_back = back.clone().unwrap_or_else(|| "/".to_owned()); | |
| 168 | + let dismiss_label = crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Dismiss); | |
| 166 | 169 | // The admin area and the user settings swap the global links for their own list. Signed-in only. |
| 167 | 170 | let mut section = if signed_in { |
| 168 | 171 | section_for(lang, uri(__cx).path()) |
| @@ -339,6 +342,18 @@ pub async fn shell( | ||
| 339 | 342 | <a class="button primary" href="/login">(t(lang, Key::LogIn))</a> |
| 340 | 343 | } |
| 341 | 344 | </header> |
| 345 | + if let Some(banner) = banner { | |
| 346 | + <div class=(if banner.warning { "site-banner warning" } else { "site-banner" }) role="status"> | |
| 347 | + <p>(banner.message.as_str())</p> | |
| 348 | + <form method="post" action="/-/banner/dismiss"> | |
| 349 | + <input type="hidden" name="hash" value=(banner.hash.as_str())> | |
| 350 | + <input type="hidden" name="back" value=(banner_back.as_str())> | |
| 351 | + <button type="submit" class="icon-btn" aria-label=(dismiss_label) title=(dismiss_label)> | |
| 352 | + <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"/></svg> | |
| 353 | + </button> | |
| 354 | + </form> | |
| 355 | + </div> | |
| 356 | + } | |
| 342 | 357 | <div class="shell"> |
| 343 | 358 | if signed_in { |
| 344 | 359 | <aside class="shell-sidebar"> |
| @@ -463,6 +478,12 @@ fn admin_items(lang: Lang) -> Vec<NavItem> { | ||
| 463 | 478 | }; |
| 464 | 479 | vec![ |
| 465 | 480 | item("users", "/admin/users", ad::t(lang, AK::Users), "users"), |
| 481 | + item( | |
| 482 | + "health", | |
| 483 | + "/admin/health", | |
| 484 | + crate::i18n::accounts::t(lang, crate::i18n::accounts::A::Health), | |
| 485 | + "health", | |
| 486 | + ), | |
| 466 | 487 | item( |
| 467 | 488 | "invites", |
| 468 | 489 | "/admin/invites", |
| @@ -660,6 +681,9 @@ async fn nav_icon(name: &str) -> Result<impl View> { | ||
| 660 | 681 | if name == "teams" { |
| 661 | 682 | <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="7" r="3"/><circle cx="5" cy="17" r="3"/><circle cx="19" cy="17" r="3"/><path d="M10 9.5 6.5 14.5M14 9.5l3.5 5M8 17h8"/></svg> |
| 662 | 683 | } |
| 684 | + if name == "health" { | |
| 685 | + <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 12h4l2.5-6 4 12 2.5-6H21"/></svg> | |
| 686 | + } | |
| 663 | 687 | if name == "users" { |
| 664 | 688 | <svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><circle cx="9" cy="8" r="4"/><path d="M2 21c0-4 3-6 7-6s7 2 7 6"/><path d="M16 4a4 4 0 0 1 0 8M22 21c0-3-2-5-4-5.5"/></svg> |
| 665 | 689 | } |
style/_account_admin.scssadded+172 -0
| @@ -0,0 +1,172 @@ | ||
| 1 | +// Site banner, admin user detail and the health grid. | |
| 2 | + | |
| 3 | +.site-banner { | |
| 4 | + display: flex; | |
| 5 | + align-items: center; | |
| 6 | + justify-content: space-between; | |
| 7 | + gap: 12px; | |
| 8 | + padding: 8px 16px; | |
| 9 | + background: var(--accent-soft, var(--surface-2)); | |
| 10 | + color: var(--text); | |
| 11 | + border-bottom: 1px solid var(--border); | |
| 12 | + | |
| 13 | + p { | |
| 14 | + margin: 0; | |
| 15 | + min-width: 0; | |
| 16 | + overflow-wrap: anywhere; | |
| 17 | + } | |
| 18 | + | |
| 19 | + form { | |
| 20 | + margin: 0; | |
| 21 | + flex: none; | |
| 22 | + } | |
| 23 | + | |
| 24 | + &.warning { | |
| 25 | + background: var(--alert-bg); | |
| 26 | + color: var(--alert-text); | |
| 27 | + border-bottom-color: var(--warn); | |
| 28 | + } | |
| 29 | +} | |
| 30 | + | |
| 31 | +.kv-grid { | |
| 32 | + display: grid; | |
| 33 | + grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); | |
| 34 | + gap: 12px 20px; | |
| 35 | + margin: 0; | |
| 36 | + | |
| 37 | + div { | |
| 38 | + min-width: 0; | |
| 39 | + } | |
| 40 | + | |
| 41 | + dt { | |
| 42 | + color: var(--muted); | |
| 43 | + font-size: 0.8125rem; | |
| 44 | + margin-bottom: 2px; | |
| 45 | + } | |
| 46 | + | |
| 47 | + dd { | |
| 48 | + margin: 0; | |
| 49 | + font-weight: 600; | |
| 50 | + overflow-wrap: anywhere; | |
| 51 | + } | |
| 52 | +} | |
| 53 | + | |
| 54 | +.action-grid { | |
| 55 | + display: grid; | |
| 56 | + grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); | |
| 57 | + gap: 16px; | |
| 58 | + | |
| 59 | + .action-box { | |
| 60 | + border: 1px solid var(--border); | |
| 61 | + border-radius: var(--radius-lg); | |
| 62 | + padding: 14px; | |
| 63 | + display: flex; | |
| 64 | + flex-direction: column; | |
| 65 | + gap: 8px; | |
| 66 | + min-width: 0; | |
| 67 | + | |
| 68 | + h3 { | |
| 69 | + margin: 0; | |
| 70 | + font-size: 1rem; | |
| 71 | + } | |
| 72 | + | |
| 73 | + p { | |
| 74 | + margin: 0; | |
| 75 | + } | |
| 76 | + | |
| 77 | + form { | |
| 78 | + display: flex; | |
| 79 | + flex-direction: column; | |
| 80 | + gap: 8px; | |
| 81 | + margin-top: auto; | |
| 82 | + } | |
| 83 | + } | |
| 84 | +} | |
| 85 | + | |
| 86 | +.reset-link { | |
| 87 | + display: block; | |
| 88 | + padding: 8px 10px; | |
| 89 | + border: 1px solid var(--border); | |
| 90 | + border-radius: var(--radius-md); | |
| 91 | + background: var(--surface-2); | |
| 92 | + font-family: var(--mono); | |
| 93 | + font-size: 0.8125rem; | |
| 94 | + overflow-wrap: anywhere; | |
| 95 | + user-select: all; | |
| 96 | +} | |
| 97 | + | |
| 98 | +.health-grid { | |
| 99 | + display: grid; | |
| 100 | + grid-template-columns: repeat(auto-fit, minmax(min(100%, 165px), 1fr)); | |
| 101 | + gap: 12px; | |
| 102 | + margin-bottom: 16px; | |
| 103 | + | |
| 104 | + .tile { | |
| 105 | + background: var(--surface); | |
| 106 | + border: 1px solid var(--border); | |
| 107 | + border-radius: var(--radius-lg); | |
| 108 | + padding: 14px 16px; | |
| 109 | + min-width: 0; | |
| 110 | + | |
| 111 | + h2 { | |
| 112 | + margin: 0 0 8px; | |
| 113 | + font-size: 0.8125rem; | |
| 114 | + font-weight: 600; | |
| 115 | + color: var(--muted); | |
| 116 | + text-transform: none; | |
| 117 | + } | |
| 118 | + | |
| 119 | + .big { | |
| 120 | + font-size: 1.5rem; | |
| 121 | + font-weight: 600; | |
| 122 | + line-height: 1.2; | |
| 123 | + overflow-wrap: anywhere; | |
| 124 | + } | |
| 125 | + | |
| 126 | + .sub { | |
| 127 | + color: var(--muted); | |
| 128 | + font-size: 0.8125rem; | |
| 129 | + margin-top: 4px; | |
| 130 | + overflow-wrap: anywhere; | |
| 131 | + } | |
| 132 | + | |
| 133 | + .meter { | |
| 134 | + display: block; | |
| 135 | + width: 100%; | |
| 136 | + height: 6px; | |
| 137 | + margin-top: 8px; | |
| 138 | + appearance: none; | |
| 139 | + border: 0; | |
| 140 | + border-radius: var(--radius-full); | |
| 141 | + background: var(--surface-2); | |
| 142 | + overflow: hidden; | |
| 143 | + | |
| 144 | + &::-webkit-progress-bar { | |
| 145 | + background: var(--surface-2); | |
| 146 | + } | |
| 147 | + | |
| 148 | + &::-webkit-progress-value { | |
| 149 | + background: var(--accent); | |
| 150 | + } | |
| 151 | + | |
| 152 | + &::-moz-progress-bar { | |
| 153 | + background: var(--accent); | |
| 154 | + } | |
| 155 | + } | |
| 156 | + | |
| 157 | + &.bad .big { | |
| 158 | + color: var(--bad); | |
| 159 | + } | |
| 160 | + | |
| 161 | + &.ok .big { | |
| 162 | + color: var(--ok); | |
| 163 | + } | |
| 164 | + } | |
| 165 | +} | |
| 166 | + | |
| 167 | +.link-row { | |
| 168 | + display: flex; | |
| 169 | + flex-wrap: wrap; | |
| 170 | + gap: 8px 20px; | |
| 171 | + margin: 16px 0 0; | |
| 172 | +} |
style/main.scssmodified+2 -0
| @@ -6285,3 +6285,5 @@ button.ci-job-last { | ||
| 6285 | 6285 | width: auto; |
| 6286 | 6286 | min-width: 12rem; |
| 6287 | 6287 | } |
| 6288 | + | |
| 6289 | +@import "account_admin"; |