1use axum::{
14 Json,
15 extract::{Path, State},
16 http::StatusCode,
17 response::IntoResponse,
18};
19use chrono::{DateTime, Utc};
20use serde::{Deserialize, Serialize};
21use uuid::Uuid;
22
23use crate::{app::AppState, auth::hash_token, error::ApiError, login::CurrentUser, model::UserRole, session};
24
25const MIN_PASSWORD_LENGTH: usize = 8;
31
32#[derive(Debug, Serialize, sqlx::FromRow)]
34pub struct UserRow {
35 pub id: Uuid,
36 pub email: String,
37 pub display_name: String,
38 pub role: UserRole,
39 pub active: bool,
40 pub has_password: bool,
44 pub agents: i64,
46 pub last_seen_at: Option<DateTime<Utc>>,
48 pub department_id: Option<Uuid>,
49 pub department: Option<String>,
52 pub created_at: DateTime<Utc>,
53}
54
55#[derive(Debug, Deserialize)]
56pub struct NewUser {
57 pub email: String,
58 pub display_name: Option<String>,
59 #[serde(default = "default_role")]
60 pub role: UserRole,
61 pub password: Option<String>,
64}
65
66fn default_role() -> UserRole {
67 UserRole::Employee
68}
69
70#[derive(Debug, Deserialize)]
73pub struct UserPatch {
74 pub display_name: Option<String>,
75 pub role: Option<UserRole>,
76 pub active: Option<bool>,
77 pub password: Option<String>,
81}
82
83#[derive(Debug, Serialize, sqlx::FromRow)]
85pub struct AgentRow {
86 pub id: Uuid,
87 pub name: String,
88 pub revoked_at: Option<DateTime<Utc>>,
89 pub last_seen_at: Option<DateTime<Utc>>,
90 pub created_at: DateTime<Utc>,
91}
92
93#[derive(Debug, Deserialize)]
94pub struct NewAgent {
95 pub name: String,
97}
98
99#[derive(Debug, Serialize)]
101pub struct IssuedAgent {
102 pub id: Uuid,
103 pub name: String,
104 pub token: String,
105 pub notice: &'static str,
108}
109
110pub async fn list_users(State(state): State<AppState>, user: CurrentUser) -> Result<impl IntoResponse, ApiError> {
120 require_manager_or_admin(&user)?;
121
122 let users: Vec<UserRow> = sqlx::query_as(
123 "SELECT u.id, u.email, u.display_name, u.role, u.active,
124 (u.password_hash IS NOT NULL) AS has_password,
125 (SELECT count(*) FROM agents a WHERE a.user_id = u.id AND a.revoked_at IS NULL) AS agents,
126 (SELECT max(a.last_seen_at) FROM agents a WHERE a.user_id = u.id) AS last_seen_at,
127 u.department_id,
128 d.name AS department,
129 u.created_at
130 FROM users u
131 LEFT JOIN departments d ON d.id = u.department_id
132 WHERE $1
133 OR u.id = $2
134 OR u.department_id IN (SELECT id FROM departments WHERE manager_id = $2)
135 ORDER BY u.display_name, u.email",
136 )
137 .bind(user.role == UserRole::Admin)
138 .bind(user.user_id)
139 .fetch_all(&state.pool)
140 .await?;
141
142 Ok(Json(users))
143}
144
145pub async fn create_user(State(state): State<AppState>, user: CurrentUser, Json(new): Json<NewUser>) -> Result<impl IntoResponse, ApiError> {
147 user.require_admin()?;
148
149 let email = new.email.trim();
150 if !looks_like_an_email(email) {
151 return Err(ApiError::bad_request("that does not look like an email address"));
152 }
153 let password_hash = match new.password.as_deref() {
154 Some(password) => Some(hash_new_password(password)?),
155 None => None,
156 };
157 let display_name = new
160 .display_name
161 .as_deref()
162 .map(str::trim)
163 .filter(|name| !name.is_empty())
164 .unwrap_or_else(|| email.split('@').next().unwrap_or(email));
165
166 let created: Result<Uuid, sqlx::Error> =
167 sqlx::query_scalar("INSERT INTO users (email, display_name, role, password_hash) VALUES ($1, $2, $3, $4) RETURNING id")
168 .bind(email)
169 .bind(display_name)
170 .bind(new.role)
171 .bind(password_hash.as_deref())
172 .fetch_one(&state.pool)
173 .await;
174
175 let id = match created {
176 Ok(id) => id,
177 Err(sqlx::Error::Database(error)) if error.is_unique_violation() => {
181 return Err(ApiError::new(StatusCode::CONFLICT, "someone with that email address already exists"));
182 }
183 Err(error) => return Err(error.into()),
184 };
185
186 tracing::info!(%id, by = %user.user_id, "created a user");
187 Ok((StatusCode::CREATED, Json(serde_json::json!({"id": id}))))
188}
189
190pub async fn update_user(
192 State(state): State<AppState>,
193 user: CurrentUser,
194 Path(target): Path<Uuid>,
195 Json(patch): Json<UserPatch>,
196) -> Result<impl IntoResponse, ApiError> {
197 user.require_admin()?;
198
199 let losing_admin = patch.role.is_some_and(|role| role != UserRole::Admin) || patch.active == Some(false);
204 if losing_admin && is_last_admin(&state.pool, target).await? {
205 return Err(ApiError::new(
206 StatusCode::CONFLICT,
207 "this is the only administrator; promote someone else first",
208 ));
209 }
210
211 let password_hash = match patch.password.as_deref() {
212 Some(password) => Some(hash_new_password(password)?),
213 None => None,
214 };
215
216 let updated = sqlx::query(
217 "UPDATE users SET
218 display_name = coalesce($2, display_name),
219 role = coalesce($3, role),
220 active = coalesce($4, active),
221 password_hash = coalesce($5, password_hash)
222 WHERE id = $1",
223 )
224 .bind(target)
225 .bind(patch.display_name.as_deref().map(str::trim).filter(|name| !name.is_empty()))
226 .bind(patch.role)
227 .bind(patch.active)
228 .bind(password_hash.as_deref())
229 .execute(&state.pool)
230 .await?
231 .rows_affected();
232
233 if updated == 0 {
234 return Err(ApiError::new(StatusCode::NOT_FOUND, "no such user"));
235 }
236
237 if patch.active == Some(false) || patch.password.is_some() {
241 let ended = session::revoke_all(&state.pool, target).await?;
242 tracing::info!(%target, ended, "ended sessions after a change to the account");
243 }
244
245 tracing::info!(%target, by = %user.user_id, "updated a user");
246 Ok(StatusCode::NO_CONTENT)
247}
248
249pub async fn list_agents(State(state): State<AppState>, user: CurrentUser, Path(target): Path<Uuid>) -> Result<impl IntoResponse, ApiError> {
252 require_manager_or_admin(&user)?;
253
254 let agents: Vec<AgentRow> = sqlx::query_as("SELECT id, name, revoked_at, last_seen_at, created_at FROM agents WHERE user_id = $1 ORDER BY created_at")
255 .bind(target)
256 .fetch_all(&state.pool)
257 .await?;
258
259 Ok(Json(agents))
260}
261
262pub async fn create_agent(
264 State(state): State<AppState>,
265 user: CurrentUser,
266 Path(target): Path<Uuid>,
267 Json(new): Json<NewAgent>,
268) -> Result<impl IntoResponse, ApiError> {
269 user.require_admin()?;
270
271 let name = new.name.trim();
272 if name.is_empty() {
273 return Err(ApiError::bad_request("an agent needs a name; the machine it runs on is the usual one"));
274 }
275
276 let active: Option<bool> = sqlx::query_scalar("SELECT active FROM users WHERE id = $1")
280 .bind(target)
281 .fetch_optional(&state.pool)
282 .await?;
283 match active {
284 None => return Err(ApiError::new(StatusCode::NOT_FOUND, "no such user")),
285 Some(false) => return Err(ApiError::new(StatusCode::CONFLICT, "that account is deactivated")),
286 Some(true) => {}
287 }
288
289 let token = generate_token();
290 let id: Uuid = sqlx::query_scalar("INSERT INTO agents (user_id, name, token_hash) VALUES ($1, $2, $3) RETURNING id")
291 .bind(target)
292 .bind(name)
293 .bind(hash_token(&token))
294 .fetch_one(&state.pool)
295 .await?;
296
297 tracing::info!(%id, %target, by = %user.user_id, "issued an agent token");
298 Ok((
299 StatusCode::CREATED,
300 Json(IssuedAgent {
301 id,
302 name: name.to_string(),
303 token,
304 notice: "this token is shown once; the server keeps only its hash",
305 }),
306 ))
307}
308
309pub async fn revoke_agent(State(state): State<AppState>, user: CurrentUser, Path(agent): Path<Uuid>) -> Result<impl IntoResponse, ApiError> {
311 user.require_admin()?;
312
313 let revoked = sqlx::query("UPDATE agents SET revoked_at = now() WHERE id = $1 AND revoked_at IS NULL")
317 .bind(agent)
318 .execute(&state.pool)
319 .await?
320 .rows_affected();
321
322 if revoked == 0 {
323 let exists: Option<Uuid> = sqlx::query_scalar("SELECT id FROM agents WHERE id = $1")
326 .bind(agent)
327 .fetch_optional(&state.pool)
328 .await?;
329 if exists.is_none() {
330 return Err(ApiError::new(StatusCode::NOT_FOUND, "no such agent"));
331 }
332 }
333
334 tracing::info!(%agent, by = %user.user_id, "revoked an agent token");
335 Ok(StatusCode::NO_CONTENT)
336}
337
338#[derive(Debug, Deserialize)]
343pub struct PasswordChange {
344 pub current: String,
345 pub new: String,
346}
347
348pub async fn change_own_password(State(state): State<AppState>, user: CurrentUser, Json(change): Json<PasswordChange>) -> Result<impl IntoResponse, ApiError> {
349 let stored: Option<String> = sqlx::query_scalar("SELECT password_hash FROM users WHERE id = $1")
350 .bind(user.user_id)
351 .fetch_one(&state.pool)
352 .await?;
353
354 let Some(stored) = stored else {
357 return Err(ApiError::new(StatusCode::CONFLICT, "this account has no password to change"));
358 };
359 if !session::verify_password(&change.current, &stored) {
360 return Err(ApiError::new(StatusCode::UNAUTHORIZED, "the current password is wrong"));
361 }
362
363 let hash = hash_new_password(&change.new)?;
364 sqlx::query("UPDATE users SET password_hash = $1 WHERE id = $2")
365 .bind(&hash)
366 .bind(user.user_id)
367 .execute(&state.pool)
368 .await?;
369
370 sqlx::query("DELETE FROM sessions WHERE user_id = $1 AND id <> $2")
374 .bind(user.user_id)
375 .bind(user.session_id)
376 .execute(&state.pool)
377 .await?;
378
379 tracing::info!(user_id = %user.user_id, "changed their password");
380 Ok(StatusCode::NO_CONTENT)
381}
382
383fn require_manager_or_admin(user: &CurrentUser) -> Result<(), ApiError> {
385 match user.role {
386 UserRole::Admin | UserRole::Manager => Ok(()),
387 UserRole::Employee => Err(ApiError::new(StatusCode::FORBIDDEN, "not allowed")),
388 }
389}
390
391fn hash_new_password(password: &str) -> Result<String, ApiError> {
393 if password.chars().count() < MIN_PASSWORD_LENGTH {
394 return Err(ApiError::bad_request(format!("the password must be at least {MIN_PASSWORD_LENGTH} characters")));
395 }
396 session::hash_password(password).map_err(Into::into)
397}
398
399fn generate_token() -> String {
404 use rand::RngExt;
405
406 let bytes: [u8; 32] = rand::rng().random();
407 bytes.iter().fold(String::from("kasl_"), |mut acc, byte| {
408 use std::fmt::Write;
409 let _ = write!(acc, "{byte:02x}");
410 acc
411 })
412}
413
414fn looks_like_an_email(candidate: &str) -> bool {
420 match candidate.split_once('@') {
421 Some((local, domain)) => !local.is_empty() && domain.contains('.') && !domain.starts_with('.') && !domain.ends_with('.'),
422 None => false,
423 }
424}
425
426async fn is_last_admin(pool: &sqlx::PgPool, target: Uuid) -> Result<bool, ApiError> {
428 let others: i64 = sqlx::query_scalar("SELECT count(*) FROM users WHERE role = 'admin' AND active AND id <> $1")
429 .bind(target)
430 .fetch_one(pool)
431 .await?;
432
433 let is_admin: Option<bool> = sqlx::query_scalar("SELECT (role = 'admin' AND active) FROM users WHERE id = $1")
437 .bind(target)
438 .fetch_optional(pool)
439 .await?;
440
441 Ok(is_admin.unwrap_or(false) && others == 0)
442}
443
444#[cfg(test)]
445mod tests {
446 use super::*;
447
448 #[test]
449 fn a_token_is_long_random_and_recognisable() {
450 let token = generate_token();
451 assert!(token.starts_with("kasl_"), "a token in a log should be identifiable: {token}");
452 assert_eq!(token.len(), 5 + 64, "32 bytes as hex");
453 assert_ne!(token, generate_token(), "two tokens must never be the same");
454 }
455
456 #[test]
457 fn a_short_password_is_refused_before_it_is_hashed() {
458 let error = hash_new_password("short").expect_err("seven characters is not a password");
459 assert!(error.to_string().contains("at least 8"), "{error}");
460 assert!(hash_new_password("just long enough").is_ok());
461 }
462
463 #[test]
464 fn the_email_check_admits_addresses_and_refuses_obvious_mistakes() {
465 for good in ["a@b.co", "first.last@example.com", "kirill+kasl@example.co.uk"] {
466 assert!(looks_like_an_email(good), "{good} should be accepted");
467 }
468 for bad in ["kirill", "kirill@", "@example.com", "kirill@example", "kirill@example.com."] {
471 assert!(!looks_like_an_email(bad), "{bad} should be refused");
472 }
473 }
474
475 #[test]
476 fn a_manager_reads_and_an_employee_does_not() {
477 let user = |role| CurrentUser {
478 session_id: Uuid::nil(),
479 user_id: Uuid::nil(),
480 role,
481 };
482 assert!(require_manager_or_admin(&user(UserRole::Admin)).is_ok());
483 assert!(require_manager_or_admin(&user(UserRole::Manager)).is_ok());
484 assert!(require_manager_or_admin(&user(UserRole::Employee)).is_err());
485
486 assert!(user(UserRole::Manager).require_admin().is_err());
488 }
489
490 #[test]
491 fn an_absent_patch_field_means_leave_it_alone() {
492 let patch: UserPatch = serde_json::from_value(serde_json::json!({"display_name": "Kirill"})).unwrap();
495 assert_eq!(patch.display_name.as_deref(), Some("Kirill"));
496 assert!(patch.role.is_none() && patch.active.is_none() && patch.password.is_none());
497 }
498
499 #[test]
500 fn a_new_user_defaults_to_the_least_authority() {
501 let new: NewUser = serde_json::from_value(serde_json::json!({"email": "a@b.co"})).unwrap();
502 assert_eq!(new.role, UserRole::Employee, "a role must be asked for, never assumed");
503 assert!(new.password.is_none(), "an account for an agent needs no password");
504 }
505}