auth.rs
⎇
Raw
1use std::sync::Arc;
2
3use api_types::{Credentials, Me, OkResp, RootInfo, UserInfo};
4use axum::Json;
5use axum::extract::State;
6use axum::http::{HeaderMap, StatusCode, header};
7use axum::response::{IntoResponse, Response};
8use serde::Deserialize;
9
10use crate::api::common::{
11 SessionUser, display_name, hash_password, session_auth, validate_account_name,
12 validate_password,
13};
14use crate::auth::{self, clear_session_cookie, parse_session_cookie, session_cookie};
15use crate::db::{RootRow, User};
16use crate::error::{ApiError, AppState};
17
18/// GET /api/auth/me
19///
20/// - No users at all → `200 {"first_boot": true}`
21/// - No/invalid session → `401`
22/// - Valid session → user info + visible roots
23pub async fn me(
24 State(state): State<Arc<AppState>>,
25 headers: HeaderMap,
26) -> Result<Json<Me>, ApiError> {
27 if state.db.user_count().await? == 0 {
28 return Ok(Json(Me {
29 first_boot: true,
30 user: None,
31 roots: Vec::new(),
32 allow_writable_shares: false,
33 thumbnails_available: state.thumbs.is_some(),
34 public_url: state.public_url.clone(),
35 }));
36 }
37
38 let (user, roots) = session_auth(&headers, &state).await?;
39 Ok(Json(me_for(&state, &user, roots).await?))
40}
41
42/// Build the `/api/auth/me` payload for an authenticated user.
43async fn me_for(state: &AppState, user: &User, roots: Vec<RootRow>) -> Result<Me, ApiError> {
44 let roots: Vec<RootInfo> = roots
45 .into_iter()
46 .map(|r| RootInfo {
47 id: r.id,
48 name: display_name(state, &r.path),
49 path: r.path,
50 mode: r.mode,
51 })
52 .collect();
53
54 Ok(Me {
55 first_boot: false,
56 user: Some(UserInfo {
57 id: user.id,
58 name: user.name.clone(),
59 is_admin: user.is_admin,
60 single_click_open: user.single_click,
61 thumbnails: user.thumbnails,
62 language: user.language.clone(),
63 }),
64 roots,
65 allow_writable_shares: state.db.allow_writable_shares().await?,
66 thumbnails_available: state.thumbs.is_some(),
67 public_url: state.public_url.clone(),
68 })
69}
70
71/// PUT /api/auth/me
72///
73/// Update the signed-in user's profile settings. Each field is optional;
74/// omitted fields are left untouched. Returns the fresh `/me` payload so
75/// clients can apply the change immediately.
76#[derive(Deserialize)]
77pub(crate) struct ProfilePatch {
78 #[serde(default)]
79 pub single_click_open: Option<bool>,
80 pub thumbnails: Option<bool>,
81 #[serde(default, deserialize_with = "language_field")]
82 pub language: Option<Option<String>>,
83}
84
85/// Deserializes `ProfilePatch::language` into the three-state patch value:
86/// `"de"` → `Some(Some("de"))`, `null` → `Some(None)` (a missing field
87/// never calls this and stays `None` via `#[serde(default)]`). The inner
88/// `Option<String>` already maps `null` → `None` and `"de"` → `Some`, so
89/// only the outer wrap is custom.
90fn language_field<'de, D>(deserializer: D) -> Result<Option<Option<String>>, D::Error>
91where
92 D: serde::Deserializer<'de>,
93{
94 serde::Deserialize::deserialize(deserializer).map(Some)
95}
96
97/// A language tag we are willing to store: short, ASCII letters/digits and
98/// `-`/`_` (BCP-47 style). Checked at the trust boundary so a raw API
99/// client cannot write arbitrary blobs into the DB.
100fn valid_language(tag: &str) -> bool {
101 !tag.is_empty()
102 && tag.len() <= 12
103 && tag
104 .bytes()
105 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
106}
107
108pub async fn update_profile(
109 State(state): State<Arc<AppState>>,
110 SessionUser { mut user, roots }: SessionUser,
111 Json(body): Json<ProfilePatch>,
112) -> Result<Json<Me>, ApiError> {
113 if let Some(Some(ref tag)) = body.language
114 && !valid_language(tag)
115 {
116 return Err(ApiError::localized(
117 StatusCode::BAD_REQUEST,
118 "invalid language tag",
119 "err_invalid_language",
120 ));
121 }
122 if let Some(v) = body.single_click_open {
123 state.db.set_user_single_click(user.id, v).await?;
124 user.single_click = v;
125 }
126 if let Some(v) = body.thumbnails {
127 state.db.set_user_thumbnails(user.id, v).await?;
128 user.thumbnails = v;
129 }
130 if let Some(lang) = body.language {
131 state.db.set_user_language(user.id, lang.as_deref()).await?;
132 user.language = lang;
133 }
134 Ok(Json(me_for(&state, &user, roots).await?))
135}
136
137fn already_set_up() -> ApiError {
138 ApiError::localized(
139 StatusCode::CONFLICT,
140 "server is already set up",
141 "err_already_set_up",
142 )
143}
144
145/// POST /api/auth/setup — create the first admin account.
146/// Only available while no users exist.
147pub async fn setup(
148 State(state): State<Arc<AppState>>,
149 Json(body): Json<Credentials>,
150) -> Result<Response, ApiError> {
151 let name = body.name.trim();
152 validate_account_name(name)?;
153 validate_password(&body.password)?;
154 // A cheap pre-check: it keeps a POST to an already-configured server from
155 // paying for an Argon2 hash. `create_admin` re-checks atomically.
156 if state.db.user_count().await? > 0 {
157 return Err(already_set_up());
158 }
159
160 let pass_hash = hash_password(&body.password).await?;
161 // `None` = another setup request won the race between the check above and
162 // this insert.
163 let Some(user) = state.db.create_admin(name, &pass_hash).await? else {
164 return Err(already_set_up());
165 };
166
167 let token = auth::random_token();
168 state.db.create_session(user.id, &token).await?;
169
170 let mut res = Json(OkResp {}).into_response();
171 res.headers_mut().insert(
172 header::SET_COOKIE,
173 session_cookie(&token, state.https).parse().unwrap(),
174 );
175 Ok(res)
176}
177
178/// POST /api/auth/login
179pub async fn login(
180 State(state): State<Arc<AppState>>,
181 Json(body): Json<Credentials>,
182) -> Result<Response, ApiError> {
183 // Online guessing gets slower per failed attempt on this name.
184 let delay = auth::login_delay(&body.name);
185 if !delay.is_zero() {
186 tokio::time::sleep(delay).await;
187 }
188 let verified = state.db.verify_password(&body.name, &body.password).await?;
189 auth::record_login(&body.name, verified.is_some());
190 let Some(user) = verified else {
191 return Err(ApiError::localized(
192 StatusCode::UNAUTHORIZED,
193 "invalid name or password",
194 "err_invalid_credentials",
195 ));
196 };
197
198 let token = auth::random_token();
199 state.db.create_session(user.id, &token).await?;
200
201 let mut res = Json(OkResp {}).into_response();
202 res.headers_mut().insert(
203 header::SET_COOKIE,
204 session_cookie(&token, state.https).parse().unwrap(),
205 );
206 Ok(res)
207}
208
209/// POST /api/auth/logout
210pub async fn logout(State(state): State<Arc<AppState>>, headers: HeaderMap) -> Response {
211 if let Some(token) = parse_session_cookie(&headers) {
212 let _ = state.db.delete_session(&token).await;
213 }
214 let mut res = Json(OkResp {}).into_response();
215 res.headers_mut().insert(
216 header::SET_COOKIE,
217 clear_session_cookie(state.https).parse().unwrap(),
218 );
219 res
220}
221