shares.rs
⎇
Raw
1//! Share management (milestone 6).
2//!
3//! Session-authenticated (management; a share token is never enough — see
4//! [`SessionUser`]):
5//! - `GET /api/shares` — list the current user's shares
6//! - `POST /api/shares` — create a share
7//! - `DELETE /api/shares/{id}` — delete one of the current user's shares
8//!
9//! Public (no login; resolved by token):
10//! - `GET /api/share/{token}` — resolve a share for the share page
11
12use std::path::Path;
13use std::sync::Arc;
14
15use api_types::{CreateShare, Mode, OkResp, ShareInfo};
16use axum::Json;
17use axum::extract::{Path as AxumPath, State};
18use axum::http::StatusCode;
19
20use crate::api::common::{SessionUser, display_name};
21use crate::auth;
22use crate::db::ShareRow;
23use crate::error::{ApiError, AppState};
24use crate::fs;
25
26/// Shared JSON shape for a share (list / create / public resolve).
27fn share_info(row: &ShareRow, server_root: &Path) -> ShareInfo {
28 ShareInfo {
29 id: row.id,
30 token: row.token.clone(),
31 name: display_name(server_root, &row.target),
32 is_file: row.is_file,
33 writable: row.mode.is_writable(),
34 target: row.target.clone(),
35 created_at: row.created_at.clone(),
36 expires_at: row.expires_at.clone(),
37 // The synthetic root id to use in file API calls.
38 root_id: row.id,
39 kind: None,
40 }
41}
42
43/// GET /api/shares — list the current user's shares.
44pub async fn list(
45 State(state): State<Arc<AppState>>,
46 auth: SessionUser,
47) -> Result<Json<Vec<ShareInfo>>, ApiError> {
48 let rows = state.db.user_shares(auth.user.id).await?;
49 Ok(Json(
50 rows.iter().map(|r| share_info(r, &state.root)).collect(),
51 ))
52}
53
54/// POST /api/shares — create a share.
55pub async fn create(
56 State(state): State<Arc<AppState>>,
57 auth: SessionUser,
58 Json(body): Json<CreateShare>,
59) -> Result<Json<ShareInfo>, ApiError> {
60 if body.writable && !state.db.allow_writable_shares().await? {
61 return Err(ApiError::new(
62 StatusCode::FORBIDDEN,
63 "writable shares are disabled",
64 ));
65 }
66
67 let root = auth
68 .roots
69 .iter()
70 .find(|r| r.id == body.root_id)
71 .ok_or_else(|| ApiError::new(StatusCode::FORBIDDEN, "no such folder"))?;
72
73 // A share must never grant more than the source root does, otherwise a
74 // read-only root could be escalated to a writable share of itself.
75 if body.writable && !root.mode.is_writable() {
76 return Err(ApiError::new(
77 StatusCode::FORBIDDEN,
78 "this folder is read-only for you, so it cannot be shared writably",
79 ));
80 }
81
82 // Resolve the target to a safe absolute path, then re-express it relative
83 // to the server root (the stored `target`).
84 let server_root = state.root.clone();
85 let root_path = root.path.clone();
86 let req = body.path.trim().to_string();
87 let req = if req.is_empty() { ".".to_string() } else { req };
88 let abs = tokio::task::spawn_blocking(move || fs::resolve_path(&server_root, &root_path, &req))
89 .await
90 .map_err(|_| ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal error"))??;
91
92 let target = abs
93 .strip_prefix(&state.root)
94 .map(|p| p.to_string_lossy().into_owned())
95 .unwrap_or_else(|_| ".".to_string());
96 let is_file = abs.is_file();
97
98 let token = auth::share_token();
99 let mode = if body.writable { Mode::Rw } else { Mode::Ro };
100 let row = state
101 .db
102 .create_share(
103 auth.user.id,
104 &token,
105 &target,
106 is_file,
107 mode,
108 body.expires_at.as_deref(),
109 )
110 .await?;
111
112 Ok(Json(share_info(&row, &state.root)))
113}
114
115/// DELETE /api/shares/{id} — delete one of the current user's shares.
116pub async fn delete(
117 State(state): State<Arc<AppState>>,
118 auth: SessionUser,
119 AxumPath(id): AxumPath<i64>,
120) -> Result<Json<OkResp>, ApiError> {
121 if !state.db.delete_share(id, auth.user.id).await? {
122 return Err(ApiError::new(StatusCode::NOT_FOUND, "share not found"));
123 }
124 Ok(Json(OkResp { ok: true }))
125}
126
127/// GET /api/share/{token} — public resolve for the share page.
128pub async fn resolve(
129 State(state): State<Arc<AppState>>,
130 AxumPath(token): AxumPath<String>,
131) -> Result<Json<ShareInfo>, ApiError> {
132 let Some(row) = state.db.share_by_token(&token).await? else {
133 return Err(ApiError::new(StatusCode::NOT_FOUND, "share not found"));
134 };
135 if row.is_expired() {
136 return Err(ApiError::new(StatusCode::GONE, "this share has expired"));
137 }
138 let mut info = share_info(&row, &state.root);
139 // A file share opens straight into the viewer, so the client needs the
140 // file's kind up front (it cannot list a file's "contents").
141 if row.is_file {
142 let (server_root, target) = (state.root.clone(), row.target.clone());
143 info.kind = tokio::task::spawn_blocking(move || {
144 fs::resolve_file(&server_root, &target)
145 .ok()
146 .map(|p| fs::detect_kind(&p, false))
147 })
148 .await
149 .ok()
150 .flatten();
151 }
152 Ok(Json(info))
153}
154