admin.rs
⎇
Raw
1//! Admin API (milestone 7): user management and server settings.
2//! All routes require an admin session (via [`AdminUser`]).
3
4use std::sync::Arc;
5
6use api_types::{
7 AdminPimLink, AdminShare, AdminUser, CreateRoom, CreateUser, Mode, OkResp, RoomInfo, RoomKind,
8 Root, Settings, UpdateRoom, UpdateUser,
9};
10use axum::Json;
11use axum::extract::{Path as AxumPath, State};
12use axum::http::StatusCode;
13
14use crate::api::common::AdminUser as AdminGuard;
15use crate::api::common::{
16 blocking, hash_password, root_info, validate_account_name, validate_password,
17};
18use crate::api::pim::principal_href;
19use crate::api::shares;
20use crate::api::{pim_api, pim_schedule};
21use crate::db::{PimPrincipal, RootRow, UserType};
22use crate::error::{ApiError, AppState};
23use crate::fs;
24
25// ---------------------------------------------------------------------------
26// Helpers
27// ---------------------------------------------------------------------------
28
29fn 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.
44async 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.
76pub 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.
91pub 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).
120pub 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).
198pub 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.
249pub 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.
268pub 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.
285pub 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.pim_links_with_owner(None).await?;
290 Ok(Json(rows.into_iter().map(pim_api::feed_entry).collect()))
291}
292
293/// DELETE {ADMIN_PIM_LINKS}/{id} — revoke a feed whoever made it.
294pub async fn delete_pim_link(
295 State(state): State<Arc<AppState>>,
296 _admin: AdminGuard,
297 AxumPath(id): AxumPath<i64>,
298) -> Result<Json<OkResp>, ApiError> {
299 if !state.db.admin_delete_pim_link(id).await? {
300 return Err(ApiError::new(StatusCode::NOT_FOUND, "link not found"));
301 }
302 Ok(Json(OkResp {}))
303}
304
305// ---------------------------------------------------------------------------
306// Rooms and resources
307// ---------------------------------------------------------------------------
308
309fn room_info(p: &PimPrincipal) -> RoomInfo {
310 RoomInfo {
311 id: p.id,
312 name: p.name.clone(),
313 display_name: p.display().to_string(),
314 kind: match p.kind {
315 UserType::Resource => RoomKind::Resource,
316 _ => RoomKind::Room,
317 },
318 url: principal_href(&p.name),
319 }
320}
321
322fn room_not_found() -> ApiError {
323 ApiError::new(StatusCode::NOT_FOUND, "room not found")
324}
325
326fn room_display_name(v: &str) -> Result<String, ApiError> {
327 let v = v.trim();
328 if v.is_empty() || v.chars().count() > 200 || v.chars().any(char::is_control) {
329 return Err(ApiError::new(
330 StatusCode::BAD_REQUEST,
331 "invalid display name",
332 ));
333 }
334 Ok(v.to_string())
335}
336
337/// GET /api/admin/rooms
338pub async fn list_rooms(
339 State(state): State<Arc<AppState>>,
340 _admin: AdminGuard,
341) -> Result<Json<Vec<RoomInfo>>, ApiError> {
342 Ok(Json(
343 state.db.rooms().await?.iter().map(room_info).collect(),
344 ))
345}
346
347/// POST /api/admin/rooms — a room or resource with its booking calendar.
348pub async fn create_room(
349 State(state): State<Arc<AppState>>,
350 _admin: AdminGuard,
351 Json(body): Json<CreateRoom>,
352) -> Result<Json<RoomInfo>, ApiError> {
353 let name = body.name.trim().to_string();
354 validate_account_name(&name)?;
355 let display = room_display_name(body.display_name.as_deref().unwrap_or(&name))?;
356 let kind = match body.kind {
357 RoomKind::Room => UserType::Room,
358 RoomKind::Resource => UserType::Resource,
359 };
360 let room = state
361 .db
362 .create_room(&name, &display, kind)
363 .await?
364 .ok_or_else(|| ApiError::new(StatusCode::CONFLICT, "the name is taken"))?;
365 Ok(Json(room_info(&room)))
366}
367
368/// PUT /api/admin/rooms/{id} — change the display name. The name stays: it
369/// is the scheduling address.
370pub async fn update_room(
371 State(state): State<Arc<AppState>>,
372 _admin: AdminGuard,
373 AxumPath(id): AxumPath<i64>,
374 Json(body): Json<UpdateRoom>,
375) -> Result<Json<RoomInfo>, ApiError> {
376 let display = room_display_name(&body.display_name)?;
377 if !state.db.set_room_display_name(id, &display).await? {
378 return Err(room_not_found());
379 }
380 let rooms = state.db.rooms().await?;
381 let room = rooms
382 .iter()
383 .find(|r| r.id == id)
384 .ok_or_else(room_not_found)?;
385 Ok(Json(room_info(room)))
386}
387
388/// DELETE /api/admin/rooms/{id} — with its bookings.
389pub async fn delete_room(
390 State(state): State<Arc<AppState>>,
391 _admin: AdminGuard,
392 AxumPath(id): AxumPath<i64>,
393) -> Result<Json<OkResp>, ApiError> {
394 let _lock = pim_schedule::LOCK.lock().await;
395 let Some(room) = state
396 .db
397 .pim_principal_by_id(id)
398 .await?
399 .filter(|p| p.user_id.is_none())
400 else {
401 return Err(room_not_found());
402 };
403 let ops = pim_schedule::forget(&state, &room).await?;
404 if !state.db.delete_room(id, &ops).await? {
405 return Err(room_not_found());
406 }
407 Ok(Json(OkResp {}))
408}
409
410/// GET /api/admin/settings
411pub async fn get_settings(
412 State(state): State<Arc<AppState>>,
413 _admin: AdminGuard,
414) -> Result<Json<Settings>, ApiError> {
415 Ok(Json(Settings {
416 allow_writable_shares: state.db.allow_writable_shares().await?,
417 search_excludes: state.db.search_excludes().await?,
418 }))
419}
420
421/// PUT /api/admin/settings
422pub async fn update_settings(
423 State(state): State<Arc<AppState>>,
424 _admin: AdminGuard,
425 Json(body): Json<Settings>,
426) -> Result<Json<Settings>, ApiError> {
427 state
428 .db
429 .set_allow_writable_shares(body.allow_writable_shares)
430 .await?;
431 // Normalised so the search can compare plain strings. "." is dropped:
432 // excluding the root would switch search off instead of narrowing it.
433 let mut excludes: Vec<String> = Vec::new();
434 for p in &body.search_excludes {
435 let p = p.trim().replace('\\', "/");
436 let p = p.trim_matches('/');
437 if p.is_empty() || p == "." || excludes.iter().any(|e| e == p) {
438 continue;
439 }
440 excludes.push(p.to_string());
441 }
442 state.db.set_search_excludes(&excludes).await?;
443 Ok(Json(Settings {
444 allow_writable_shares: body.allow_writable_shares,
445 search_excludes: excludes,
446 }))
447}
448