admin.rs
| 1 | //! Admin API (milestone 7): user management and server settings. |
| 2 | //! All routes require an admin session (via [`AdminUser`]). |
| 3 | |
| 4 | use std::sync::Arc; |
| 5 | |
| 6 | use api_types::{ |
| 7 | AdminPimLink, AdminShare, AdminUser, CreateRoom, CreateUser, Mode, OkResp, RoomInfo, RoomKind, |
| 8 | Root, Settings, UpdateRoom, UpdateUser, |
| 9 | }; |
| 10 | use axum::Json; |
| 11 | use axum::extract::{Path as AxumPath, State}; |
| 12 | use axum::http::StatusCode; |
| 13 | |
| 14 | use crate::api::common::AdminUser as AdminGuard; |
| 15 | use crate::api::common::{ |
| 16 | blocking, hash_password, root_info, validate_account_name, validate_password, |
| 17 | }; |
| 18 | use crate::api::pim::principal_href; |
| 19 | use crate::api::shares; |
| 20 | use crate::api::{pim_api, pim_schedule}; |
| 21 | use crate::db::{PimPrincipal, RootRow, UserType}; |
| 22 | use crate::error::{ApiError, AppState}; |
| 23 | use crate::fs; |
| 24 | |
| 25 | // --------------------------------------------------------------------------- |
| 26 | // Helpers |
| 27 | // --------------------------------------------------------------------------- |
| 28 | |
| 29 | fn admin_user(state: &AppState, user: &crate::db::User, roots: &[RootRow]) -> AdminUser { |
| 30 | AdminUser { |
| 31 | id: user.id, |
| 32 | name: user.name.clone(), |
| 33 | is_admin: user.is_admin, |
| 34 | active: user.active, |
| 35 | roots: roots.iter().map(|r| root_info(state, r)).collect(), |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | /// Validate each requested root path (must exist, be a directory, and stay |
| 40 | /// inside the server root). Returns the (path, mode) pairs. |
| 41 | /// |
| 42 | /// The mode needs no check: `Mode` only deserializes from "rw" or "ro", so a |
| 43 | /// bad value is rejected by the `Json` extractor before this runs. |
| 44 | async fn validate_roots(state: &AppState, roots: &[Root]) -> Result<Vec<(String, Mode)>, ApiError> { |
| 45 | let mut out = Vec::new(); |
| 46 | for r in roots { |
| 47 | let path = if r.path.trim().is_empty() { |
| 48 | ".".to_string() |
| 49 | } else { |
| 50 | r.path.trim().to_string() |
| 51 | }; |
| 52 | let server_root = state.root.clone(); |
| 53 | let (path2, label) = (path.clone(), path.clone()); |
| 54 | // The message is built inside the closure so it carries the |
| 55 | // `FsError`, not the join failure. |
| 56 | blocking(move || { |
| 57 | fs::resolve_root(&server_root, &path2).map_err(|e| { |
| 58 | let msg = ApiError::from(e).1; |
| 59 | ApiError::new( |
| 60 | StatusCode::BAD_REQUEST, |
| 61 | format!("root path '{label}': {msg}"), |
| 62 | ) |
| 63 | }) |
| 64 | }) |
| 65 | .await?; |
| 66 | out.push((path, r.mode)); |
| 67 | } |
| 68 | Ok(out) |
| 69 | } |
| 70 | |
| 71 | // --------------------------------------------------------------------------- |
| 72 | // Handlers |
| 73 | // --------------------------------------------------------------------------- |
| 74 | |
| 75 | /// GET /api/admin/users — list all users with their roots. |
| 76 | pub async fn list_users( |
| 77 | State(state): State<Arc<AppState>>, |
| 78 | _admin: AdminGuard, |
| 79 | ) -> Result<Json<Vec<AdminUser>>, ApiError> { |
| 80 | let out = state |
| 81 | .db |
| 82 | .all_users_with_roots() |
| 83 | .await? |
| 84 | .into_iter() |
| 85 | .map(|(u, roots)| admin_user(&state, &u, &roots)) |
| 86 | .collect(); |
| 87 | Ok(Json(out)) |
| 88 | } |
| 89 | |
| 90 | /// POST /api/admin/users — create a user. |
| 91 | pub async fn create_user( |
| 92 | State(state): State<Arc<AppState>>, |
| 93 | _admin: AdminGuard, |
| 94 | Json(body): Json<CreateUser>, |
| 95 | ) -> Result<Json<AdminUser>, ApiError> { |
| 96 | let name = body.name.trim().to_string(); |
| 97 | validate_account_name(&name)?; |
| 98 | validate_password(&body.password)?; |
| 99 | // Rooms and resources share the name space. |
| 100 | if state.db.name_taken(&name).await? { |
| 101 | return Err(ApiError::localized( |
| 102 | StatusCode::CONFLICT, |
| 103 | "a user with that name already exists", |
| 104 | "err_user_exists", |
| 105 | )); |
| 106 | } |
| 107 | let roots = validate_roots(&state, &body.roots).await?; |
| 108 | |
| 109 | let pass_hash = hash_password(&body.password).await?; |
| 110 | let user = state |
| 111 | .db |
| 112 | .create_user(&name, &pass_hash, body.is_admin, &roots) |
| 113 | .await?; |
| 114 | let roots = state.db.user_roots(user.id).await?; |
| 115 | Ok(Json(admin_user(&state, &user, &roots))) |
| 116 | } |
| 117 | |
| 118 | /// PUT /api/admin/users/{id} — update a user (password / is_admin / active / |
| 119 | /// roots; all optional). |
| 120 | pub async fn update_user( |
| 121 | State(state): State<Arc<AppState>>, |
| 122 | admin: AdminGuard, |
| 123 | AxumPath(id): AxumPath<i64>, |
| 124 | Json(body): Json<UpdateUser>, |
| 125 | ) -> Result<Json<AdminUser>, ApiError> { |
| 126 | let target = state.db.find_user_by_id(id).await?.ok_or_else(|| { |
| 127 | ApiError::localized( |
| 128 | StatusCode::NOT_FOUND, |
| 129 | "user not found", |
| 130 | "err_user_not_found", |
| 131 | ) |
| 132 | })?; |
| 133 | |
| 134 | // Lockout guards: an admin cannot demote, disable, or delete themselves. |
| 135 | if id == admin.user.id { |
| 136 | if body.is_admin == Some(false) { |
| 137 | return Err(ApiError::localized( |
| 138 | StatusCode::BAD_REQUEST, |
| 139 | "you cannot remove your own admin rights", |
| 140 | "err_own_admin", |
| 141 | )); |
| 142 | } |
| 143 | if body.active == Some(false) { |
| 144 | return Err(ApiError::localized( |
| 145 | StatusCode::BAD_REQUEST, |
| 146 | "you cannot disable your own account", |
| 147 | "err_own_account", |
| 148 | )); |
| 149 | } |
| 150 | } |
| 151 | // Never allow dropping to zero active admins. |
| 152 | let demoting = id != admin.user.id && body.is_admin == Some(false) && target.is_admin; |
| 153 | let disabling = |
| 154 | id != admin.user.id && body.active == Some(false) && target.active && target.is_admin; |
| 155 | if (demoting || disabling) && state.db.count_admins().await? <= 1 { |
| 156 | return Err(ApiError::localized( |
| 157 | StatusCode::BAD_REQUEST, |
| 158 | "cannot remove the last active admin", |
| 159 | "err_last_admin", |
| 160 | )); |
| 161 | } |
| 162 | |
| 163 | let hash = match &body.password { |
| 164 | Some(pw) => { |
| 165 | validate_password(pw)?; |
| 166 | Some(hash_password(pw).await?) |
| 167 | } |
| 168 | None => None, |
| 169 | }; |
| 170 | let pairs = match &body.roots { |
| 171 | Some(roots) => Some(validate_roots(&state, roots).await?), |
| 172 | None => None, |
| 173 | }; |
| 174 | state |
| 175 | .db |
| 176 | .update_user( |
| 177 | id, |
| 178 | hash.as_deref(), |
| 179 | body.is_admin, |
| 180 | body.active, |
| 181 | pairs.as_deref(), |
| 182 | ) |
| 183 | .await?; |
| 184 | crate::auth::forget_verified(); |
| 185 | |
| 186 | let updated = state.db.find_user_by_id(id).await?.ok_or_else(|| { |
| 187 | ApiError::localized( |
| 188 | StatusCode::NOT_FOUND, |
| 189 | "user not found", |
| 190 | "err_user_not_found", |
| 191 | ) |
| 192 | })?; |
| 193 | let roots = state.db.user_roots(updated.id).await?; |
| 194 | Ok(Json(admin_user(&state, &updated, &roots))) |
| 195 | } |
| 196 | |
| 197 | /// DELETE /api/admin/users/{id} — delete a user (not yourself). |
| 198 | pub async fn delete_user( |
| 199 | State(state): State<Arc<AppState>>, |
| 200 | admin: AdminGuard, |
| 201 | AxumPath(id): AxumPath<i64>, |
| 202 | ) -> Result<Json<OkResp>, ApiError> { |
| 203 | if id == admin.user.id { |
| 204 | return Err(ApiError::localized( |
| 205 | StatusCode::BAD_REQUEST, |
| 206 | "you cannot delete your own account", |
| 207 | "err_own_delete", |
| 208 | )); |
| 209 | } |
| 210 | let target = state.db.find_user_by_id(id).await?.ok_or_else(|| { |
| 211 | ApiError::localized( |
| 212 | StatusCode::NOT_FOUND, |
| 213 | "user not found", |
| 214 | "err_user_not_found", |
| 215 | ) |
| 216 | })?; |
| 217 | if target.is_admin && target.active && state.db.count_admins().await? <= 1 { |
| 218 | return Err(ApiError::localized( |
| 219 | StatusCode::BAD_REQUEST, |
| 220 | "cannot delete the last active admin", |
| 221 | "err_last_admin_delete", |
| 222 | )); |
| 223 | } |
| 224 | crate::auth::forget_verified(); |
| 225 | let _lock = pim_schedule::LOCK.lock().await; |
| 226 | let pid = state.db.principal_of(id).await?; |
| 227 | let ops = match state.db.pim_principal_by_id(pid).await? { |
| 228 | Some(p) => pim_schedule::forget(&state, &p).await?, |
| 229 | None => Vec::new(), |
| 230 | }; |
| 231 | if !state.db.delete_user(id, &ops).await? { |
| 232 | return Err(ApiError::localized( |
| 233 | StatusCode::NOT_FOUND, |
| 234 | "user not found", |
| 235 | "err_user_not_found", |
| 236 | )); |
| 237 | } |
| 238 | Ok(Json(OkResp {})) |
| 239 | } |
| 240 | |
| 241 | // --------------------------------------------------------------------------- |
| 242 | // Shares |
| 243 | // --------------------------------------------------------------------------- |
| 244 | |
| 245 | /// GET /api/admin/shares — every share on the server with its creator. |
| 246 | /// |
| 247 | /// Answers with the full share tokens, which the admin view offers as copy |
| 248 | /// buttons. A token is access, so this route stays admin-only. |
| 249 | pub async fn list_shares( |
| 250 | State(state): State<Arc<AppState>>, |
| 251 | _admin: AdminGuard, |
| 252 | ) -> Result<Json<Vec<AdminShare>>, ApiError> { |
| 253 | let rows = state.db.all_shares_with_creators().await?; |
| 254 | Ok(Json( |
| 255 | rows.iter() |
| 256 | .map(|r| AdminShare { |
| 257 | share: shares::share_info(&r.share, &state), |
| 258 | creator_id: r.share.creator_id, |
| 259 | creator_name: r.creator_name.clone(), |
| 260 | creator_active: r.creator_active, |
| 261 | }) |
| 262 | .collect(), |
| 263 | )) |
| 264 | } |
| 265 | |
| 266 | /// DELETE /api/admin/shares/{id} — revoke a share whoever created it. The |
| 267 | /// user-facing `DELETE /api/shares/{id}` only touches the caller's own links. |
| 268 | pub async fn delete_share( |
| 269 | State(state): State<Arc<AppState>>, |
| 270 | _admin: AdminGuard, |
| 271 | AxumPath(id): AxumPath<i64>, |
| 272 | ) -> Result<Json<OkResp>, ApiError> { |
| 273 | if !state.db.admin_delete_share(id).await? { |
| 274 | return Err(ApiError::localized( |
| 275 | StatusCode::NOT_FOUND, |
| 276 | "share not found", |
| 277 | "err_share_not_found", |
| 278 | )); |
| 279 | } |
| 280 | Ok(Json(OkResp {})) |
| 281 | } |
| 282 | |
| 283 | /// GET {ADMIN_PIM_LINKS} — every public calendar and address book feed. |
| 284 | /// Like the share list, it carries the full tokens. |
| 285 | pub async fn list_pim_links( |
| 286 | State(state): State<Arc<AppState>>, |
| 287 | _admin: AdminGuard, |
| 288 | ) -> Result<Json<Vec<AdminPimLink>>, ApiError> { |
| 289 | let rows = state.db.all_pim_links().await?; |
| 290 | Ok(Json( |
| 291 | rows.into_iter() |
| 292 | .map(|r| AdminPimLink { |
| 293 | link: pim_api::link_info(&r.link, r.kind), |
| 294 | collection_id: r.link.collection_id, |
| 295 | collection_name: r.collection_name, |
| 296 | kind: pim_api::wire_kind(r.kind), |
| 297 | owner_id: r.owner_id, |
| 298 | owner_name: r.owner_name, |
| 299 | owner_active: r.owner_active, |
| 300 | }) |
| 301 | .collect(), |
| 302 | )) |
| 303 | } |
| 304 | |
| 305 | /// DELETE {ADMIN_PIM_LINKS}/{id} — revoke a feed whoever made it. |
| 306 | pub async fn delete_pim_link( |
| 307 | State(state): State<Arc<AppState>>, |
| 308 | _admin: AdminGuard, |
| 309 | AxumPath(id): AxumPath<i64>, |
| 310 | ) -> Result<Json<OkResp>, ApiError> { |
| 311 | if !state.db.admin_delete_pim_link(id).await? { |
| 312 | return Err(ApiError::new(StatusCode::NOT_FOUND, "link not found")); |
| 313 | } |
| 314 | Ok(Json(OkResp {})) |
| 315 | } |
| 316 | |
| 317 | // --------------------------------------------------------------------------- |
| 318 | // Rooms and resources |
| 319 | // --------------------------------------------------------------------------- |
| 320 | |
| 321 | fn room_info(p: &PimPrincipal) -> RoomInfo { |
| 322 | RoomInfo { |
| 323 | id: p.id, |
| 324 | name: p.name.clone(), |
| 325 | display_name: p.display().to_string(), |
| 326 | kind: match p.kind { |
| 327 | UserType::Resource => RoomKind::Resource, |
| 328 | _ => RoomKind::Room, |
| 329 | }, |
| 330 | url: principal_href(&p.name), |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | fn room_not_found() -> ApiError { |
| 335 | ApiError::new(StatusCode::NOT_FOUND, "room not found") |
| 336 | } |
| 337 | |
| 338 | fn room_display_name(v: &str) -> Result<String, ApiError> { |
| 339 | let v = v.trim(); |
| 340 | if v.is_empty() || v.chars().count() > 200 || v.chars().any(char::is_control) { |
| 341 | return Err(ApiError::new( |
| 342 | StatusCode::BAD_REQUEST, |
| 343 | "invalid display name", |
| 344 | )); |
| 345 | } |
| 346 | Ok(v.to_string()) |
| 347 | } |
| 348 | |
| 349 | /// GET /api/admin/rooms |
| 350 | pub async fn list_rooms( |
| 351 | State(state): State<Arc<AppState>>, |
| 352 | _admin: AdminGuard, |
| 353 | ) -> Result<Json<Vec<RoomInfo>>, ApiError> { |
| 354 | Ok(Json( |
| 355 | state.db.rooms().await?.iter().map(room_info).collect(), |
| 356 | )) |
| 357 | } |
| 358 | |
| 359 | /// POST /api/admin/rooms — a room or resource with its booking calendar. |
| 360 | pub async fn create_room( |
| 361 | State(state): State<Arc<AppState>>, |
| 362 | _admin: AdminGuard, |
| 363 | Json(body): Json<CreateRoom>, |
| 364 | ) -> Result<Json<RoomInfo>, ApiError> { |
| 365 | let name = body.name.trim().to_string(); |
| 366 | validate_account_name(&name)?; |
| 367 | let display = room_display_name(body.display_name.as_deref().unwrap_or(&name))?; |
| 368 | let kind = match body.kind { |
| 369 | RoomKind::Room => UserType::Room, |
| 370 | RoomKind::Resource => UserType::Resource, |
| 371 | }; |
| 372 | let room = state |
| 373 | .db |
| 374 | .create_room(&name, &display, kind) |
| 375 | .await? |
| 376 | .ok_or_else(|| ApiError::new(StatusCode::CONFLICT, "the name is taken"))?; |
| 377 | Ok(Json(room_info(&room))) |
| 378 | } |
| 379 | |
| 380 | /// PUT /api/admin/rooms/{id} — change the display name. The name stays: it |
| 381 | /// is the scheduling address. |
| 382 | pub async fn update_room( |
| 383 | State(state): State<Arc<AppState>>, |
| 384 | _admin: AdminGuard, |
| 385 | AxumPath(id): AxumPath<i64>, |
| 386 | Json(body): Json<UpdateRoom>, |
| 387 | ) -> Result<Json<RoomInfo>, ApiError> { |
| 388 | let display = room_display_name(&body.display_name)?; |
| 389 | if !state.db.set_room_display_name(id, &display).await? { |
| 390 | return Err(room_not_found()); |
| 391 | } |
| 392 | let rooms = state.db.rooms().await?; |
| 393 | let room = rooms |
| 394 | .iter() |
| 395 | .find(|r| r.id == id) |
| 396 | .ok_or_else(room_not_found)?; |
| 397 | Ok(Json(room_info(room))) |
| 398 | } |
| 399 | |
| 400 | /// DELETE /api/admin/rooms/{id} — with its bookings. |
| 401 | pub async fn delete_room( |
| 402 | State(state): State<Arc<AppState>>, |
| 403 | _admin: AdminGuard, |
| 404 | AxumPath(id): AxumPath<i64>, |
| 405 | ) -> Result<Json<OkResp>, ApiError> { |
| 406 | let _lock = pim_schedule::LOCK.lock().await; |
| 407 | let Some(room) = state |
| 408 | .db |
| 409 | .pim_principal_by_id(id) |
| 410 | .await? |
| 411 | .filter(|p| p.user_id.is_none()) |
| 412 | else { |
| 413 | return Err(room_not_found()); |
| 414 | }; |
| 415 | let ops = pim_schedule::forget(&state, &room).await?; |
| 416 | if !state.db.delete_room(id, &ops).await? { |
| 417 | return Err(room_not_found()); |
| 418 | } |
| 419 | Ok(Json(OkResp {})) |
| 420 | } |
| 421 | |
| 422 | /// GET /api/admin/settings |
| 423 | pub async fn get_settings( |
| 424 | State(state): State<Arc<AppState>>, |
| 425 | _admin: AdminGuard, |
| 426 | ) -> Result<Json<Settings>, ApiError> { |
| 427 | Ok(Json(Settings { |
| 428 | allow_writable_shares: state.db.allow_writable_shares().await?, |
| 429 | search_excludes: state.db.search_excludes().await?, |
| 430 | })) |
| 431 | } |
| 432 | |
| 433 | /// PUT /api/admin/settings |
| 434 | pub async fn update_settings( |
| 435 | State(state): State<Arc<AppState>>, |
| 436 | _admin: AdminGuard, |
| 437 | Json(body): Json<Settings>, |
| 438 | ) -> Result<Json<Settings>, ApiError> { |
| 439 | state |
| 440 | .db |
| 441 | .set_allow_writable_shares(body.allow_writable_shares) |
| 442 | .await?; |
| 443 | // Normalised so the search can compare plain strings. "." is dropped: |
| 444 | // excluding the root would switch search off instead of narrowing it. |
| 445 | let mut excludes: Vec<String> = Vec::new(); |
| 446 | for p in &body.search_excludes { |
| 447 | let p = p.trim().replace('\\', "/"); |
| 448 | let p = p.trim_matches('/'); |
| 449 | if p.is_empty() || p == "." || excludes.iter().any(|e| e == p) { |
| 450 | continue; |
| 451 | } |
| 452 | excludes.push(p.to_string()); |
| 453 | } |
| 454 | state.db.set_search_excludes(&excludes).await?; |
| 455 | Ok(Json(Settings { |
| 456 | allow_writable_shares: body.allow_writable_shares, |
| 457 | search_excludes: excludes, |
| 458 | })) |
| 459 | } |
| 460 |