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::localized(
62 StatusCode::FORBIDDEN,
63 "writable shares are disabled",
64 "err_rw_shares_disabled",
65 ));
66 }
67
68 let root = auth
69 .roots
70 .iter()
71 .find(|r| r.id == body.root_id)
72 .ok_or_else(|| {
73 ApiError::localized(
74 StatusCode::FORBIDDEN,
75 "no such folder",
76 "err_no_such_folder",
77 )
78 })?;
79
80 // A share must never grant more than the source root does, otherwise a
81 // read-only root could be escalated to a writable share of itself.
82 if body.writable && !root.mode.is_writable() {
83 return Err(ApiError::localized(
84 StatusCode::FORBIDDEN,
85 "this folder is read-only for you, so it cannot be shared writably",
86 "err_rw_ro_folder",
87 ));
88 }
89
90 // Resolve the target to a safe absolute path, then re-express it relative
91 // to the server root (the stored `target`).
92 let server_root = state.root.clone();
93 let root_path = root.path.clone();
94 let req = body.path.trim().to_string();
95 let req = if req.is_empty() { ".".to_string() } else { req };
96 let abs = tokio::task::spawn_blocking(move || fs::resolve_path(&server_root, &root_path, &req))
97 .await
98 .map_err(|_| {
99 ApiError::localized(
100 StatusCode::INTERNAL_SERVER_ERROR,
101 "internal error",
102 "err_internal",
103 )
104 })??;
105
106 let target = abs
107 .strip_prefix(&state.root)
108 .map(|p| p.to_string_lossy().into_owned())
109 .unwrap_or_else(|_| ".".to_string());
110 let is_file = abs.is_file();
111
112 let token = auth::share_token();
113 let mode = if body.writable { Mode::Rw } else { Mode::Ro };
114 let row = state
115 .db
116 .create_share(
117 auth.user.id,
118 &token,
119 &target,
120 is_file,
121 mode,
122 body.expires_at.as_deref(),
123 )
124 .await?;
125
126 Ok(Json(share_info(&row, &state.root)))
127}
128
129/// DELETE /api/shares/{id} — delete one of the current user's shares.
130pub async fn delete(
131 State(state): State<Arc<AppState>>,
132 auth: SessionUser,
133 AxumPath(id): AxumPath<i64>,
134) -> Result<Json<OkResp>, ApiError> {
135 if !state.db.delete_share(id, auth.user.id).await? {
136 return Err(ApiError::localized(
137 StatusCode::NOT_FOUND,
138 "share not found",
139 "err_share_not_found",
140 ));
141 }
142 Ok(Json(OkResp { ok: true }))
143}
144
145/// GET /api/share/{token} — public resolve for the share page.
146pub async fn resolve(
147 State(state): State<Arc<AppState>>,
148 AxumPath(token): AxumPath<String>,
149) -> Result<Json<ShareInfo>, ApiError> {
150 let Some(row) = state.db.share_by_token(&token).await? else {
151 return Err(ApiError::localized(
152 StatusCode::NOT_FOUND,
153 "share not found",
154 "err_share_not_found",
155 ));
156 };
157 if row.is_expired() {
158 return Err(ApiError::localized(
159 StatusCode::GONE,
160 "this share has expired",
161 "err_share_expired",
162 ));
163 }
164 let mut info = share_info(&row, &state.root);
165 // A file share opens straight into the viewer, so the client needs the
166 // file's kind up front (it cannot list a file's "contents").
167 if row.is_file {
168 let (server_root, target) = (state.root.clone(), row.target.clone());
169 info.kind = tokio::task::spawn_blocking(move || {
170 fs::resolve_file(&server_root, &target)
171 .ok()
172 .map(|p| fs::detect_kind(&p, false))
173 })
174 .await
175 .ok()
176 .flatten();
177 }
178 Ok(Json(info))
179}
180