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