1use std::net::SocketAddr;
8
9use axum::extract::{ConnectInfo, Path, State};
10use axum::http::{header, HeaderMap, StatusCode};
11use axum::response::{IntoResponse, Response};
12use axum::Json;
13use serde::{Deserialize, Serialize};
14
15use super::{ok_seq, require_admin, require_user, Shared};
16use crate::db::now;
17use crate::model::{groups, NumberMode, PartType, Session, User};
18use crate::security::ThrottleKind;
19use crate::{auth, Error};
20
21#[derive(Debug, Serialize)]
23pub struct PublicUser {
24 pub id: String,
25 pub username: String,
26 pub display_name: String,
27 pub email: String,
28 pub groups: Vec<String>,
29 pub active: bool,
30 pub created_at: u64,
31 pub can_author: bool,
34 pub can_checkin: bool,
35 pub is_admin: bool,
36 pub can_bake: bool,
37 #[serde(skip_serializing_if = "Option::is_none")]
40 pub csrf: Option<String>,
41 #[serde(skip_serializing_if = "Option::is_none")]
43 pub via: Option<&'static str>,
44 #[serde(skip_serializing_if = "Option::is_none")]
48 pub server_version: Option<&'static str>,
49 #[serde(skip_serializing_if = "Option::is_none")]
50 pub min_client_version: Option<String>,
51 #[serde(skip_serializing_if = "Option::is_none")]
53 pub features: Option<&'static [&'static str]>,
54}
55
56impl From<&User> for PublicUser {
57 fn from(user: &User) -> Self {
58 Self {
59 id: user.id.clone(),
60 username: user.username.clone(),
61 display_name: user.display_name.clone(),
62 email: user.email.clone(),
63 groups: user.groups.clone(),
64 active: user.active,
65 created_at: user.created_at,
66 can_author: user.can_author(),
67 can_checkin: user.can_checkin(),
68 is_admin: user.is_admin(),
69 can_bake: user.can_bake(),
70 csrf: None,
71 via: None,
72 server_version: None,
73 min_client_version: None,
74 features: None,
75 }
76 }
77}
78
79#[derive(Debug, Deserialize)]
80pub struct Credentials {
81 pub username: String,
82 pub password: String,
83}
84
85pub async fn login(
94 State(db): State<Shared>,
95 headers: HeaderMap,
96 peer: Option<ConnectInfo<SocketAddr>>,
97 Json(body): Json<Credentials>,
98) -> Result<Response, Error> {
99 let security = db.security();
100 let ip = security.config.client_ip(&headers, peer.map(|ConnectInfo(addr)| addr.ip()));
101 let ip_key = ip.map(|ip| ip.to_string());
102 let username = body.username.trim().to_ascii_lowercase();
103 let t = now();
104 let locked = security
105 .throttle
106 .locked_for(ThrottleKind::User, &username, t)
107 .into_iter()
108 .chain(ip_key.as_deref().and_then(|ip| security.throttle.locked_for(ThrottleKind::Ip, ip, t)))
109 .max();
110 let failed = |db: &crate::db::Db, user_id: &str, reason: &str| {
111 let who = crate::model::EntityRef {
112 kind: "user".into(),
113 id: user_id.to_string(),
114 label: body.username.trim().to_string(),
115 part_id: String::new(),
116 };
117 db.record("sign-in-failed", who, reason);
118 };
119 if let Some(seconds) = locked {
120 failed(&db, "", "locked out by the sign-in throttle");
121 return Err(Error::too_many(format!(
122 "too many failed sign-ins — try again in {seconds} s, or ask an administrator to clear the lockout"
123 )));
124 }
125
126 let found = db.read(|state| state.user_by_name(&body.username).cloned());
127 let refusal = || {
128 security.throttle.fail(ThrottleKind::User, &username, t);
129 if let Some(ip) = &ip_key {
130 security.throttle.fail(ThrottleKind::Ip, ip, t);
131 }
132 Error::unauthorized("wrong username or password")
133 };
134
135 let user = match found {
136 Some(user) if auth::verify_password(&body.password, &user.password) => user,
137 Some(user) => {
138 failed(&db, &user.id, "wrong password");
139 return Err(refusal());
140 }
141 None => {
142 failed(&db, "", "no such username");
143 static DECOY: std::sync::OnceLock<String> = std::sync::OnceLock::new();
146 let decoy = DECOY.get_or_init(|| auth::hash_password("decoy"));
147 let _ = auth::verify_password(&body.password, decoy);
148 return Err(refusal());
149 }
150 };
151 if !user.active {
152 failed(&db, &user.id, "the account is disabled");
153 return Err(Error::forbidden("this account is disabled"));
154 }
155 security.throttle.clear(ThrottleKind::User, &username);
156
157 let token = auth::random_token(32);
158 let csrf = auth::random_token(32);
159 let session = Session {
160 token: token.clone(),
161 user_id: user.id.clone(),
162 created_at: now(),
163 last_seen: now(),
164 csrf: csrf.clone(),
165 };
166 let actor = crate::model::Actor {
169 user_id: user.id.clone(),
170 username: user.username.clone(),
171 via: "session".into(),
172 ..crate::audit::current_actor()
173 };
174 crate::audit::as_actor(actor, || {
175 db.mutate(move |state| {
176 state.sessions.push(session);
177 Ok(())
178 })
179 })?;
180 if let Err(error) = db.prune_sessions() {
183 eprintln!("brep-plm: could not remove expired sessions: {}", error.message);
184 }
185
186 let cookie = super::session_cookie(&db, &headers, &token);
187 let mut public = PublicUser::from(&user);
188 public.csrf = Some(csrf);
189 Ok((StatusCode::OK, [(header::SET_COOKIE, cookie)], Json(public)).into_response())
190}
191
192pub async fn logout(State(db): State<Shared>, headers: HeaderMap) -> Result<Response, Error> {
193 if let Some(token) = super::session_token(&headers) {
194 db.mutate(move |state| {
195 state.sessions.retain(|s| s.token != token);
196 Ok(())
197 })?;
198 }
199 let cookie = super::clear_cookie(&db, &headers);
200 Ok((StatusCode::OK, [(header::SET_COOKIE, cookie)], Json(serde_json::json!({"ok": true})))
201 .into_response())
202}
203
204pub async fn me(State(db): State<Shared>, headers: HeaderMap) -> Result<Json<PublicUser>, Error> {
207 let identity = super::identify(&db, &headers)?;
208 let mut public = PublicUser::from(&identity.user);
209 public.server_version = Some(crate::version::SERVER_VERSION);
210 public.min_client_version = Some(db.security().config.min_client_version().to_string());
211 public.features = Some(crate::version::FEATURES);
212 if let Some(token) = identity.session {
213 let csrf = db.mutate(move |state| {
214 let session = state
215 .sessions
216 .iter_mut()
217 .find(|s| s.token == token)
218 .ok_or_else(|| Error::unauthorized("session has expired"))?;
219 if session.csrf.is_empty() {
220 session.csrf = auth::random_token(32);
221 }
222 Ok(session.csrf.clone())
223 })?;
224 public.csrf = Some(csrf);
225 public.via = Some("session");
226 } else {
227 public.via = Some("token");
228 }
229 Ok(Json(public))
230}
231
232pub async fn list_users(
237 State(db): State<Shared>,
238 headers: HeaderMap,
239) -> Result<Json<Vec<PublicUser>>, Error> {
240 require_admin(&db, &headers)?;
241 Ok(Json(db.read(|state| {
242 state.users.iter().map(PublicUser::from).collect()
243 })))
244}
245
246#[derive(Debug, Deserialize)]
247pub struct NewUser {
248 pub username: String,
249 pub password: String,
250 #[serde(default)]
251 pub display_name: String,
252 #[serde(default)]
253 pub email: String,
254 #[serde(default)]
255 pub groups: Vec<String>,
256}
257
258pub async fn create_user(
259 State(db): State<Shared>,
260 headers: HeaderMap,
261 Json(body): Json<NewUser>,
262) -> Result<Response, Error> {
263 require_admin(&db, &headers)?;
264 let username = body.username.trim().to_string();
265 if username.is_empty() {
266 return Err(Error::bad_request("a user needs a username"));
267 }
268 if body.password.len() < 8 {
269 return Err(Error::bad_request("a password needs at least 8 characters"));
270 }
271 let user = User {
272 id: auth::new_id(),
273 username,
274 display_name: body.display_name.trim().to_string(),
275 email: body.email.trim().to_string(),
276 password: auth::hash_password(&body.password),
277 groups: normalize_groups(body.groups),
278 active: true,
279 created_at: now(),
280 };
281 db.mutate(move |state| {
282 if state.user_by_name(&user.username).is_some() {
283 return Err(Error::conflict(format!(
284 "username '{}' is taken",
285 user.username
286 )));
287 }
288 state.users.push(user);
289 Ok(())
290 })?;
291 Ok(ok_seq(&db))
292}
293
294#[derive(Debug, Deserialize)]
295pub struct UserPatch {
296 pub display_name: Option<String>,
297 pub email: Option<String>,
298 pub groups: Option<Vec<String>>,
299 pub active: Option<bool>,
300 pub password: Option<String>,
301}
302
303pub async fn update_user(
304 State(db): State<Shared>,
305 headers: HeaderMap,
306 Path(id): Path<String>,
307 Json(body): Json<UserPatch>,
308) -> Result<Response, Error> {
309 let actor = require_admin(&db, &headers)?;
310 if let Some(password) = &body.password {
311 if password.len() < 8 {
312 return Err(Error::bad_request("a password needs at least 8 characters"));
313 }
314 }
315 let mut reset_for: Option<String> = None;
316 let reset = &mut reset_for;
317 db.mutate(move |state| {
318 let reset_for = reset;
319 let losing_admin = body.active == Some(false)
323 || body
324 .groups
325 .as_ref()
326 .is_some_and(|g| !g.iter().any(|name| name == groups::ADMIN));
327 if id == actor.id && losing_admin {
328 return Err(Error::conflict(
329 "an administrator cannot remove their own admin access".to_string(),
330 ));
331 }
332 let user = state
333 .users
334 .iter_mut()
335 .find(|u| u.id == id)
336 .ok_or_else(|| Error::not_found("user"))?;
337 if let Some(name) = body.display_name {
338 user.display_name = name.trim().to_string();
339 }
340 if let Some(email) = body.email {
341 user.email = email.trim().to_string();
342 }
343 if let Some(list) = body.groups {
344 user.groups = normalize_groups(list);
345 }
346 if let Some(active) = body.active {
347 user.active = active;
348 }
349 if let Some(password) = body.password {
350 user.password = auth::hash_password(&password);
351 *reset_for = Some(user.username.clone());
352 let user_id = user.id.clone();
354 state.sessions.retain(|s| s.user_id != user_id);
355 }
356 Ok(())
357 })?;
358 if let Some(username) = reset_for {
360 db.security().throttle.clear(ThrottleKind::User, &username);
361 }
362 Ok(ok_seq(&db))
363}
364
365fn normalize_groups(list: Vec<String>) -> Vec<String> {
368 let mut out: Vec<String> = Vec::new();
369 for name in list {
370 let name = name.trim().to_ascii_lowercase();
371 if !name.is_empty() && !out.contains(&name) {
372 out.push(name);
373 }
374 }
375 out
376}
377
378pub async fn list_part_types(
383 State(db): State<Shared>,
384 headers: HeaderMap,
385) -> Result<Json<Vec<PartTypeView>>, Error> {
386 require_user(&db, &headers)?;
387 Ok(Json(db.read(|state| {
388 state.part_types.iter().map(PartTypeView::from).collect()
389 })))
390}
391
392#[derive(Debug, Serialize)]
395pub struct PartTypeView {
396 pub id: String,
397 pub name: String,
398 pub prefix: String,
399 pub digits: u32,
400 pub next: u64,
401 pub next_number: String,
404 pub capacity: u64,
405 pub mode: NumberMode,
406}
407
408impl From<&PartType> for PartTypeView {
409 fn from(kind: &PartType) -> Self {
410 Self {
411 id: kind.id.clone(),
412 name: kind.name.clone(),
413 prefix: kind.prefix.clone(),
414 digits: kind.digits,
415 next: kind.next,
416 next_number: kind.format_number(kind.next),
417 capacity: kind.capacity(),
418 mode: kind.mode.clone(),
419 }
420 }
421}
422
423#[derive(Debug, Deserialize)]
424pub struct NewPartType {
425 pub id: String,
426 pub name: String,
427 #[serde(default)]
429 pub prefix: String,
430 #[serde(default = "nine")]
431 pub digits: u32,
432 #[serde(default)]
433 pub start: Option<u64>,
434 #[serde(default)]
437 pub mode: NumberMode,
438}
439
440fn nine() -> u32 {
441 9
442}
443
444fn check_mode(db: &crate::db::Db, mode: &NumberMode) -> Result<(), Error> {
448 match mode {
449 NumberMode::Counter | NumberMode::Free => Ok(()),
450 NumberMode::Pattern { regex } => {
451 if regex.trim().is_empty() {
452 return Err(Error::bad_request("a pattern type needs a pattern"));
453 }
454 crate::db::full_match(regex).map(|_| ())
455 }
456 NumberMode::Script { script } => db.scripts().resolve(script).map(|_| ()),
457 }
458}
459
460fn prefix_clash<'a>(state: &'a crate::db::State, kind: &PartType) -> Option<&'a PartType> {
464 if kind.mode != NumberMode::Counter {
465 return None;
466 }
467 state.part_types.iter().find(|t| {
468 t.id != kind.id && t.mode == NumberMode::Counter && t.prefix.eq_ignore_ascii_case(&kind.prefix)
469 })
470}
471
472pub async fn create_part_type(
473 State(db): State<Shared>,
474 headers: HeaderMap,
475 Json(body): Json<NewPartType>,
476) -> Result<Response, Error> {
477 require_admin(&db, &headers)?;
478 let id = body.id.trim().to_ascii_lowercase();
479 if id.is_empty() || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
480 return Err(Error::bad_request(
481 "a part type id is letters, digits, '-' and '_'",
482 ));
483 }
484 if !(1..=18).contains(&body.digits) {
487 return Err(Error::bad_request("digits must be between 1 and 18"));
488 }
489 let kind = PartType {
490 id,
491 name: body.name.trim().to_string(),
492 prefix: body.prefix.trim().to_string(),
493 digits: body.digits,
494 next: body.start.unwrap_or(1).max(1),
495 created_at: now(),
496 mode: body.mode,
497 };
498 check_mode(&db, &kind.mode)?;
499 if kind.name.is_empty() {
500 return Err(Error::bad_request("a part type needs a name"));
501 }
502 if kind.next > kind.capacity() {
503 return Err(Error::bad_request(format!(
504 "a start of {} does not fit in {} digits",
505 kind.next, kind.digits
506 )));
507 }
508 db.mutate(move |state| {
509 if state.part_type(&kind.id).is_some() {
510 return Err(Error::conflict(format!("part type '{}' exists", kind.id)));
511 }
512 if let Some(clash) = prefix_clash(state, &kind) {
513 return Err(Error::conflict(format!(
514 "prefix '{}' is already used by part type '{}'",
515 kind.prefix, clash.id
516 )));
517 }
518 state.part_types.push(kind);
519 Ok(())
520 })?;
521 Ok(ok_seq(&db))
522}
523
524#[derive(Debug, Deserialize)]
525pub struct PartTypeChange {
526 #[serde(default)]
527 pub name: Option<String>,
528 #[serde(default)]
529 pub mode: Option<NumberMode>,
530}
531
532pub async fn update_part_type(
535 State(db): State<Shared>,
536 headers: HeaderMap,
537 Path(id): Path<String>,
538 Json(body): Json<PartTypeChange>,
539) -> Result<Response, Error> {
540 require_admin(&db, &headers)?;
541 if let Some(mode) = &body.mode {
542 check_mode(&db, mode)?;
543 }
544 db.mutate(move |state| {
545 let index = state
546 .part_types
547 .iter()
548 .position(|t| t.id == id)
549 .ok_or_else(|| Error::not_found("part type"))?;
550 let mut kind = state.part_types[index].clone();
551 if let Some(name) = body.name {
552 let name = name.trim().to_string();
553 if name.is_empty() {
554 return Err(Error::bad_request("a part type needs a name"));
555 }
556 kind.name = name;
557 }
558 if let Some(mode) = body.mode {
559 kind.mode = mode;
560 }
561 if let Some(clash) = prefix_clash(state, &kind) {
562 return Err(Error::conflict(format!(
563 "prefix '{}' is already used by counter type '{}'",
564 kind.prefix, clash.id
565 )));
566 }
567 state.part_types[index] = kind;
568 Ok(())
569 })?;
570 Ok(ok_seq(&db))
571}