| 19bb31ff Andy McCall ↶ |
1 |
|
| 2 |
|
| 3 |
|
| 4 |
use super::settings::csrf; |
| 5 |
use super::{filters, Error, Page, Shell}; |
| 6 |
use crate::auth::{self, Viewer}; |
| 7 |
use crate::db::accounts; |
| 8 |
use crate::Shared; |
| 9 |
use askama::Template; |
| 10 |
use axum::extract::{Form, State}; |
| 11 |
use serde::Deserialize; |
| 12 |
|
| 13 |
#[derive(Template)] |
| 14 |
#[template(path = "admin.html")] |
| 15 |
pub struct AdminPage { |
| 16 |
shell: Shell, |
| 17 |
accounts: Vec<accounts::Account>, |
| 18 |
orgs: Vec<accounts::Organisation>, |
| 19 |
mode: String, |
| 20 |
invitations: Vec<(String, Option<i64>, i64)>, |
| 21 |
audit: Vec<accounts::AuditRow>, |
| 22 |
repos: usize, |
| 23 |
notice: Option<String>, |
| 24 |
} |
| 25 |
|
| 26 |
fn require_admin(viewer: &Viewer, shell: &Shell) -> Result<accounts::Account, Error> { |
| 27 |
match viewer.account() { |
| 28 |
Some(a) if a.is_admin => Ok(a.clone()), |
| 29 |
_ => Err(Error::not_found(shell.clone())), |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
async fn admin_page(app: &Shared, shell: Shell, notice: Option<String>) -> Result<Page<AdminPage>, Error> { |
| 34 |
let e = |e| Error::from_db(shell.clone(), e); |
| 35 |
let accounts_list = accounts::accounts(&app.db).await.map_err(e)?; |
| 36 |
let orgs = accounts::orgs(&app.db).await.map_err(e)?; |
| 37 |
let mode = super::session::registration_mode(app).await; |
| 38 |
let invitations = accounts::invitations(&app.db).await.map_err(e)?; |
| 39 |
let audit = accounts::audit_rows(&app.db, 100).await.map_err(e)?; |
| 40 |
let repos = crate::db::repos::list(&app.db).await.map_err(e)?.len(); |
| 41 |
Ok(Page(AdminPage { shell, accounts: accounts_list, orgs, mode, invitations, audit, repos, notice })) |
| 42 |
} |
| 43 |
|
| 44 |
pub async fn index(State(app): State<Shared>, viewer: Viewer) -> Result<Page<AdminPage>, Error> { |
| 45 |
let shell = Shell::new(&app, "/admin", &viewer); |
| 46 |
require_admin(&viewer, &shell)?; |
| 47 |
admin_page(&app, shell, None).await |
| 48 |
} |
| 49 |
|
| 50 |
#[derive(Deserialize)] |
| 51 |
pub struct ModeForm { |
| 52 |
#[serde(rename = "_csrf")] |
| 53 |
csrf_token: String, |
| 54 |
mode: String, |
| 55 |
} |
| 56 |
|
| 57 |
pub async fn set_mode(State(app): State<Shared>, viewer: Viewer, Form(f): Form<ModeForm>) -> Result<Page<AdminPage>, Error> { |
| 58 |
let shell = Shell::new(&app, "/admin", &viewer); |
| 59 |
let me = require_admin(&viewer, &shell)?; |
| 60 |
csrf(&viewer, &f.csrf_token, &shell)?; |
| 61 |
if !matches!(f.mode.as_str(), "open" | "invite" | "closed") { |
| 62 |
return Err(Error::bad(shell, "mode is open, invite or closed")); |
| 63 |
} |
| 64 |
accounts::set_setting(&app.db, "registration_mode", &f.mode).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 65 |
accounts::audit(&app.db, Some(&me), "admin.registration", &f.mode, "").await.ok(); |
| 66 |
admin_page(&app, shell, Some(format!("Registration is {}.", f.mode))).await |
| 67 |
} |
| 68 |
|
| 69 |
pub async fn invite(State(app): State<Shared>, viewer: Viewer, Form(f): Form<super::session::CsrfForm>) -> Result<Page<AdminPage>, Error> { |
| 70 |
let shell = Shell::new(&app, "/admin", &viewer); |
| 71 |
let me = require_admin(&viewer, &shell)?; |
| 72 |
csrf(&viewer, &f.csrf, &shell)?; |
| 73 |
let code = auth::random_hex(12); |
| 74 |
accounts::create_invitation(&app.db, &code, Some(me.id)).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 75 |
accounts::audit(&app.db, Some(&me), "admin.invite", &code, "").await.ok(); |
| 76 |
admin_page(&app, shell, Some(format!("Invitation created: {}/register?invite={code}", app.config.base_url()))).await |
| 77 |
} |
| 78 |
|
| 79 |
#[derive(Deserialize)] |
| 80 |
pub struct AccountForm { |
| 81 |
#[serde(rename = "_csrf")] |
| 82 |
csrf_token: String, |
| 83 |
username: String, |
| 84 |
action: String, |
| 85 |
} |
| 86 |
|
| 87 |
pub async fn account(State(app): State<Shared>, viewer: Viewer, Form(f): Form<AccountForm>) -> Result<Page<AdminPage>, Error> { |
| 88 |
let shell = Shell::new(&app, "/admin", &viewer); |
| 89 |
let me = require_admin(&viewer, &shell)?; |
| 90 |
csrf(&viewer, &f.csrf_token, &shell)?; |
| 91 |
let Some(target) = accounts::account_by_name(&app.db, f.username.trim()).await.map_err(|e| Error::from_db(shell.clone(), e))? else { |
| 92 |
return admin_page(&app, shell, Some("No such account.".into())).await; |
| 93 |
}; |
| 94 |
if target.id == me.id && matches!(f.action.as_str(), "ban" | "demote") { |
| 95 |
return admin_page(&app, shell, Some("Not on yourself.".into())).await; |
| 96 |
} |
| 97 |
let e = |e| Error::from_db(shell.clone(), e); |
| 34beb1a7 Andy McCall ↶ |
98 |
if f.action == "reset_link" { |
| 99 |
if target.banned { |
| 100 |
return admin_page(&app, shell, Some("A banned account cannot be reset.".into())).await; |
| 101 |
} |
| 102 |
let url = super::recovery::admin_reset_link(&app, &me, &target).await.map_err(e)?; |
| 103 |
return admin_page( |
| 104 |
&app, |
| 105 |
shell, |
| 106 |
Some(format!("Reset link for {} (works once, for 24 hours; shown only now): {url}", target.username)), |
| 107 |
) |
| 108 |
.await; |
| 109 |
} |
| 19bb31ff Andy McCall ↶ |
110 |
match f.action.as_str() { |
| 111 |
"ban" => accounts::set_banned(&app.db, target.id, true).await.map_err(e)?, |
| 112 |
"unban" => accounts::set_banned(&app.db, target.id, false).await.map_err(e)?, |
| 113 |
"promote" => accounts::set_admin(&app.db, target.id, true).await.map_err(e)?, |
| 114 |
"demote" => accounts::set_admin(&app.db, target.id, false).await.map_err(e)?, |
| 115 |
_ => return Err(Error::bad(shell, "unknown action")), |
| 116 |
} |
| 117 |
accounts::audit(&app.db, Some(&me), &format!("admin.account.{}", f.action), &target.username, "").await.ok(); |
| 118 |
admin_page(&app, shell, Some(format!("{}: {}.", target.username, f.action))).await |
| 119 |
} |
| 8fb35df7 Andy McCall ↶ |
120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
pub struct StorageRow { |
| 125 |
pub slug: String, |
| 126 |
pub bytes: u64, |
| 127 |
|
| 128 |
pub loose: usize, |
| 129 |
pub packs: usize, |
| 130 |
} |
| 131 |
|
| 132 |
#[derive(Template)] |
| 133 |
#[template(path = "admin_storage.html")] |
| 134 |
pub struct StoragePage { |
| 135 |
shell: Shell, |
| 136 |
rows: Vec<StorageRow>, |
| 137 |
total: u64, |
| 138 |
notice: Option<String>, |
| 139 |
error: Option<String>, |
| 140 |
} |
| 141 |
|
| 142 |
|
| 143 |
fn footprint(dir: &std::path::Path) -> (u64, usize, usize) { |
| 144 |
let (mut bytes, mut loose, mut packs) = (0u64, 0usize, 0usize); |
| 145 |
let mut stack = vec![dir.to_path_buf()]; |
| 146 |
while let Some(d) = stack.pop() { |
| 147 |
let Ok(rd) = std::fs::read_dir(&d) else { continue }; |
| 148 |
for e in rd.flatten() { |
| 149 |
let Ok(ft) = e.file_type() else { continue }; |
| 150 |
if ft.is_dir() { |
| 151 |
stack.push(e.path()); |
| 152 |
} else if ft.is_file() { |
| 153 |
bytes += e.metadata().map(|m| m.len()).unwrap_or(0); |
| 154 |
let p = e.path(); |
| 155 |
if p.components().any(|c| c.as_os_str() == "loose") { |
| 156 |
loose += 1; |
| 157 |
} else if p.extension().is_some_and(|x| x == "pack") { |
| 158 |
packs += 1; |
| 159 |
} |
| 160 |
} |
| 161 |
} |
| 162 |
} |
| 163 |
(bytes, loose, packs) |
| 164 |
} |
| 165 |
|
| 166 |
async fn storage_page(app: &Shared, shell: Shell, notice: Option<String>, error: Option<String>) -> Result<Page<StoragePage>, Error> { |
| 167 |
let repos = crate::db::repos::list(&app.db).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 168 |
let dirs: Vec<(String, std::path::PathBuf)> = |
| 169 |
repos.iter().filter_map(|r| crate::repos::RepoName::new(&r.owner, &r.name).map(|n| (n.to_string(), app.repos.dir(&n)))).collect(); |
| 170 |
let mut rows = tokio::task::spawn_blocking(move || { |
| 171 |
dirs.into_iter() |
| 172 |
.map(|(slug, dir)| { |
| 173 |
let (bytes, loose, packs) = footprint(&dir); |
| 174 |
StorageRow { slug, bytes, loose, packs } |
| 175 |
}) |
| 176 |
.collect::<Vec<_>>() |
| 177 |
}) |
| 178 |
.await |
| 179 |
.unwrap_or_default(); |
| 180 |
rows.sort_by_key(|r| std::cmp::Reverse(r.bytes)); |
| 181 |
let total = rows.iter().map(|r| r.bytes).sum(); |
| 182 |
Ok(Page(StoragePage { shell, rows, total, notice, error })) |
| 183 |
} |
| 184 |
|
| 185 |
pub async fn storage(State(app): State<Shared>, viewer: Viewer) -> Result<Page<StoragePage>, Error> { |
| 186 |
let shell = Shell::new(&app, "/admin/storage", &viewer); |
| 187 |
require_admin(&viewer, &shell)?; |
| 188 |
storage_page(&app, shell, None, None).await |
| 189 |
} |
| 190 |
|
| 191 |
#[derive(Deserialize)] |
| 192 |
pub struct MaintainForm { |
| 193 |
#[serde(rename = "_csrf")] |
| 194 |
csrf_token: String, |
| 195 |
|
| 196 |
repo: String, |
| 197 |
} |
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
pub async fn maintain(State(app): State<Shared>, viewer: Viewer, Form(f): Form<MaintainForm>) -> Result<Page<StoragePage>, Error> { |
| 202 |
let shell = Shell::new(&app, "/admin/storage", &viewer); |
| 203 |
let me = require_admin(&viewer, &shell)?; |
| 204 |
csrf(&viewer, &f.csrf_token, &shell)?; |
| 205 |
let names: Vec<crate::repos::RepoName> = if f.repo == "*" { |
| 206 |
crate::db::repos::list(&app.db) |
| 207 |
.await |
| 208 |
.map_err(|e| Error::from_db(shell.clone(), e))? |
| 209 |
.iter() |
| 210 |
.filter_map(|r| crate::repos::RepoName::new(&r.owner, &r.name)) |
| 211 |
.collect() |
| 212 |
} else { |
| 213 |
match crate::repos::RepoName::parse(&f.repo) { |
| 214 |
Some(n) if app.repos.exists(&n) => vec![n], |
| 215 |
_ => return storage_page(&app, shell, None, Some(format!("No repository {}.", f.repo))).await, |
| 216 |
} |
| 217 |
}; |
| 218 |
let (mut packed, mut pruned, mut freed, mut failed) = (0usize, 0usize, 0u64, Vec::new()); |
| 219 |
for name in &names { |
| 220 |
match app.repos.write(name, |r, _| r.gc(false).map_err(crate::repos::RepoError::Oxy)).await { |
| 221 |
Ok(rep) => { |
| 222 |
packed += rep.packed.objects; |
| 223 |
pruned += rep.pruned.objects; |
| 224 |
freed += rep.pruned.bytes + rep.packed.raw_bytes.saturating_sub(rep.packed.packed_bytes); |
| 225 |
} |
| 226 |
Err(e) => failed.push(format!("{name}: {e}")), |
| 227 |
} |
| 228 |
} |
| 229 |
let summary = format!( |
| 230 |
"Maintained {} repositor{}: {packed} loose objects packed, {pruned} unreachable objects pruned, about {} saved.", |
| 231 |
names.len(), |
| 232 |
if names.len() == 1 { "y" } else { "ies" }, |
| 233 |
crate::render::bytes(freed) |
| 234 |
); |
| 235 |
accounts::audit(&app.db, Some(&me), "admin.gc", &f.repo, &summary).await.ok(); |
| 236 |
let error = (!failed.is_empty()).then(|| failed.join("; ")); |
| 237 |
storage_page(&app, shell, Some(summary), error).await |
| 238 |
} |