From 5ba34424b8190d4a6c01bc001b52b73ee6228db8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 11 Sep 2026 10:16:47 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=B9=20chore:=20split=20user=20into=20d?= =?UTF-8?q?omain/db/service=20layers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ai/server.rs | 2 +- src/constant.rs | 4 +- src/database.rs | 4 +- src/db/cap.rs | 2 +- src/db/exam_attempt.rs | 4 +- src/db/mod.rs | 1 + src/db/user.rs | 719 +++++++++++++++++++ src/domain/appointment_slot.rs | 12 +- src/domain/board.rs | 4 +- src/domain/class_member.rs | 15 +- src/domain/class_pump.rs | 2 +- src/domain/event.rs | 6 +- src/domain/exam_question.rs | 4 +- src/domain/homework_submission.rs | 4 +- src/domain/parent_link.rs | 2 +- src/domain/registration.rs | 8 +- src/domain/user.rs | 1072 +---------------------------- src/service/course.rs | 4 +- src/service/exam_attempt.rs | 6 +- src/service/mod.rs | 1 + src/service/user.rs | 477 +++++++++++++ src/web/appointments.rs | 11 +- src/web/attendance.rs | 2 +- src/web/auth.rs | 11 +- src/web/bank_questions.rs | 9 +- src/web/board_ws.rs | 16 +- src/web/boards.rs | 6 +- src/web/builder.rs | 8 +- src/web/classes.rs | 17 +- src/web/courses.rs | 20 +- src/web/dto.rs | 2 +- src/web/events.rs | 15 +- src/web/exams/mod.rs | 2 +- src/web/extractor.rs | 2 +- src/web/homework.rs | 4 +- src/web/marks.rs | 2 +- src/web/meals.rs | 11 +- src/web/messages.rs | 4 +- src/web/mod.rs | 19 +- src/web/payments.rs | 4 +- src/web/pomodoro.rs | 2 +- src/web/sessions.rs | 6 +- src/web/tenant_state.rs | 6 +- src/web/users.rs | 79 ++- src/web/work.rs | 4 +- tests/builder_api.rs | 4 +- tests/integration.rs | 16 +- tests/regress_admin_floor.rs | 14 +- tests/regress_role_sweep.rs | 8 +- 49 files changed, 1436 insertions(+), 1221 deletions(-) create mode 100644 src/db/user.rs create mode 100644 src/service/user.rs diff --git a/src/ai/server.rs b/src/ai/server.rs index 6292f46..086afb5 100644 --- a/src/ai/server.rs +++ b/src/ai/server.rs @@ -704,7 +704,7 @@ async fn principal( // Both the bare key (`abc`, as a REST path spells it) and the record form // (`user:abc`) are accepted. let key = who.strip_prefix("user:").unwrap_or(who); - User::read(&UserId::from_key(key), db) + crate::db::user::read(db, &UserId::from_key(key)) .await .map_err(|e| ("unavailable", format!("could not load `{who}`: {e}")))? .ok_or_else(|| ("unknown_user", format!("no user `{who}`"))) diff --git a/src/constant.rs b/src/constant.rs index ac4e782..994c2b8 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -969,7 +969,7 @@ pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count"; pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count"; /// The column a *grant* claim moves and puts back, so its transaction writes /// the holder's own `user` record — the one key -/// [`crate::domain::user::User::set_role`] writes (see +/// [`crate::service::user::set_role`] writes (see /// [`crate::db::cap::role_claim`]). Any `option` on the row would do: /// the claim nets zero and never reads it, so this is an alias rather than a /// column of its own — a new one would mean a migration on a SCHEMAFULL table @@ -1202,7 +1202,7 @@ pub const BOARD_OPEN_GUARD: &str = "locked = false AND closed_at = NONE"; /// an `event` row. /// /// This is `Event::registration_capacity`'s `Conflict` arm re-spelled in -/// SurrealQL, because the role cascade (`User::set_role`) frees a demoted +/// SurrealQL, because the role cascade (`service::user::set_role`) frees a demoted /// parent's seats *inside* its transaction and cannot call Rust from there. The /// audience conjunct is what keeps it that arm and only that arm: an event that /// takes no registrations is refused earlier, by the `Validation` arm, so a diff --git a/src/database.rs b/src/database.rs index e570eff..56924fb 100644 --- a/src/database.rs +++ b/src/database.rs @@ -545,8 +545,8 @@ mod tests { #[test] fn the_admin_seed_mints_the_role_with_the_row() { let source = - std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/domain/user.rs")) - .expect("read user.rs"); + std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/service/user.rs")) + .expect("read service/user.rs"); let start = source .find("pub async fn ensure_admin") .expect("ensure_admin is declared"); diff --git a/src/db/cap.rs b/src/db/cap.rs index 3ea51ad..117322c 100644 --- a/src/db/cap.rs +++ b/src/db/cap.rs @@ -454,7 +454,7 @@ pub(crate) async fn touch_and_create( /// The statements that put a transaction's write on a **user's own record** /// while the role that row still carries may hold the grant being written — /// [`touch_and_create`]'s trick pointed at the one key -/// [`crate::domain::user::User::set_role`] writes. +/// [`crate::service::user::set_role`] writes. /// /// WHY: a demotion sheds every grant the old role implied, and it does that in /// the role write's own transaction — but its sweeps are *snapshots* diff --git a/src/db/exam_attempt.rs b/src/db/exam_attempt.rs index 0c938d2..88c62be 100644 --- a/src/db/exam_attempt.rs +++ b/src/db/exam_attempt.rs @@ -370,10 +370,10 @@ mod tests { .hash_async() .await .unwrap(); - crate::domain::user::User::create( + crate::db::user::create( + db, crate::domain::user::Username::try_new("ogrenci").unwrap(), hash, - db, ) .await .unwrap() diff --git a/src/db/mod.rs b/src/db/mod.rs index 1ad9342..5a2132a 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -10,3 +10,4 @@ pub mod page; pub mod payment_ledger; pub mod session; pub mod settings; +pub mod user; diff --git a/src/db/user.rs b/src/db/user.rs new file mode 100644 index 0000000..fcbe36f --- /dev/null +++ b/src/db/user.rs @@ -0,0 +1,719 @@ +//! The `user` table: the row mint (with the duplicate-username mapping), row +//! reads and listings, the admin-floor count, the role cascade transaction, +//! and the field-scoped writers. The workflows that sequence these under +//! [`crate::service::user::ADMIN_FLOOR_LOCK`] live in +//! [`crate::service::user`]. + +use surrealdb::types::{RecordId, SurrealValue}; + +use crate::constant::{ + APPOINTMENT_SLOT_TABLE, APPOINTMENT_TABLE, BOARD_TABLE, CLASS_GROUP_TABLE, + CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE, COURSE_TABLE, ENROLLMENT_COUNT_FIELD, + ENROLLMENT_TABLE, PARENT_LINK_TABLE, REGISTRATION_COUNT_FIELD, REGISTRATION_FROZEN_GUARD, + REGISTRATION_TABLE, +}; +use crate::database::{Database, transaction_with_retry, write_with_retry}; +use crate::db::field_update::FieldUpdate; +use crate::db::page::PagedList; +use crate::domain::appointment::AppointmentStatus; +use crate::domain::board::Board; +use crate::domain::note_file::FileContentType; +use crate::domain::preferences::{Language, PaletteColor, Theme}; +use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; +use crate::domain::role::Role; +use crate::domain::text_fold::{search_fold, search_fold_sql}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::{PasswordHash, User, UserId, Username}; +use crate::error::AppError; + +/// Register a new account. New users always start as [`Role::Student`]; +/// elevation is a separate, admin-only action +/// (see [`crate::service::user::set_role`]). +pub async fn create( + db: &Database, + username: Username, + password_hash: PasswordHash, +) -> Result { + create_with_role(db, username, password_hash, Role::Student).await +} + +/// The one row-minting path. `role` is written *with* the row rather than +/// patched on afterwards, which is what makes the admin seed atomic: a +/// create-then-promote pair can be interrupted between its halves (a SIGKILL, +/// or a cancelled future), and the row left behind is an ordinary student +/// account that [`crate::service::user::ensure_admin`] must then refuse to +/// touch — a deployment with no admin and no way for a later boot to repair it. +pub async fn create_with_role( + db: &Database, + username: Username, + password_hash: PasswordHash, + role: Role, +) -> Result { + if find_by_username(db, username.as_str()).await?.is_some() { + return Err(AppError::Conflict("username already taken")); + } + let user = User { + id: UserId::generate(), + username, + password_hash, + role, + name: None, + surname: None, + email: None, + phone: None, + birth_date: None, + theme: None, + language: None, + palette_color: None, + display_name: None, + bio: None, + avatar_file: None, + avatar_content_type: None, + avatar_size: None, + }; + let created: Result, surrealdb::Error> = + db.create(user.id.record()).content(user.clone()).await; + match created { + Ok(Some(created)) => Ok(created), + Ok(None) => Err(AppError::Internal("failed to create user".into())), + // The availability pre-check above is not atomic with the insert: + // two concurrent registrations can both pass it, and the loser then + // trips the unique username index. That loss is the same condition + // as the sequential duplicate, so report the same 409 — not a 500. + Err(err) => { + if find_by_username(db, user.username.as_str()) + .await? + .is_some() + { + Err(AppError::Conflict("username already taken")) + } else { + Err(err.into()) + } + } + } +} + +pub async fn read(db: &Database, id: &UserId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +pub async fn list_all( + db: &Database, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new("user", "ORDER BY id DESC") + .run(limit, offset, db) + .await +} + +/// Fetch the users behind `ids` in one query. Ids with no row are simply +/// absent from the result — the caller decides how to degrade. +pub async fn list_by_ids(db: &Database, ids: &[UserId]) -> Result, AppError> { + if ids.is_empty() { + return Ok(Vec::new()); + } + let records: Vec = ids.iter().map(UserId::record).collect(); + let mut result = db + .query("SELECT * FROM user WHERE id IN $ids") + .bind(("ids", records)) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Every user holding exactly `role` — e.g. the roster of a role-targeted +/// event. Exact match, not `at_least`: "all teachers" means teachers, not +/// managers and admins too. +pub async fn list_by_role(db: &Database, role: Role) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM user WHERE role = $role ORDER BY id DESC") + .bind(("role", role)) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Would lowering `target` out of `admin` leave the school with none? Both +/// halves are asked of the **live** rows in one round trip: is that row an +/// admin right now, and does any other admin exist. It asks for one id per +/// half rather than a `count()` — a count over an indexed field compared +/// against a plan-time value answers `{count: N}` on the real server, and +/// neither half needs a number. +/// +/// Caller must hold +/// [`crate::service::user::ADMIN_FLOOR_LOCK`] for the answer to still be +/// true by the time it is acted on. +pub async fn would_orphan_admins(db: &Database, target: &UserId) -> Result { + let mut result = db + .query( + "SELECT VALUE id FROM user WHERE id = $usr AND role = $role;\n\ + SELECT VALUE id FROM user WHERE role = $role AND id != $usr LIMIT 1", + ) + .bind(("role", Role::Admin)) + .bind(("usr", target.record())) + .await? + .check()?; + let is_admin = !result.take::>(0)?.is_empty(); + let others = !result.take::>(1)?.is_empty(); + Ok(is_admin && !others) +} + +/// Case- and diacritic-insensitive fragment search over username, name, +/// and surname. Needle and columns both go through +/// [`crate::domain::text_fold`], so `ilker` finds `İLKER` and back — +/// backs the user pickers. `role` narrows to one role (e.g. only students +/// for an enroll picker); `None` searches everyone. `allowed_roles` +/// narrows the *visible* set (the roles a non-staff caller may message — +/// see [`Role::messageable_roles`]); it is part of the query, not a +/// post-filter, so `total` counts only what the caller may see. A blank +/// `query` +/// matches everyone, so blank + `role` is a role-scoped listing. Returns +/// every match, ordered by username; the HTTP layer pages the result like +/// any other list (no built-in cap — an over-broad fragment is windowed +/// by `?limit`). +pub async fn search( + db: &Database, + query: &str, + role: Option, + allowed_roles: Option<&[Role]>, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + let needle = search_fold(query.trim()); + let text_clause = format!( + "({} CONTAINS $q OR {} CONTAINS $q OR {} CONTAINS $q)", + search_fold_sql("username"), + search_fold_sql("name ?? ''"), + search_fold_sql("surname ?? ''"), + ); + let mut clauses = Vec::new(); + if !needle.is_empty() { + clauses.push(text_clause.as_str()); + } + if role.is_some() { + clauses.push("role = $role"); + } + if allowed_roles.is_some() { + clauses.push("role IN $allowed"); + } + let where_clause = if clauses.is_empty() { + "true".to_string() + } else { + clauses.join(" AND ") + }; + let mut list = PagedList::new(format!("user WHERE {where_clause}"), "ORDER BY username") + .bind("q", needle); + if let Some(role) = role { + list = list.bind("role", role); + } + if let Some(allowed) = allowed_roles { + list = list.bind("allowed", allowed.to_vec()); + } + list.run(limit, offset, db).await +} + +/// The role write and every sweep it owes, in one transaction — the +/// statement list behind [`crate::service::user::set_role`]. See there for +/// the floor that guards it and the arm-by-arm reasoning; what follows is +/// the store side. +/// +/// Writes *only* the `role` field of the user row (never the whole row): +/// the row mixes admin-owned (role) and self-service (profile, preferences) +/// fields, and each writer starts from a snapshot read at request start. A +/// whole-row write would carry the snapshot's copy of the *other* group back +/// over a concurrent edit — an in-flight profile save silently reverting an +/// admin's demotion, or this write erasing a profile edit that raced it. +/// [`crate::db::user::set_profile`] and +/// [`crate::db::user::set_preferences`] are scoped for the same reason. +/// +/// What is swept, and why the conditions differ: +/// +/// * **Non-student** sheds class memberships, *every* enrollment row +/// (hand-placed ones included — only students enroll, and a kept row +/// would grant nothing and count a seat) and the parent links observing +/// them. Memberships and enrollments were already one transaction and +/// still are: released apart, an enrollment row could be left tagged with +/// a class whose counters had been given back, so the class passed its +/// zero-zero delete guard and no sweep could ever reach the row again. +/// * **Parent** additionally frees event seats, comes off every whiteboard +/// roster and has the boards they *created* closed — permanently +/// read-only, rows kept, because a room whose creator is demoted is +/// commandable by nobody at all (see the statement's own note). The seat +/// is the one thing on a signup list nothing +/// else could remove: staff free their own by hand (`unregister` allows +/// the self case) but a parent can reach no such door, so a promotion +/// strands nothing and only this demotion does. A list that has already +/// **frozen** ([`REGISTRATION_FROZEN_GUARD`]) is left exactly as it +/// stands — past the freeze it is historical record, re-registering +/// answers 409, and rewriting it here would be irrecoverable. A signup +/// whose event record is *gone* has no seat to hand back and no list that +/// can freeze, so it is deleted rather than skipped: skipped, it is +/// stranded forever (`unregister` 404s on the missing event). +/// * **Below teacher** gives up course staffing and homeroom-teacher +/// columns — only teacher+ may hold either — and the published +/// appointment calendar, whose live bookings are cancelled in the same +/// breath. Nothing else could ever reach those: a slot is listed only on +/// its own teacher's calendar and deleted only by a teacher+, so after the +/// demotion neither its owner nor a manager has a route that yields its +/// id, and a booking on it can be neither decided (teacher+ only) nor +/// cancelled once its window opens — leaving the slot's `occupied` seat +/// pinned at one and the slot itself undeletable forever. The requester +/// keeps the row, `cancelled`, with the teacher on `cancelled_by` and the +/// reason on `cancel_reason`; the slot it pointed at is gone, so the +/// booking renders without a window +/// ([`crate::domain::appointment::Appointment`]'s reader already treats a +/// vanished slot that way). There is no notification anywhere in +/// this crate, so a settled row the person can read is the strongest +/// defined end available — and the alternative, deleting it, would make a +/// confirmed meeting vanish with no trace at all. +/// +/// The returned boards are the rooms whose roster this changed, plus those +/// the user created — whose roster is untouched but which are now closed, +/// and they carry that stamp because the close is written first. Publishing +/// to them is the caller's job: an in-process +/// fan-out cannot sit inside a database transaction, and a room told before +/// the commit would re-read the pre-commit state. +/// +/// Admissible for [`transaction_with_retry`] by construction: `SELECT`, +/// `UPDATE` and `DELETE` only, so no statement can answer "already exists" +/// and every lost round is a plain re-send. +pub async fn set_role_cascade( + db: &Database, + target: &UserId, + role: Role, +) -> Result<(User, Vec), AppError> { + // Built as a statement list rather than one string so the result slot + // of the board write is *counted*, not hand-tallied against arms that + // may or may not be in the batch. Slot 0 is `BEGIN`, as everywhere. + let mut batch = vec![ + "BEGIN TRANSACTION".to_string(), + "UPDATE $usr SET role = $role RETURN AFTER".to_string(), + ]; + if role != Role::Student { + batch.push(format!( + "LET $links = (DELETE {CLASS_MEMBER_TABLE} WHERE user = $usr RETURN BEFORE)" + )); + batch.push(format!( + "FOR $link IN ($links ?? []) {{ UPDATE $link.class SET \ + {CLASS_MEMBER_COUNT_FIELD} = \ + math::max([({CLASS_MEMBER_COUNT_FIELD} ?? 0) - 1, 0]); }}" + )); + batch.push(format!( + "LET $rows = (DELETE {ENROLLMENT_TABLE} WHERE user = $usr RETURN BEFORE)" + )); + batch.push(format!( + "FOR $row IN ($rows ?? []) {{ UPDATE $row.course SET \ + {ENROLLMENT_COUNT_FIELD} = \ + math::max([({ENROLLMENT_COUNT_FIELD} ?? 0) - 1, 0]); }}" + )); + batch.push(format!("DELETE {PARENT_LINK_TABLE} WHERE student = $usr")); + } + let mut board_slot = None; + if role == Role::Parent { + batch.push(format!( + "LET $signups = (SELECT * FROM {REGISTRATION_TABLE} WHERE user = $usr)" + )); + // Row and seat move together per signup, the way `unregister` does: + // the seats are independent facts on unrelated events. A missing + // event matches nothing in the guard *and* nothing in the counter + // write, which is precisely the orphan rule. + batch.push(format!( + "FOR $signup IN ($signups ?? []) {{ \ + IF array::len((SELECT VALUE id FROM $signup.event \ + WHERE {REGISTRATION_FROZEN_GUARD})) = 0 {{ \ + LET $freed = (DELETE $signup.id RETURN BEFORE); \ + UPDATE $signup.event SET {REGISTRATION_COUNT_FIELD} = \ + math::max([({REGISTRATION_COUNT_FIELD} ?? 0) - array::len($freed), 0]); \ + }}; }}" + )); + // A room whose *creator* is demoted can never be ended by anyone: + // the whiteboard is closed to parents outright, so the creator is + // 404'd off their own board, `clear`/`lock`/`close`/`delete` are + // creator-only for everyone else, and `Board::list_for_user` is the + // crate's only enumeration — no manager or admin can so much as find + // the id. Its participants meanwhile keep drawing (the room re-derives + // membership per frame and they still pass), into a board only the + // 50 000-stroke lifetime cap could ever retire. So the demotion + // retires it, with the same compare-and-set [`Board::close`] uses: an + // already-closed board keeps its first stamp. Closed and not deleted + // because the marks are the participants' work too — they keep reading + // the board and its whole history, and the creator's `board_count` + // seat stays taken, which is correct while the row it counts exists. + // Stamped *before* the roster strip so the strip's `RETURN AFTER` + // carries the closed row the caller fans out. + batch.push(format!( + "UPDATE {BOARD_TABLE} SET closed_at = $now WHERE creator = $usr AND closed_at = NONE" + )); + board_slot = Some(batch.len()); + batch.push(format!( + "UPDATE {BOARD_TABLE} SET participants -= $usr \ + WHERE $usr IN participants OR creator = $usr RETURN AFTER" + )); + } + if role != Role::Parent { + batch.push(format!("DELETE {PARENT_LINK_TABLE} WHERE parent = $usr")); + } + if !role.at_least(Role::Teacher) { + batch.push(format!( + "UPDATE {COURSE_TABLE} SET teachers -= $usr WHERE $usr IN teachers" + )); + batch.push(format!( + "UPDATE {CLASS_GROUP_TABLE} SET teacher = NONE WHERE teacher = $usr" + )); + // The published calendar goes too, and the bookings on it are + // settled first: a slot only its own teacher can list and only a + // teacher+ can delete is reachable by nobody once that teacher is + // demoted, and a live booking on one is worse — nobody can approve, + // reject or (past its start) cancel it, so it pins the slot's + // `occupied` seat forever. Cancelled rather than deleted so the + // person who asked is left with a settled booking they can still + // read, carrying who dropped it and why; the slot row (and with it + // the seat) goes, which is what makes this convergent. + batch.push(format!( + "LET $slots = (SELECT VALUE id FROM {APPOINTMENT_SLOT_TABLE} WHERE teacher = $usr)" + )); + batch.push(format!( + "UPDATE {APPOINTMENT_TABLE} SET status = '{cancelled}', cancelled_by = $usr, \ + cancel_reason = 'the teacher no longer holds a teaching role' \ + WHERE slot IN $slots AND status IN ['{pending}', '{approved}']", + cancelled = AppointmentStatus::Cancelled.as_str(), + pending = AppointmentStatus::Pending.as_str(), + approved = AppointmentStatus::Approved.as_str(), + )); + // Deleting the slots is also what makes a *concurrent* booking safe: + // `Appointment::book` claims the slot row this deletes, so the two + // collide in the store and the loser re-sends. A slot *published* + // concurrently shares no key with any of this, which is why + // `AppointmentSlot::insert_claimed` claims the user row instead. + batch.push(format!( + "DELETE {APPOINTMENT_SLOT_TABLE} WHERE id IN $slots" + )); + } + let sql = format!("{};\nCOMMIT TRANSACTION;", batch.join(";\n")); + let (mut result, mut errors) = transaction_with_retry( + db, + &sql, + &[ + ("usr".into(), target.record().into_value()), + ("role".into(), role.into_value()), + ("now".into(), Timestamp::now().as_millis().into_value()), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + let updated = result + .take::>(1)? + .into_iter() + .next() + .ok_or(AppError::NotFound)?; + let boards = match board_slot { + Some(slot) => result.take::>(slot)?, + None => Vec::new(), + }; + Ok((updated, boards)) +} + +/// Write the personal-info and public-profile fields the request actually +/// carried — everything a person edits about themselves except the avatar +/// blob, which needs its own writer ([`set_avatar`]). Every +/// column is nullable, so each argument is an outer/inner `Option`: `None` +/// = omitted (not written at all), `Some(None)` = cleared, `Some(Some(v))` +/// = set. Merging the request against the current row is the HTTP layer's +/// job; the caller authorizes. +/// +/// Request-scoped, not merely field-scoped: nothing guards the row across +/// the handler's read and this write, so re-sending the snapshot's value +/// for an omitted field would revert a concurrent PATCH of that field — +/// two profile edits (a name and a phone) used to lose each other. See +/// [`set_role_cascade`] for why no writer here touches the whole row. +// One argument per nullable column is the point: folding them into a struct +// would just re-spell the HTTP DTO here and cost the compiler's check that +// every column was considered at the call site. +#[allow(clippy::too_many_arguments)] +pub async fn set_profile( + db: &Database, + id: &UserId, + name: Option>, + surname: Option>, + email: Option>, + phone: Option>, + birth_date: Option>, + display_name: Option>, + bio: Option>, +) -> Result { + FieldUpdate::new(id.record()) + .set("name", name) + .set("surname", surname) + .set("email", email) + .set("phone", phone) + .set("birth_date", birth_date) + .set("display_name", display_name) + .set("bio", bio) + .run::(db) + .await +} + +/// Point the row at a freshly uploaded avatar blob, returning the row *as +/// it was* — the caller deletes `before.get_avatar_file()` off disk. Losing +/// `RETURN BEFORE` here strands the replaced blob forever: no route ever +/// deletes a user, so nothing else would collect it. +/// +/// Field-scoped for the same reason as [`set_profile`]: an avatar +/// upload must not carry a stale snapshot's role back over an admin's +/// change. `None` means the row is gone. +/// +/// Sent through [`write_with_retry`] like every other single-statement row +/// write here, unguarded or not: the user row is contended (preferences, +/// profile, role all write it), and a lost round wrote nothing, so +/// re-sending it is the recovery rather than a 500 in the caller's face. +pub async fn set_avatar( + db: &Database, + id: &UserId, + file: &str, + content_type: &FileContentType, + size: i64, +) -> Result, AppError> { + let rows: Vec = write_with_retry( + db, + "UPDATE $u SET avatar_file = $file, avatar_content_type = $ct, avatar_size = $size \ + RETURN BEFORE", + &[ + ("u".into(), id.record().into_value()), + ("file".into(), file.to_string().into_value()), + ("ct".into(), content_type.clone().into_value()), + ("size".into(), size.into_value()), + ], + ) + .await?; + Ok(rows.into_iter().next()) +} + +/// Drop the avatar, returning the row as it was so the caller can delete +/// the blob. Same `RETURN BEFORE` contract as [`set_avatar`]. +pub async fn clear_avatar(db: &Database, id: &UserId) -> Result, AppError> { + let rows: Vec = write_with_retry( + db, + "UPDATE $u SET avatar_file = NONE, avatar_content_type = NONE, \ + avatar_size = NONE RETURN BEFORE", + &[("u".into(), id.record().into_value())], + ) + .await?; + Ok(rows.into_iter().next()) +} + +/// Replace a user's password hash — the builder's admin-password reset +/// (`POST /schools/{slug}/admin-password`). Only the credential is +/// rewritten; revoking the sessions minted under the old one is the +/// caller's second half +/// ([`crate::db::session::delete_by_user`]), because a reset +/// that leaves a stolen cookie working resets nothing. +pub async fn set_password_hash( + db: &Database, + id: &UserId, + password_hash: PasswordHash, +) -> Result, AppError> { + let rows: Vec = write_with_retry( + db, + "UPDATE $u SET password_hash = $hash RETURN AFTER", + &[ + ("u".into(), id.record().into_value()), + ("hash".into(), password_hash.into_value()), + ], + ) + .await?; + Ok(rows.into_iter().next()) +} + +/// Write the UI-preference fields the request actually carried. Same +/// contract as [`set_profile`]: `None` = omitted (not written), +/// `Some(None)` = cleared back to "never chose", `Some(Some(v))` = set. +pub async fn set_preferences( + db: &Database, + id: &UserId, + theme: Option>, + language: Option>, + palette_color: Option>, +) -> Result { + FieldUpdate::new(id.record()) + .set("theme", theme) + .set("language", language) + .set("palette_color", palette_color) + .run::(db) + .await +} + +pub async fn find_by_username(db: &Database, username: &str) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM user WHERE username = $username LIMIT 1") + .bind(("username", username.to_string())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database::init_mem; + use crate::domain::user::Password; + + fn png() -> FileContentType { + FileContentType::try_new("image/png").unwrap() + } + + async fn a_user(username: &str, db: &Database) -> User { + create( + db, + Username::try_new(username).unwrap(), + Password::try_new("secret1") + .unwrap() + .hash_async() + .await + .unwrap(), + ) + .await + .unwrap() + } + + #[tokio::test] + async fn a_stale_profile_write_cannot_revert_a_role_change() { + let db = init_mem().await.unwrap(); + let user = a_user("aysenur", &db).await; + + // A PATCH /users/me handler reads its snapshot (role = student)... + let stale = read(&db, user.get_id()).await.unwrap().unwrap(); + + // ...then an admin's role change commits before the profile save runs. + crate::service::user::set_role(&db, user.get_id(), Role::Teacher) + .await + .unwrap(); + + // The in-flight save lands from the stale snapshot. It must write only + // the profile fields — not carry the snapshot's old role back over the + // admin's change. + let name = PersonName::try_new("name", "Ayşenur").unwrap(); + set_profile( + &db, + stale.get_id(), + Some(Some(name.clone())), + None, + None, + None, + None, + None, + None, + ) + .await + .unwrap(); + + let after = read(&db, user.get_id()).await.unwrap().unwrap(); + assert_eq!( + after.get_role(), + Role::Teacher, + "the role change must survive the racing profile write" + ); + assert_eq!( + after.get_name(), + Some(&name), + "the profile edit itself lands" + ); + } + + #[tokio::test] + async fn an_avatar_upload_cannot_revert_a_role_change() { + let db = init_mem().await.unwrap(); + let user = a_user("berk", &db).await; + + // The upload handler holds its snapshot (role = student)... + let stale = read(&db, user.get_id()).await.unwrap().unwrap(); + + // ...an admin promotes and the person edits their bio, both while the + // blob is still being written... + crate::service::user::set_role(&db, user.get_id(), Role::Teacher) + .await + .unwrap(); + let display_name = DisplayName::try_new("Berk").unwrap(); + set_profile( + &db, + user.get_id(), + None, + None, + None, + None, + None, + Some(Some(display_name.clone())), + None, + ) + .await + .unwrap(); + + // ...and only then does the avatar land, from the stale row's id. + set_avatar(&db, stale.get_id(), "blob-1", &png(), 42) + .await + .unwrap() + .expect("the row exists"); + + let after = read(&db, user.get_id()).await.unwrap().unwrap(); + assert_eq!( + after.get_role(), + Role::Teacher, + "the role change must survive the racing avatar write" + ); + assert_eq!( + after.get_display_name(), + Some(&display_name), + "and so must every other column the avatar write never named" + ); + assert_eq!(after.get_avatar_file(), Some("blob-1")); + assert_eq!(after.get_avatar_content_type(), Some(&png())); + assert_eq!(after.get_avatar_size(), Some(42)); + } + + /// The blob cleanup is built entirely on `RETURN BEFORE`: without the old + /// `avatar_file` coming back, every replace strands a file on disk that no + /// route ever collects. + #[tokio::test] + async fn the_avatar_writers_return_the_replaced_blob() { + let db = init_mem().await.unwrap(); + let user = a_user("ceyda", &db).await; + + let before = set_avatar(&db, user.get_id(), "blob-1", &png(), 10) + .await + .unwrap() + .expect("the row exists"); + assert_eq!(before.get_avatar_file(), None, "no blob to collect yet"); + + let before = set_avatar(&db, user.get_id(), "blob-2", &png(), 20) + .await + .unwrap() + .expect("the row exists"); + assert_eq!( + before.get_avatar_file(), + Some("blob-1"), + "the replaced blob is what the caller must delete" + ); + + let before = clear_avatar(&db, user.get_id()) + .await + .unwrap() + .expect("the row exists"); + assert_eq!(before.get_avatar_file(), Some("blob-2")); + + let after = read(&db, user.get_id()).await.unwrap().unwrap(); + assert_eq!(after.get_avatar_file(), None); + assert_eq!(after.get_avatar_content_type(), None); + assert_eq!(after.get_avatar_size(), None); + + assert!( + clear_avatar(&db, &UserId::from_key("yok")) + .await + .unwrap() + .is_none(), + "a missing row is None, not an error" + ); + } +} diff --git a/src/domain/appointment_slot.rs b/src/domain/appointment_slot.rs index f99eb10..4651b57 100644 --- a/src/domain/appointment_slot.rs +++ b/src/domain/appointment_slot.rs @@ -207,7 +207,7 @@ impl AppointmentSlot { /// still *holds* a teaching role. /// /// Every row here names the teacher, so the write touches no key a demotion - /// touches: [`crate::domain::user::User::set_role`] sweeps the slots its own + /// touches: [`crate::service::user::set_role`] sweeps the slots its own /// snapshot can see, and a slot landing after that snapshot would survive it /// under a role that may not publish — reachable by no route afterwards, /// since the calendar hides a demoted teacher's slots and the deletes are @@ -951,7 +951,7 @@ mod tests { /// The other half of that claim: the publish that arrives *while* the /// demotion is running. Its sweep has already chosen the slots it will take - /// ([`crate::domain::user::User::set_role`] reads them into `$slots` before + /// ([`crate::service::user::set_role`] reads them into `$slots` before /// it deletes), so a row landing after that read shares no key with anything /// the demotion writes and survives it — a slot owned by someone who can /// neither list nor delete it, forever. The claim on the user record is what @@ -974,7 +974,6 @@ mod tests { #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_publish_landing_inside_a_demotion_never_outlives_the_role() { use crate::domain::role::Role; - use crate::domain::user::User; let (db, _serialized) = crate::database::init_test_server("slot_demotion_race").await; let (mut raced, mut published, mut stranded) = (0, 0, 0); @@ -1008,12 +1007,11 @@ mod tests { let db = db.clone(); let target = teacher.clone(); tokio::spawn(async move { - User::read(&target, &db) + crate::db::user::read(&db, &target) .await .unwrap() - .unwrap() - .set_role(Role::Student, &db) - .await + .expect("the account is there"); + crate::service::user::set_role(&db, &target, Role::Student).await }) }; tokio::time::sleep(std::time::Duration::from_millis(50)).await; diff --git a/src/domain/board.rs b/src/domain/board.rs index 217db83..c28477e 100644 --- a/src/domain/board.rs +++ b/src/domain/board.rs @@ -48,7 +48,7 @@ use crate::validate::validate_required; /// read, one user-list read and one field write. /// /// **A leaf**: nothing under it takes another lock. Note it does not reach the -/// demotion sweep in [`crate::domain::user::User::set_role`], which strips ids +/// demotion sweep in [`crate::service::user::set_role`], which strips ids /// from every roster inside the role write's own transaction — an invite that /// read a roster before that sweep can put a swept id back, which the boot /// repair and the room's own live gate both still catch. @@ -310,7 +310,7 @@ impl Board { // The demotion sweep — stripping a user off every roster they are listed // on, deleting nothing, and handing the affected rooms back so the caller - // can prompt them — lives in [`crate::domain::user::User::set_role`], where + // can prompt them — lives in [`crate::service::user::set_role`], where // it commits with the role write that invalidates the membership. /// Retire the board: permanently read-only, history still readable. diff --git a/src/domain/class_member.rs b/src/domain/class_member.rs index 11195f2..c95e72f 100644 --- a/src/domain/class_member.rs +++ b/src/domain/class_member.rs @@ -545,10 +545,10 @@ pub(crate) mod tests { .hash_async() .await .unwrap(); - let account = crate::domain::user::User::create( + let account = crate::db::user::create( + &db, crate::domain::user::Username::try_new("ogrenci").unwrap(), hash, - &db, ) .await .unwrap(); @@ -566,10 +566,13 @@ pub(crate) mod tests { .await .unwrap(); - account - .set_role(crate::domain::role::Role::Teacher, &db) - .await - .unwrap(); + crate::service::user::set_role( + &db, + account.get_id(), + crate::domain::role::Role::Teacher, + ) + .await + .unwrap(); assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); for class in [&first, &second] { assert_eq!( diff --git a/src/domain/class_pump.rs b/src/domain/class_pump.rs index ceae88c..d485bcb 100644 --- a/src/domain/class_pump.rs +++ b/src/domain/class_pump.rs @@ -347,7 +347,7 @@ impl Axis { // The sweep a role change *off* `student` owes — every class membership (each // class getting its member count back) and every enrollment row (each course // getting its seat back) — is two of the arms of -// [`crate::domain::user::User::set_role`], because it belongs in the same +// [`crate::service::user::set_role`], because it belongs in the same // transaction as the role write that invalidates them. It stays one fact with // the counters either way: released separately, a failure between the halves // left enrollment rows tagged `source = class_group:X` while the class had its diff --git a/src/domain/event.rs b/src/domain/event.rs index 0648d4e..fa6f074 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -146,13 +146,13 @@ impl EventAudience { /// are kept; the caller degrades their display like any stale reference. pub async fn members(&self, event: &EventId, db: &Database) -> Result, AppError> { match self { - EventAudience::School => Ok(User::list_all(None, 0, db) + EventAudience::School => Ok(crate::db::user::list_all(db, None, 0) .await? .0 .iter() .map(|user| user.get_id().clone()) .collect()), - EventAudience::Role { role } => Ok(User::list_by_role(*role, db) + EventAudience::Role { role } => Ok(crate::db::user::list_by_role(db, *role) .await? .iter() .map(|user| user.get_id().clone()) @@ -358,7 +358,7 @@ mod tests { /// The forcing function behind the one rule with two spellings: the freeze /// this file decides in Rust ([`Event::registration_capacity`]) and /// [`crate::constant::REGISTRATION_FROZEN_GUARD`], its SurrealQL copy, which - /// the role cascade (`User::set_role`) carries because it frees a demoted + /// the role cascade (`service::user::set_role`) carries because it frees a demoted /// parent's seats inside a transaction and cannot call Rust from there. /// /// Every schedule shape is put to both, including the three the SQL is most diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index cadf182..cafb618 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -1194,10 +1194,10 @@ mod tests { .hash_async() .await .unwrap(); - let student = crate::domain::user::User::create( + let student = crate::db::user::create( + &db, crate::domain::user::Username::try_new("ogrenci").unwrap(), hash, - &db, ) .await .unwrap(); diff --git a/src/domain/homework_submission.rs b/src/domain/homework_submission.rs index a7986b3..ffd65f3 100644 --- a/src/domain/homework_submission.rs +++ b/src/domain/homework_submission.rs @@ -413,10 +413,10 @@ mod tests { .hash_async() .await .unwrap(); - crate::domain::user::User::create( + crate::db::user::create( + db, crate::domain::user::Username::try_new(username).unwrap(), hash, - db, ) .await .unwrap() diff --git a/src/domain/parent_link.rs b/src/domain/parent_link.rs index 3822c19..21bbdf7 100644 --- a/src/domain/parent_link.rs +++ b/src/domain/parent_link.rs @@ -122,7 +122,7 @@ impl ParentLink { // Both role-change sweeps (the observed student leaving `student`, the // observing parent leaving `parent`) live in - // [`crate::domain::user::User::set_role`]: they commit with the role write + // [`crate::service::user::set_role`]: they commit with the role write // itself, so there is no window where a link outlives the role that // justified it. } diff --git a/src/domain/registration.rs b/src/domain/registration.rs index 7e976af..14dd932 100644 --- a/src/domain/registration.rs +++ b/src/domain/registration.rs @@ -5,7 +5,7 @@ use crate::database::Database; use crate::db::cap; use crate::domain::event::{Event, EventId}; use crate::domain::role::Role; -use crate::domain::user::{User, UserId}; +use crate::domain::user::UserId; use crate::error::AppError; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -77,7 +77,7 @@ impl Registration { /// /// The seat is claimed on the event row, so the same statement says nothing /// about the *user* it is for — and a fall to `parent` is the one demotion - /// whose sweep ([`crate::domain::user::User::set_role`]) can miss a seat and + /// whose sweep ([`crate::service::user::set_role`]) can miss a seat and /// leave it unfreeable: `unregister` refuses a non-student target and a /// parent cannot reach the route at all. So the transaction also claims the /// holder's own record ([`cap::role_claim`]), which is the key that @@ -133,7 +133,7 @@ impl Registration { // the reads that tell them apart. cap::Claimed::Full => match Event::read(event, db).await? { None => Err(AppError::NotFound), - Some(_) => match User::read(user, db).await? { + Some(_) => match crate::db::user::read(db, user).await? { Some(held) if held.get_role() == Role::Parent => Err(AppError::Forbidden( "that account was demoted to parent while this request ran — \ only students can be registered for", @@ -194,7 +194,7 @@ impl Registration { // The demotion sweep — freeing every seat a fall to `parent` would strand, // and leaving a list that has already frozen exactly as it stands — is an - // arm of [`crate::domain::user::User::set_role`], so the seat comes back in + // arm of [`crate::service::user::set_role`], so the seat comes back in // the same transaction as the role that invalidated it. The freeze it obeys // is [`Event::registration_capacity`]'s `Conflict` arm, re-spelled for // SurrealQL as [`crate::constant::REGISTRATION_FROZEN_GUARD`] and held to it diff --git a/src/domain/user.rs b/src/domain/user.rs index 38e7ebd..50b6278 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -1,60 +1,30 @@ +//! Pure user shapes: the typed id, the credential newtypes (username, +//! password, argon2 hash — with their blocking-pool discipline), and the row +//! itself. Persistence lives in [`crate::db::user`]; the admin seed and the +//! role change in [`crate::service::user`]. + use std::sync::OnceLock; use argon2::password_hash::SaltString; use argon2::{Argon2, PasswordHasher, PasswordVerifier}; use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ - AI_PRINCIPAL_KEY, APPOINTMENT_SLOT_TABLE, APPOINTMENT_TABLE, BOARD_TABLE, CLASS_GROUP_TABLE, - CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE, COURSE_TABLE, DECOY_PASSWORD, - ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE, PARENT_LINK_TABLE, REGISTRATION_COUNT_FIELD, - REGISTRATION_FROZEN_GUARD, REGISTRATION_TABLE, USER_TABLE, -}; -use crate::database::{Database, transaction_with_retry, write_with_retry}; -use crate::db::field_update::FieldUpdate; -use crate::db::page::PagedList; -use crate::domain::appointment::AppointmentStatus; -use crate::domain::board::Board; +use crate::constant::{AI_PRINCIPAL_KEY, DECOY_PASSWORD, USER_TABLE}; use crate::domain::monotonic_id::next_ulid; use crate::domain::note_file::FileContentType; use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; use crate::domain::role::Role; -use crate::domain::text_fold::{search_fold, search_fold_sql}; -use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_password, validate_username}; -/// One role demotion at a time, school-wide. -/// -/// The invariant it protects is "the school always keeps an admin", and that -/// guard is a count-then-write: read whether another admin exists, then lower -/// this row. SurrealDB conflict-checks neither side of that pair — a -/// `BEGIN…COMMIT` does not serialize a cross-record count against a concurrent -/// update (write-skew, see [`crate::db::cap`]) and a statement that only -/// *reads* the rival's row never collides with it. So two admins demoting each -/// other both counted the other and both committed, leaving **zero** admins and -/// a school nobody can administer: `ensure_admin` refuses to promote an -/// existing non-admin row on every later boot, so the only way back was hand-run -/// SurrealQL against the volume. -/// -/// Serializing the pair is what closes it, the same argument -/// [`crate::service::settings::SETTINGS_LOCK`] makes one level up: the deployment -/// runs one process by contract (stop-the-world upgrades), so process-wide is -/// deployment-wide. A per-row counter (the [`crate::db::cap`] shape) does -/// not fit — the count being capped is over *every* user row, with no parent -/// record to hold it and no place to seed one without a backfill. -/// -/// **Lock order:** taken alone. Nothing is locked while it is held. -static ADMIN_FLOOR_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); - /// Typed user record id (`user:`). #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct UserId(RecordId); impl UserId { /// Minted from the process-wide monotonic generator, not `Ulid::new()`: - /// users list `id DESC` (newest first, [`User::list_all`]) and page by + /// users list `id DESC` (newest first, [`crate::db::user::list_all`]) and page by /// offset over that order, and a random low half scrambles rows minted in /// the same millisecond. Not a secret: the session token is separate /// (32-byte CSPRNG, `web::auth`), so id order carries no authority. @@ -224,35 +194,37 @@ impl PasswordHash { } #[derive(Debug, Clone, SurrealValue)] +/// Fields are crate-visible: [`crate::db::user`] mints rows and the role +/// cascade reads the id, exactly as the other split domains do. pub struct User { - id: UserId, - username: Username, - password_hash: PasswordHash, - role: Role, + pub(crate) id: UserId, + pub(crate) username: Username, + pub(crate) password_hash: PasswordHash, + pub(crate) role: Role, // Personal info, identical for every role. All optional: accounts are // created from bare credentials and filled in later, and rows from before // these fields existed simply read back as `None`. - name: Option, - surname: Option, - email: Option, - phone: Option, - birth_date: Option, + pub(crate) name: Option, + pub(crate) surname: Option, + pub(crate) email: Option, + pub(crate) phone: Option, + pub(crate) birth_date: Option, // Frontend UI preferences. Optional like the personal info: `None` means // "never chose", which the frontend renders as the device preference. - theme: Option, - language: Option, - palette_color: Option, + pub(crate) theme: Option, + pub(crate) language: Option, + pub(crate) palette_color: Option, // The public profile: what other people see instead of the credentials. // Optional like everything above — a profile is written after the account // exists, so rows from before these fields existed read back as `None`, // which is exactly a fresh account that never filled one in. The avatar is // a blob on disk (`FILES_PATH`) like every other upload; only its name, // type and size live on the row. - display_name: Option, - bio: Option, - avatar_file: Option, - avatar_content_type: Option, - avatar_size: Option, + pub(crate) display_name: Option, + pub(crate) bio: Option, + pub(crate) avatar_file: Option, + pub(crate) avatar_content_type: Option, + pub(crate) avatar_size: Option, } impl User { @@ -354,1003 +326,11 @@ impl User { self.avatar_size } - /// Register a new account. New users always start as [`Role::Student`]; - /// elevation is a separate, admin-only action (see [`User::set_role`]). - pub async fn create( - username: Username, - password_hash: PasswordHash, - db: &Database, - ) -> Result { - Self::create_with_role(username, password_hash, Role::Student, db).await - } - - /// The one row-minting path. `role` is written *with* the row rather than - /// patched on afterwards, which is what makes the admin seed atomic: a - /// create-then-promote pair can be interrupted between its halves (a SIGKILL, - /// or a cancelled future), and the row left behind is an ordinary student - /// account that [`User::ensure_admin`] must then refuse to touch — a - /// deployment with no admin and no way for a later boot to repair it. - pub async fn create_with_role( - username: Username, - password_hash: PasswordHash, - role: Role, - db: &Database, - ) -> Result { - if Self::find_by_username(username.as_str(), db) - .await? - .is_some() - { - return Err(AppError::Conflict("username already taken")); - } - let user = User { - id: UserId::generate(), - username, - password_hash, - role, - name: None, - surname: None, - email: None, - phone: None, - birth_date: None, - theme: None, - language: None, - palette_color: None, - display_name: None, - bio: None, - avatar_file: None, - avatar_content_type: None, - avatar_size: None, - }; - let created: Result, surrealdb::Error> = - db.create(user.id.record()).content(user.clone()).await; - match created { - Ok(Some(created)) => Ok(created), - Ok(None) => Err(AppError::Internal("failed to create user".into())), - // The availability pre-check above is not atomic with the insert: - // two concurrent registrations can both pass it, and the loser then - // trips the unique username index. That loss is the same condition - // as the sequential duplicate, so report the same 409 — not a 500. - Err(err) => { - if Self::find_by_username(user.username.as_str(), db) - .await? - .is_some() - { - Err(AppError::Conflict("username already taken")) - } else { - Err(err.into()) - } - } - } - } - - /// Idempotent startup seed: guarantee an admin account with this username. - /// Missing → created directly with [`Role::Admin`]. Already an admin → - /// nothing to do (the stored password stays whatever it is — the seed never - /// rewrites credentials). Taken by a non-admin → refuse to touch it and log - /// a warning: silently promoting an account someone else registered would - /// be a privilege escalation, so that conflict is resolved out-of-band. - pub async fn ensure_admin( - username: Username, - password: Password, - db: &Database, - ) -> Result<(), AppError> { - match Self::find_by_username(username.as_str(), db).await? { - Some(user) if user.role == Role::Admin => Ok(()), - Some(_) => { - tracing::warn!( - "ADMIN_USERNAME names an existing non-admin account; refusing to promote it. \ - Grant the role through an existing admin or the manual SurrealQL path." - ); - Ok(()) - } - None => { - // One statement, admin from birth. Never create-then-promote: - // an interruption between those two writes leaves a student row - // holding ADMIN_USERNAME, which the `Some(_)` arm above then - // refuses to promote — forever, on every subsequent boot. There - // is no marker that could tell such a row apart from a stranger - // who registered the name first, so the hole cannot be healed - // later; it has to be impossible to open. - Self::create_with_role(username, password.hash_async().await?, Role::Admin, db) - .await?; - // No `username` field: with OTLP on every event is exported as a - // log record, so an account name here leaves the process. - tracing::info!("seeded the admin account named by ADMIN_USERNAME"); - Ok(()) - } - } - } - - pub async fn read(id: &UserId, db: &Database) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - pub async fn list_all( - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new("user", "ORDER BY id DESC") - .run(limit, offset, db) - .await - } - - /// Fetch the users behind `ids` in one query. Ids with no row are simply - /// absent from the result — the caller decides how to degrade. - pub async fn list_by_ids(ids: &[UserId], db: &Database) -> Result, AppError> { - if ids.is_empty() { - return Ok(Vec::new()); - } - let records: Vec = ids.iter().map(UserId::record).collect(); - let mut result = db - .query("SELECT * FROM user WHERE id IN $ids") - .bind(("ids", records)) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Every user holding exactly `role` — e.g. the roster of a role-targeted - /// event. Exact match, not `at_least`: "all teachers" means teachers, not - /// managers and admins too. - pub async fn list_by_role(role: Role, db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM user WHERE role = $role ORDER BY id DESC") - .bind(("role", role)) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Would lowering `target` out of `admin` leave the school with none? Both - /// halves are asked of the **live** rows in one round trip: is that row an - /// admin right now, and does any other admin exist. It asks for one id per - /// half rather than a `count()` — a count over an indexed field compared - /// against a plan-time value answers `{count: N}` on the real server, and - /// neither half needs a number. - async fn would_orphan_admins(target: &UserId, db: &Database) -> Result { - let mut result = db - .query( - "SELECT VALUE id FROM user WHERE id = $usr AND role = $role;\n\ - SELECT VALUE id FROM user WHERE role = $role AND id != $usr LIMIT 1", - ) - .bind(("role", Role::Admin)) - .bind(("usr", target.record())) - .await? - .check()?; - let is_admin = !result.take::>(0)?.is_empty(); - let others = !result.take::>(1)?.is_empty(); - Ok(is_admin && !others) - } - - /// Case- and diacritic-insensitive fragment search over username, name, - /// and surname. Needle and columns both go through - /// [`crate::domain::text_fold`], so `ilker` finds `İLKER` and back — - /// backs the user pickers. `role` narrows to one role (e.g. only students - /// for an enroll picker); `None` searches everyone. `allowed_roles` - /// narrows the *visible* set (the roles a non-staff caller may message — - /// see [`Role::messageable_roles`]); it is part of the query, not a - /// post-filter, so `total` counts only what the caller may see. A blank - /// `query` - /// matches everyone, so blank + `role` is a role-scoped listing. Returns - /// every match, ordered by username; the HTTP layer pages the result like - /// any other list (no built-in cap — an over-broad fragment is windowed - /// by `?limit`). - pub async fn search( - query: &str, - role: Option, - allowed_roles: Option<&[Role]>, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - let needle = search_fold(query.trim()); - let text_clause = format!( - "({} CONTAINS $q OR {} CONTAINS $q OR {} CONTAINS $q)", - search_fold_sql("username"), - search_fold_sql("name ?? ''"), - search_fold_sql("surname ?? ''"), - ); - let mut clauses = Vec::new(); - if !needle.is_empty() { - clauses.push(text_clause.as_str()); - } - if role.is_some() { - clauses.push("role = $role"); - } - if allowed_roles.is_some() { - clauses.push("role IN $allowed"); - } - let where_clause = if clauses.is_empty() { - "true".to_string() - } else { - clauses.join(" AND ") - }; - let mut list = PagedList::new(format!("user WHERE {where_clause}"), "ORDER BY username") - .bind("q", needle); - if let Some(role) = role { - list = list.bind("role", role); - } - if let Some(allowed) = allowed_roles { - list = list.bind("allowed", allowed.to_vec()); - } - list.run(limit, offset, db).await - } - - /// Overwrite this user's role **and** shed every grant the new role may not - /// hold, in one transaction. The caller is responsible for authorizing it. - /// - /// Refuses (`Conflict`) to lower the school's last admin, however the - /// request is spelled and however many demotions are in flight at once — - /// see [`ADMIN_FLOOR_LOCK`] for why that guard cannot live in the - /// transaction below. - /// - /// Writes *only* the `role` field of the user row (never the whole row): - /// the row mixes admin-owned (role) and self-service (profile, preferences) - /// fields, and each writer starts from a snapshot read at request start. A - /// whole-row write would carry the snapshot's copy of the *other* group back - /// over a concurrent edit — an in-flight profile save silently reverting an - /// admin's demotion, or this write erasing a profile edit that raced it. - /// [`User::set_profile`] and [`User::set_preferences`] are scoped for the - /// same reason. - /// - /// One transaction and not eight statements, which is what this used to be: - /// a sweep that errored answered 500 with the role already lowered and some - /// of the old grants still standing — exactly the state the sweeps exist to - /// prevent, and a crash between them left it with nobody to answer to. - /// Nothing here is a security hole either way (every gate re-reads the live - /// role, `web::mod`), but the residue pollutes rosters, counts and signup - /// lists, and one of those, the event seat, nothing could ever free again. - /// - /// What is swept, and why the conditions differ: - /// - /// * **Non-student** sheds class memberships, *every* enrollment row - /// (hand-placed ones included — only students enroll, and a kept row - /// would grant nothing and count a seat) and the parent links observing - /// them. Memberships and enrollments were already one transaction and - /// still are: released apart, an enrollment row could be left tagged with - /// a class whose counters had been given back, so the class passed its - /// zero-zero delete guard and no sweep could ever reach the row again. - /// * **Parent** additionally frees event seats, comes off every whiteboard - /// roster and has the boards they *created* closed — permanently - /// read-only, rows kept, because a room whose creator is demoted is - /// commandable by nobody at all (see the statement's own note). The seat - /// is the one thing on a signup list nothing - /// else could remove: staff free their own by hand (`unregister` allows - /// the self case) but a parent can reach no such door, so a promotion - /// strands nothing and only this demotion does. A list that has already - /// **frozen** ([`REGISTRATION_FROZEN_GUARD`]) is left exactly as it - /// stands — past the freeze it is historical record, re-registering - /// answers 409, and rewriting it here would be irrecoverable. A signup - /// whose event record is *gone* has no seat to hand back and no list that - /// can freeze, so it is deleted rather than skipped: skipped, it is - /// stranded forever (`unregister` 404s on the missing event). - /// * **Below teacher** gives up course staffing and homeroom-teacher - /// columns — only teacher+ may hold either — and the published - /// appointment calendar, whose live bookings are cancelled in the same - /// breath. Nothing else could ever reach those: a slot is listed only on - /// its own teacher's calendar and deleted only by a teacher+, so after the - /// demotion neither its owner nor a manager has a route that yields its - /// id, and a booking on it can be neither decided (teacher+ only) nor - /// cancelled once its window opens — leaving the slot's `occupied` seat - /// pinned at one and the slot itself undeletable forever. The requester - /// keeps the row, `cancelled`, with the teacher on `cancelled_by` and the - /// reason on `cancel_reason`; the slot it pointed at is gone, so the - /// booking renders without a window - /// ([`crate::domain::appointment::Appointment`]'s reader already treats a - /// vanished slot that way). There is no notification anywhere in - /// this crate, so a settled row the person can read is the strongest - /// defined end available — and the alternative, deleting it, would make a - /// confirmed meeting vanish with no trace at all. - /// - /// The returned boards are the rooms whose roster this changed, plus those - /// the user created — whose roster is untouched but which are now closed, - /// and they carry that stamp because the close is written first. Publishing - /// to them is the caller's job: an in-process - /// fan-out cannot sit inside a database transaction, and a room told before - /// the commit would re-read the pre-commit state. - /// - /// Admissible for [`transaction_with_retry`] by construction: `SELECT`, - /// `UPDATE` and `DELETE` only, so no statement can answer "already exists" - /// and every lost round is a plain re-send. - pub async fn set_role(self, role: Role, db: &Database) -> Result<(User, Vec), AppError> { - // The admin floor, held from the count to the commit ([`ADMIN_FLOOR_LOCK`] - // for why a transaction cannot do this). Asked on the *live* rows rather - // than `self.role`, so a snapshot that predates a promotion cannot skip - // the check, and cheap enough to ask on every demotion: one round trip - // on an admin-only route. - let _floor = if role == Role::Admin { - None - } else { - let guard = ADMIN_FLOOR_LOCK.lock().await; - if Self::would_orphan_admins(&self.id, db).await? { - return Err(AppError::Conflict( - "the school must keep at least one admin — promote another account first", - )); - } - Some(guard) - }; - // Built as a statement list rather than one string so the result slot - // of the board write is *counted*, not hand-tallied against arms that - // may or may not be in the batch. Slot 0 is `BEGIN`, as everywhere. - let mut batch = vec![ - "BEGIN TRANSACTION".to_string(), - "UPDATE $usr SET role = $role RETURN AFTER".to_string(), - ]; - if role != Role::Student { - batch.push(format!( - "LET $links = (DELETE {CLASS_MEMBER_TABLE} WHERE user = $usr RETURN BEFORE)" - )); - batch.push(format!( - "FOR $link IN ($links ?? []) {{ UPDATE $link.class SET \ - {CLASS_MEMBER_COUNT_FIELD} = \ - math::max([({CLASS_MEMBER_COUNT_FIELD} ?? 0) - 1, 0]); }}" - )); - batch.push(format!( - "LET $rows = (DELETE {ENROLLMENT_TABLE} WHERE user = $usr RETURN BEFORE)" - )); - batch.push(format!( - "FOR $row IN ($rows ?? []) {{ UPDATE $row.course SET \ - {ENROLLMENT_COUNT_FIELD} = \ - math::max([({ENROLLMENT_COUNT_FIELD} ?? 0) - 1, 0]); }}" - )); - batch.push(format!("DELETE {PARENT_LINK_TABLE} WHERE student = $usr")); - } - let mut board_slot = None; - if role == Role::Parent { - batch.push(format!( - "LET $signups = (SELECT * FROM {REGISTRATION_TABLE} WHERE user = $usr)" - )); - // Row and seat move together per signup, the way `unregister` does: - // the seats are independent facts on unrelated events. A missing - // event matches nothing in the guard *and* nothing in the counter - // write, which is precisely the orphan rule. - batch.push(format!( - "FOR $signup IN ($signups ?? []) {{ \ - IF array::len((SELECT VALUE id FROM $signup.event \ - WHERE {REGISTRATION_FROZEN_GUARD})) = 0 {{ \ - LET $freed = (DELETE $signup.id RETURN BEFORE); \ - UPDATE $signup.event SET {REGISTRATION_COUNT_FIELD} = \ - math::max([({REGISTRATION_COUNT_FIELD} ?? 0) - array::len($freed), 0]); \ - }}; }}" - )); - // A room whose *creator* is demoted can never be ended by anyone: - // the whiteboard is closed to parents outright, so the creator is - // 404'd off their own board, `clear`/`lock`/`close`/`delete` are - // creator-only for everyone else, and `Board::list_for_user` is the - // crate's only enumeration — no manager or admin can so much as find - // the id. Its participants meanwhile keep drawing (the room re-derives - // membership per frame and they still pass), into a board only the - // 50 000-stroke lifetime cap could ever retire. So the demotion - // retires it, with the same compare-and-set [`Board::close`] uses: an - // already-closed board keeps its first stamp. Closed and not deleted - // because the marks are the participants' work too — they keep reading - // the board and its whole history, and the creator's `board_count` - // seat stays taken, which is correct while the row it counts exists. - // Stamped *before* the roster strip so the strip's `RETURN AFTER` - // carries the closed row the caller fans out. - batch.push(format!( - "UPDATE {BOARD_TABLE} SET closed_at = $now WHERE creator = $usr AND closed_at = NONE" - )); - board_slot = Some(batch.len()); - batch.push(format!( - "UPDATE {BOARD_TABLE} SET participants -= $usr \ - WHERE $usr IN participants OR creator = $usr RETURN AFTER" - )); - } - if role != Role::Parent { - batch.push(format!("DELETE {PARENT_LINK_TABLE} WHERE parent = $usr")); - } - if !role.at_least(Role::Teacher) { - batch.push(format!( - "UPDATE {COURSE_TABLE} SET teachers -= $usr WHERE $usr IN teachers" - )); - batch.push(format!( - "UPDATE {CLASS_GROUP_TABLE} SET teacher = NONE WHERE teacher = $usr" - )); - // The published calendar goes too, and the bookings on it are - // settled first: a slot only its own teacher can list and only a - // teacher+ can delete is reachable by nobody once that teacher is - // demoted, and a live booking on one is worse — nobody can approve, - // reject or (past its start) cancel it, so it pins the slot's - // `occupied` seat forever. Cancelled rather than deleted so the - // person who asked is left with a settled booking they can still - // read, carrying who dropped it and why; the slot row (and with it - // the seat) goes, which is what makes this convergent. - batch.push(format!( - "LET $slots = (SELECT VALUE id FROM {APPOINTMENT_SLOT_TABLE} WHERE teacher = $usr)" - )); - batch.push(format!( - "UPDATE {APPOINTMENT_TABLE} SET status = '{cancelled}', cancelled_by = $usr, \ - cancel_reason = 'the teacher no longer holds a teaching role' \ - WHERE slot IN $slots AND status IN ['{pending}', '{approved}']", - cancelled = AppointmentStatus::Cancelled.as_str(), - pending = AppointmentStatus::Pending.as_str(), - approved = AppointmentStatus::Approved.as_str(), - )); - // Deleting the slots is also what makes a *concurrent* booking safe: - // `Appointment::book` claims the slot row this deletes, so the two - // collide in the store and the loser re-sends. A slot *published* - // concurrently shares no key with any of this, which is why - // `AppointmentSlot::insert_claimed` claims the user row instead. - batch.push(format!( - "DELETE {APPOINTMENT_SLOT_TABLE} WHERE id IN $slots" - )); - } - let sql = format!("{};\nCOMMIT TRANSACTION;", batch.join(";\n")); - let (mut result, mut errors) = transaction_with_retry( - db, - &sql, - &[ - ("usr".into(), self.id.record().into_value()), - ("role".into(), role.into_value()), - ("now".into(), Timestamp::now().as_millis().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - let updated = result - .take::>(1)? - .into_iter() - .next() - .ok_or(AppError::NotFound)?; - let boards = match board_slot { - Some(slot) => result.take::>(slot)?, - None => Vec::new(), - }; - Ok((updated, boards)) - } - - /// Write the personal-info and public-profile fields the request actually - /// carried — everything a person edits about themselves except the avatar - /// blob, which needs its own writer ([`User::set_avatar`]). Every - /// column is nullable, so each argument is an outer/inner `Option`: `None` - /// = omitted (not written at all), `Some(None)` = cleared, `Some(Some(v))` - /// = set. Merging the request against the current row is the HTTP layer's - /// job; the caller authorizes. - /// - /// Request-scoped, not merely field-scoped: nothing guards the row across - /// the handler's read and this write, so re-sending the snapshot's value - /// for an omitted field would revert a concurrent PATCH of that field — - /// two profile edits (a name and a phone) used to lose each other. See - /// [`User::set_role`] for why no writer here touches the whole row. - // One argument per nullable column is the point: folding them into a struct - // would just re-spell the HTTP DTO here and cost the compiler's check that - // every column was considered at the call site. - #[allow(clippy::too_many_arguments)] - pub async fn set_profile( - self, - name: Option>, - surname: Option>, - email: Option>, - phone: Option>, - birth_date: Option>, - display_name: Option>, - bio: Option>, - db: &Database, - ) -> Result { - FieldUpdate::new(self.id.record()) - .set("name", name) - .set("surname", surname) - .set("email", email) - .set("phone", phone) - .set("birth_date", birth_date) - .set("display_name", display_name) - .set("bio", bio) - .run::(db) - .await - } - - /// Point the row at a freshly uploaded avatar blob, returning the row *as - /// it was* — the caller deletes `before.get_avatar_file()` off disk. Losing - /// `RETURN BEFORE` here strands the replaced blob forever: no route ever - /// deletes a user, so nothing else would collect it. - /// - /// Field-scoped for the same reason as [`User::set_profile`]: an avatar - /// upload must not carry a stale snapshot's role back over an admin's - /// change. `None` means the row is gone. - /// - /// Sent through [`write_with_retry`] like every other single-statement row - /// write here, unguarded or not: the user row is contended (preferences, - /// profile, role all write it), and a lost round wrote nothing, so - /// re-sending it is the recovery rather than a 500 in the caller's face. - pub async fn set_avatar( - id: &UserId, - file: &str, - content_type: &FileContentType, - size: i64, - db: &Database, - ) -> Result, AppError> { - let rows: Vec = write_with_retry( - db, - "UPDATE $u SET avatar_file = $file, avatar_content_type = $ct, avatar_size = $size \ - RETURN BEFORE", - &[ - ("u".into(), id.record().into_value()), - ("file".into(), file.to_string().into_value()), - ("ct".into(), content_type.clone().into_value()), - ("size".into(), size.into_value()), - ], - ) - .await?; - Ok(rows.into_iter().next()) - } - - /// Drop the avatar, returning the row as it was so the caller can delete - /// the blob. Same `RETURN BEFORE` contract as [`User::set_avatar`]. - pub async fn clear_avatar(id: &UserId, db: &Database) -> Result, AppError> { - let rows: Vec = write_with_retry( - db, - "UPDATE $u SET avatar_file = NONE, avatar_content_type = NONE, \ - avatar_size = NONE RETURN BEFORE", - &[("u".into(), id.record().into_value())], - ) - .await?; - Ok(rows.into_iter().next()) - } - - /// Replace a user's password hash — the builder's admin-password reset - /// (`POST /schools/{slug}/admin-password`). Only the credential is - /// rewritten; revoking the sessions minted under the old one is the - /// caller's second half - /// ([`crate::db::session::delete_by_user`]), because a reset - /// that leaves a stolen cookie working resets nothing. - pub async fn set_password_hash( - id: &UserId, - password_hash: PasswordHash, - db: &Database, - ) -> Result, AppError> { - let rows: Vec = write_with_retry( - db, - "UPDATE $u SET password_hash = $hash RETURN AFTER", - &[ - ("u".into(), id.record().into_value()), - ("hash".into(), password_hash.into_value()), - ], - ) - .await?; - Ok(rows.into_iter().next()) - } - - /// Write the UI-preference fields the request actually carried. Same - /// contract as [`User::set_profile`]: `None` = omitted (not written), - /// `Some(None)` = cleared back to "never chose", `Some(Some(v))` = set. - pub async fn set_preferences( - self, - theme: Option>, - language: Option>, - palette_color: Option>, - db: &Database, - ) -> Result { - FieldUpdate::new(self.id.record()) - .set("theme", theme) - .set("language", language) - .set("palette_color", palette_color) - .run::(db) - .await - } - - pub async fn find_by_username(username: &str, db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM user WHERE username = $username LIMIT 1") - .bind(("username", username.to_string())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) - } } #[cfg(test)] mod tests { use super::*; - use crate::database::init_mem; - - /// The board result slot is an *index* into a batch whose length depends on - /// which arms the role selected, so it is the one number in the cascade a - /// silent mistake would not show up in the store: pointed at the wrong - /// statement it yields an empty list, and every whiteboard room whose roster - /// just changed is simply never told. Assert the rows come back. - #[tokio::test] - async fn the_cascade_returns_the_boards_it_stripped() { - use crate::domain::board::{Board, BoardTitle}; - - let db = init_mem().await.unwrap(); - let creator = User::create( - Username::try_new("ogretmen").unwrap(), - Password::try_new("secret1").unwrap().hash().unwrap(), - &db, - ) - .await - .unwrap(); - let guest = User::create( - Username::try_new("ogrenci").unwrap(), - Password::try_new("secret1").unwrap().hash().unwrap(), - &db, - ) - .await - .unwrap(); - let board = Board::create( - creator.get_id(), - BoardTitle::try_new("Geometri").unwrap(), - vec![guest.get_id().clone()], - &db, - ) - .await - .unwrap(); - - // A promotion touches no roster and must report none. - let (guest, boards) = guest.set_role(Role::Teacher, &db).await.unwrap(); - assert!( - boards.is_empty(), - "only a demotion to parent strips rosters" - ); - - let (_, boards) = guest.set_role(Role::Parent, &db).await.unwrap(); - assert_eq!(boards.len(), 1, "the stripped room must be reported back"); - assert_eq!(boards[0].get_id(), board.get_id()); - assert!( - boards[0].get_participants().is_empty(), - "and carry the roster the room is about to be told about" - ); - } - - /// The half the roster strip cannot reach: the board's **creator**. Demoted, - /// they are 404'd off their own room, every command on it is creator-only - /// for everyone else, and nothing in the crate lists a board a caller is not - /// on — so the room could be cleared, locked, closed and deleted by nobody - /// while its participants kept drawing on it. The demotion closes it, and - /// closing is *all* it does: the roster, the row and every mark stay - /// readable. - #[tokio::test] - async fn a_demoted_creator_s_board_is_closed_and_still_readable() { - use crate::domain::board::{Board, BoardTitle}; - use crate::domain::board_stroke::{BOARD_CLOSED, BoardStroke}; - - let db = init_mem().await.unwrap(); - let creator = a_user("ogretmen", &db).await; - let guest = a_user("ogrenci", &db).await; - let board = Board::create( - creator.get_id(), - BoardTitle::try_new("Geometri").unwrap(), - vec![guest.get_id().clone()], - &db, - ) - .await - .unwrap(); - let mark = |epoch| { - let (id, author, db) = (board.get_id().clone(), guest.get_id().clone(), db.clone()); - async move { BoardStroke::append(&id, &author, "{\"p\":[1]}", epoch, &db).await } - }; - mark(0).await.unwrap(); - - let (creator, boards) = creator.set_role(Role::Parent, &db).await.unwrap(); - assert_eq!(boards.len(), 1, "the room must be reported back"); - let stamp = boards[0] - .get_closed_at() - .expect("and carry the closing stamp the room is told about"); - - // Stored, not merely reported — and nothing else moved. - let stored = Board::read(board.get_id(), &db).await.unwrap().unwrap(); - assert_eq!(stored.get_closed_at(), Some(stamp)); - assert_eq!( - stored.get_participants(), - [guest.get_id().clone()], - "closing must not empty the roster it did not touch" - ); - assert_eq!( - BoardStroke::history(board.get_id(), None, false, None, 0, &db) - .await - .unwrap() - .1, - 1, - "the marks the participants drew stay on disk" - ); - - // Read-only for the participants who are still on it. - assert!( - matches!(mark(0).await, Err(AppError::Conflict(BOARD_CLOSED))), - "a closed board must refuse every write with the terminal answer" - ); - - // The stamp is the record: a re-run of the sweep must not move it. - tokio::time::sleep(std::time::Duration::from_millis(2)).await; - creator.set_role(Role::Parent, &db).await.unwrap(); - assert_eq!( - Board::read(board.get_id(), &db) - .await - .unwrap() - .unwrap() - .get_closed_at(), - Some(stamp), - "the close is a compare-and-set, not a re-stamp" - ); - } - - /// A demotion below `teacher` must take the published calendar with it and - /// settle the bookings on it. Nothing else can: a slot is listed only on its - /// own teacher's calendar (and hidden from every other reader once its owner - /// is demoted), deleted only by a teacher+, and a booking on one can be - /// decided only by a teacher+ and cancelled only by its requester — who is - /// refused the moment the window opens. So a slot left behind here is a row - /// no route can reach and a seat nothing can ever free. - #[tokio::test] - async fn a_demotion_withdraws_the_calendar_and_settles_its_bookings() { - use crate::domain::appointment::AppointmentReason; - use crate::domain::appointment_slot::AppointmentSlot; - use crate::service::appointment; - - let db = init_mem().await.unwrap(); - let staff = |name: &'static str, db: Database| async move { - a_user(name, &db) - .await - .set_role(Role::Teacher, &db) - .await - .unwrap() - .0 - }; - let teacher = staff("ogretmen", db.clone()).await; - let other = staff("digerogretmen", db.clone()).await; - let student = a_user("ogrenci", &db).await; - let soon = |offset| Timestamp::from_millis(Timestamp::now().as_millis() + offset); - let reason = || AppointmentReason::try_new("görüşme").unwrap(); - let slot = |owner: &User, offset: i64, db: Database| { - let owner = owner.get_id().clone(); - async move { - AppointmentSlot::create(&owner, soon(offset), soon(offset + 60_000), None, &db) - .await - .unwrap() - } - }; - - let free = slot(&teacher, 60_000, db.clone()).await; - let asked = slot(&teacher, 180_000, db.clone()).await; - let agreed = slot(&teacher, 300_000, db.clone()).await; - let kept = slot(&other, 60_000, db.clone()).await; - - let pending = appointment::book(&db, asked.get_id(), student.get_id(), reason()) - .await - .unwrap(); - let approved = appointment::book(&db, agreed.get_id(), student.get_id(), reason()) - .await - .unwrap(); - appointment::approve(&db, approved.get_id(), teacher.get_id()) - .await - .unwrap(); - let elsewhere = appointment::book(&db, kept.get_id(), student.get_id(), reason()) - .await - .unwrap(); - - teacher.clone().set_role(Role::Student, &db).await.unwrap(); - - // The calendar is gone, the booked weeks included. - assert!( - AppointmentSlot::list_for_teacher(teacher.get_id(), &db) - .await - .unwrap() - .is_empty() - ); - for slot in [&free, &asked, &agreed] { - assert!( - AppointmentSlot::read(slot.get_id(), &db) - .await - .unwrap() - .is_none(), - "a slot only a teacher+ could reach outlived the role" - ); - } - // Both bookings — the pending request and the confirmed meeting — ended - // in a state their requester can still read, saying who dropped it. - for booking in [&pending, &approved] { - let after = appointment::read(&db, booking.get_id()) - .await - .unwrap() - .expect("the requester keeps the row"); - assert_eq!(after.get_status(), AppointmentStatus::Cancelled); - assert_eq!(after.get_cancelled_by(), Some(teacher.get_id())); - assert!(after.get_cancel_reason().is_some(), "and why"); - } - // The seat each held died with its slot row, so nothing is pinned: no - // live booking is left pointing at a slot that no longer exists. - let mut result = db - .query( - "SELECT VALUE id FROM appointment \ - WHERE status IN ['pending', 'approved'] AND slot.starts_at = NONE", - ) - .await - .unwrap() - .check() - .unwrap(); - assert!(result.take::>(0).unwrap().is_empty()); - - // Another teacher's calendar is nobody else's business. - assert_eq!( - AppointmentSlot::list_for_teacher(other.get_id(), &db) - .await - .unwrap() - .len(), - 1 - ); - assert_eq!( - appointment::read(&db, elsewhere.get_id()) - .await - .unwrap() - .unwrap() - .get_status(), - AppointmentStatus::Pending - ); - } - - #[tokio::test] - async fn a_stale_profile_write_cannot_revert_a_role_change() { - let db = init_mem().await.unwrap(); - let user = User::create( - Username::try_new("aysenur").unwrap(), - Password::try_new("secret1").unwrap().hash().unwrap(), - &db, - ) - .await - .unwrap(); - - // A PATCH /users/me handler reads its snapshot (role = student)... - let stale = User::read(user.get_id(), &db).await.unwrap().unwrap(); - - // ...then an admin's role change commits before the profile save runs. - User::read(user.get_id(), &db) - .await - .unwrap() - .unwrap() - .set_role(Role::Teacher, &db) - .await - .unwrap(); - - // The in-flight save lands from the stale snapshot. It must write only - // the profile fields — not carry the snapshot's old role back over the - // admin's change. - let name = PersonName::try_new("name", "Ayşenur").unwrap(); - stale - .set_profile( - Some(Some(name.clone())), - None, - None, - None, - None, - None, - None, - &db, - ) - .await - .unwrap(); - - let after = User::read(user.get_id(), &db).await.unwrap().unwrap(); - assert_eq!( - after.get_role(), - Role::Teacher, - "the role change must survive the racing profile write" - ); - assert_eq!( - after.get_name(), - Some(&name), - "the profile edit itself lands" - ); - } - - fn png() -> FileContentType { - FileContentType::try_new("image/png").unwrap() - } - - async fn a_user(username: &str, db: &Database) -> User { - User::create( - Username::try_new(username).unwrap(), - Password::try_new("secret1").unwrap().hash().unwrap(), - db, - ) - .await - .unwrap() - } - - #[tokio::test] - async fn an_avatar_upload_cannot_revert_a_role_change() { - let db = init_mem().await.unwrap(); - let user = a_user("berk", &db).await; - - // The upload handler holds its snapshot (role = student)... - let stale = User::read(user.get_id(), &db).await.unwrap().unwrap(); - - // ...an admin promotes and the person edits their bio, both while the - // blob is still being written... - User::read(user.get_id(), &db) - .await - .unwrap() - .unwrap() - .set_role(Role::Teacher, &db) - .await - .unwrap(); - let display_name = DisplayName::try_new("Berk").unwrap(); - User::read(user.get_id(), &db) - .await - .unwrap() - .unwrap() - .set_profile( - None, - None, - None, - None, - None, - Some(Some(display_name.clone())), - None, - &db, - ) - .await - .unwrap(); - - // ...and only then does the avatar land, from the stale row's id. - User::set_avatar(stale.get_id(), "blob-1", &png(), 42, &db) - .await - .unwrap() - .expect("the row exists"); - - let after = User::read(user.get_id(), &db).await.unwrap().unwrap(); - assert_eq!( - after.get_role(), - Role::Teacher, - "the role change must survive the racing avatar write" - ); - assert_eq!( - after.get_display_name(), - Some(&display_name), - "and so must every other column the avatar write never named" - ); - assert_eq!(after.get_avatar_file(), Some("blob-1")); - assert_eq!(after.get_avatar_content_type(), Some(&png())); - assert_eq!(after.get_avatar_size(), Some(42)); - } - - /// The blob cleanup is built entirely on `RETURN BEFORE`: without the old - /// `avatar_file` coming back, every replace strands a file on disk that no - /// route ever collects. - #[tokio::test] - async fn the_avatar_writers_return_the_replaced_blob() { - let db = init_mem().await.unwrap(); - let user = a_user("ceyda", &db).await; - - let before = User::set_avatar(user.get_id(), "blob-1", &png(), 10, &db) - .await - .unwrap() - .expect("the row exists"); - assert_eq!(before.get_avatar_file(), None, "no blob to collect yet"); - - let before = User::set_avatar(user.get_id(), "blob-2", &png(), 20, &db) - .await - .unwrap() - .expect("the row exists"); - assert_eq!( - before.get_avatar_file(), - Some("blob-1"), - "the replaced blob is what the caller must delete" - ); - - let before = User::clear_avatar(user.get_id(), &db) - .await - .unwrap() - .expect("the row exists"); - assert_eq!(before.get_avatar_file(), Some("blob-2")); - - let after = User::read(user.get_id(), &db).await.unwrap().unwrap(); - assert_eq!(after.get_avatar_file(), None); - assert_eq!(after.get_avatar_content_type(), None); - assert_eq!(after.get_avatar_size(), None); - - assert!( - User::clear_avatar(&UserId::from_key("yok"), &db) - .await - .unwrap() - .is_none(), - "a missing row is None, not an error" - ); - } #[tokio::test] async fn username_newtype_validates() { diff --git a/src/service/course.rs b/src/service/course.rs index 31018fe..4862a7e 100644 --- a/src/service/course.rs +++ b/src/service/course.rs @@ -13,7 +13,7 @@ use crate::domain::homework_file::HomeworkFile; use crate::domain::question_image::QuestionImage; use crate::domain::term::{self, TermId}; use crate::domain::role::Role; -use crate::domain::user::{User, UserId}; +use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; /// Refuse the write when this course's term is archived — a pre-flight guard, @@ -90,7 +90,7 @@ pub async fn assign_teacher( target: &UserId, ) -> Result { require_open(db, course).await?; - let Some(target_user) = User::read(target, db).await? else { + let Some(target_user) = crate::db::user::read(db, target).await? else { return Err(AppError::Validation(ValidationError::Invalid { field: "user_id", reason: "target user does not exist", diff --git a/src/service/exam_attempt.rs b/src/service/exam_attempt.rs index 70c965d..1c6e9f2 100644 --- a/src/service/exam_attempt.rs +++ b/src/service/exam_attempt.rs @@ -86,7 +86,7 @@ pub fn ensure_student(user: &User) -> Result<(), AppError> { /// save — the room's door check is not the last word for a socket that /// outlives the role. pub async fn ensure_student_now(user: &UserId, db: &Database) -> Result<(), AppError> { - let user = crate::domain::user::User::read(user, db) + let user = crate::db::user::read(db, user) .await? .ok_or(AppError::Unauthorized)?; ensure_student(&user) @@ -568,10 +568,10 @@ mod tests { .hash_async() .await .unwrap(); - crate::domain::user::User::create( + crate::db::user::create( + db, crate::domain::user::Username::try_new("ogrenci").unwrap(), hash, - db, ) .await .unwrap() diff --git a/src/service/mod.rs b/src/service/mod.rs index 892e3cd..e0b3042 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -8,3 +8,4 @@ pub mod note; pub mod payment_ledger; pub mod session; pub mod settings; +pub mod user; diff --git a/src/service/user.rs b/src/service/user.rs new file mode 100644 index 0000000..be4b125 --- /dev/null +++ b/src/service/user.rs @@ -0,0 +1,477 @@ +//! User workflows: the boot-time admin seed, and the role change — the +//! admin floor ([`ADMIN_FLOOR_LOCK`]) held across the count that checks it +//! and the transaction that commits it, sweeps included. Reads, listings, +//! the row mint, and the field-scoped writers live in [`crate::db::user`]. + +use crate::database::Database; +use crate::db::user; +use crate::domain::board::Board; +use crate::domain::note_file::FileContentType; +use crate::domain::preferences::{Language, PaletteColor, Theme}; +use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; +use crate::domain::role::Role; +use crate::domain::user::{Password, PasswordHash, User, UserId, Username}; +use crate::error::AppError; + +/// One role demotion at a time, school-wide. +/// +/// The invariant it protects is "the school always keeps an admin", and that +/// guard is a count-then-write: read whether another admin exists, then lower +/// this row. SurrealDB conflict-checks neither side of that pair — a +/// `BEGIN…COMMIT` does not serialize a cross-record count against a concurrent +/// update (write-skew, see [`crate::db::cap`]) and a statement that only +/// *reads* the rival's row never collides with it. So two admins demoting each +/// other both counted the other and both committed, leaving **zero** admins and +/// a school nobody can administer: `ensure_admin` refuses to promote an +/// existing non-admin row on every later boot, so the only way back was hand-run +/// SurrealQL against the volume. +/// +/// Serializing the pair is what closes it, the same argument +/// [`crate::service::settings::SETTINGS_LOCK`] makes one level up: the deployment +/// runs one process by contract (stop-the-world upgrades), so process-wide is +/// deployment-wide. A per-row counter (the [`crate::db::cap`] shape) does +/// not fit — the count being capped is over *every* user row, with no parent +/// record to hold it and no place to seed one without a backfill. +/// +/// **Lock order:** taken alone. Nothing is locked while it is held. +static ADMIN_FLOOR_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +/// Idempotent startup seed: guarantee an admin account with this username. +/// Missing → created directly with [`Role::Admin`]. Already an admin → +/// nothing to do (the stored password stays whatever it is — the seed never +/// rewrites credentials). Taken by a non-admin → refuse to touch it and log +/// a warning: silently promoting an account someone else registered would +/// be a privilege escalation, so that conflict is resolved out-of-band. +pub async fn ensure_admin( + db: &Database, + username: Username, + password: Password, +) -> Result<(), AppError> { + match user::find_by_username(db, username.as_str()).await? { + Some(user) if user.role == Role::Admin => Ok(()), + Some(_) => { + tracing::warn!( + "ADMIN_USERNAME names an existing non-admin account; refusing to promote it. \ + Grant the role through an existing admin or the manual SurrealQL path." + ); + Ok(()) + } + None => { + // One statement, admin from birth. Never create-then-promote: + // an interruption between those two writes leaves a student row + // holding ADMIN_USERNAME, which the `Some(_)` arm above then + // refuses to promote — forever, on every subsequent boot. There + // is no marker that could tell such a row apart from a stranger + // who registered the name first, so the hole cannot be healed + // later; it has to be impossible to open. + user::create_with_role(db, username, password.hash_async().await?, Role::Admin) + .await?; + // No `username` field: with OTLP on every event is exported as a + // log record, so an account name here leaves the process. + tracing::info!("seeded the admin account named by ADMIN_USERNAME"); + Ok(()) + } + } +} + +/// Overwrite this user's role **and** shed every grant the new role may not +/// hold, in one transaction. The caller is responsible for authorizing it. +/// +/// Refuses (`Conflict`) to lower the school's last admin, however the +/// request is spelled and however many demotions are in flight at once — +/// see [`ADMIN_FLOOR_LOCK`] for why that guard cannot live in the +/// transaction below. +/// +/// The sweep itself — what each role change owes, arm by arm, and why the +/// conditions differ — is [`user::set_role_cascade`]'s statement list, +/// documented there. +pub async fn set_role( + db: &Database, + target: &UserId, + role: Role, +) -> Result<(User, Vec), AppError> { + // A missing account is a 404, answered before the floor is asked. + user::read(db, target).await?.ok_or(AppError::NotFound)?; + // The admin floor, held from the count to the commit ([`ADMIN_FLOOR_LOCK`] + // for why a transaction cannot do this). Asked on the *live* rows rather + // than a caller's snapshot, so a snapshot that predates a promotion cannot + // skip the check, and cheap enough to ask on every demotion: one round + // trip on an admin-only route. + let _floor = if role == Role::Admin { + None + } else { + let guard = ADMIN_FLOOR_LOCK.lock().await; + if user::would_orphan_admins(db, target).await? { + return Err(AppError::Conflict( + "the school must keep at least one admin — promote another account first", + )); + } + Some(guard) + }; + user::set_role_cascade(db, target, role).await +} + +/// Register a new account — the web layer's row mint. New users always start +/// as [`Role::Student`]; elevation is a separate, admin-only action +/// (see [`set_role`]). +pub async fn create( + db: &Database, + username: Username, + password_hash: PasswordHash, +) -> Result { + user::create(db, username, password_hash).await +} + +/// Mint a row holding `role` outright — the school-creation path, whose +/// first account must be an admin from birth. +pub async fn create_with_role( + db: &Database, + username: Username, + password_hash: PasswordHash, + role: Role, +) -> Result { + user::create_with_role(db, username, password_hash, role).await +} + +/// One user row, for callers that only inspect it — the web layer's reads go +/// through here. +pub async fn read(db: &Database, id: &UserId) -> Result, AppError> { + user::read(db, id).await +} + +/// Every account, newest first — the web layer's paging read. +pub async fn list_all( + db: &Database, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + user::list_all(db, limit, offset).await +} + +/// The users behind `ids` in one query; missing ids simply absent. +pub async fn list_by_ids(db: &Database, ids: &[UserId]) -> Result, AppError> { + user::list_by_ids(db, ids).await +} + +/// Username/name/surname fragment search — the pickers' backing read. +pub async fn search( + db: &Database, + query: &str, + role: Option, + allowed_roles: Option<&[Role]>, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + user::search(db, query, role, allowed_roles, limit, offset).await +} + +/// The login lookup. Usernames are stored trimmed; callers trim the same way +/// so a padded attempt matches the canonical name. +pub async fn find_by_username(db: &Database, username: &str) -> Result, AppError> { + user::find_by_username(db, username).await +} + +/// Persist the personal-info/profile fields a PATCH carried. +pub async fn set_profile( + db: &Database, + id: &UserId, + name: Option>, + surname: Option>, + email: Option>, + phone: Option>, + birth_date: Option>, + display_name: Option>, + bio: Option>, +) -> Result { + user::set_profile(db, id, name, surname, email, phone, birth_date, display_name, bio).await +} + +/// Persist an avatar upload, handing back the replaced blob's name. +pub async fn set_avatar( + db: &Database, + id: &UserId, + file: &str, + content_type: &FileContentType, + size: i64, +) -> Result, AppError> { + user::set_avatar(db, id, file, content_type, size).await +} + +/// Clear the avatar, handing back the blob's name for deletion. +pub async fn clear_avatar(db: &Database, id: &UserId) -> Result, AppError> { + user::clear_avatar(db, id).await +} + +/// Rewrite the credential — the admin-password reset's store half. +pub async fn set_password_hash( + db: &Database, + id: &UserId, + password_hash: PasswordHash, +) -> Result, AppError> { + user::set_password_hash(db, id, password_hash).await +} + +/// Persist the UI-preference fields a PATCH carried. +pub async fn set_preferences( + db: &Database, + id: &UserId, + theme: Option>, + language: Option>, + palette_color: Option>, +) -> Result { + user::set_preferences(db, id, theme, language, palette_color).await +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database::{Database, init_mem}; + use crate::domain::user::Password; + + async fn a_user(username: &str, db: &Database) -> User { + user::create( + db, + Username::try_new(username).unwrap(), + Password::try_new("secret1") + .unwrap() + .hash_async() + .await + .unwrap(), + ) + .await + .unwrap() + } + + /// The board result slot is an *index* into a batch whose length depends on + /// which arms the role selected, so it is the one number in the cascade a + /// silent mistake would not show up in the store: pointed at the wrong + /// statement it yields an empty list, and every whiteboard room whose roster + /// just changed is simply never told. Assert the rows come back. + #[tokio::test] + async fn the_cascade_returns_the_boards_it_stripped() { + use crate::domain::board::{Board, BoardTitle}; + + let db = init_mem().await.unwrap(); + let creator = a_user("ogretmen", &db).await; + let guest = a_user("ogrenci", &db).await; + let board = Board::create( + creator.get_id(), + BoardTitle::try_new("Geometri").unwrap(), + vec![guest.get_id().clone()], + &db, + ) + .await + .unwrap(); + + // A promotion touches no roster and must report none. + let (guest, boards) = set_role(&db, guest.get_id(), Role::Teacher) + .await + .unwrap(); + assert!( + boards.is_empty(), + "only a demotion to parent strips rosters" + ); + + let (_, boards) = set_role(&db, guest.get_id(), Role::Parent) + .await + .unwrap(); + assert_eq!(boards.len(), 1, "the stripped room must be reported back"); + assert_eq!(boards[0].get_id(), board.get_id()); + assert!( + boards[0].get_participants().is_empty(), + "and carry the roster the room is about to be told about" + ); + } + + /// The half the roster strip cannot reach: the board's **creator**. Demoted, + /// they are 404'd off their own room, every command on it is creator-only + /// for everyone else, and nothing in the crate lists a board a caller is not + /// on — so the room could be cleared, locked, closed and deleted by nobody + /// while its participants kept drawing on it. The demotion closes it, and + /// closing is *all* it does: the roster, the row and every mark stay + /// readable. + #[tokio::test] + async fn a_demoted_creator_s_board_is_closed_and_still_readable() { + use crate::domain::board::{Board, BoardTitle}; + use crate::domain::board_stroke::{BOARD_CLOSED, BoardStroke}; + + let db = init_mem().await.unwrap(); + let creator = a_user("ogretmen", &db).await; + let guest = a_user("ogrenci", &db).await; + let board = Board::create( + creator.get_id(), + BoardTitle::try_new("Geometri").unwrap(), + vec![guest.get_id().clone()], + &db, + ) + .await + .unwrap(); + let mark = |epoch| { + let (id, author, db) = (board.get_id().clone(), guest.get_id().clone(), db.clone()); + async move { BoardStroke::append(&id, &author, "{\"p\":[1]}", epoch, &db).await } + }; + mark(0).await.unwrap(); + + let (creator, boards) = set_role(&db, creator.get_id(), Role::Parent) + .await + .unwrap(); + assert_eq!(boards.len(), 1, "the room must be reported back"); + let stamp = boards[0] + .get_closed_at() + .expect("and carry the closing stamp the room is told about"); + + // Stored, not merely reported — and nothing else moved. + let stored = Board::read(board.get_id(), &db).await.unwrap().unwrap(); + assert_eq!(stored.get_closed_at(), Some(stamp)); + assert_eq!( + stored.get_participants(), + [guest.get_id().clone()], + "closing must not empty the roster it did not touch" + ); + assert_eq!( + BoardStroke::history(board.get_id(), None, false, None, 0, &db) + .await + .unwrap() + .1, + 1, + "the marks the participants drew stay on disk" + ); + + // Read-only for the participants who are still on it. + assert!( + matches!(mark(0).await, Err(AppError::Conflict(BOARD_CLOSED))), + "a closed board must refuse every write with the terminal answer" + ); + + // The stamp is the record: a re-run of the sweep must not move it. + tokio::time::sleep(std::time::Duration::from_millis(2)).await; + set_role(&db, creator.get_id(), Role::Parent) + .await + .unwrap(); + assert_eq!( + Board::read(board.get_id(), &db) + .await + .unwrap() + .unwrap() + .get_closed_at(), + Some(stamp), + "the close is a compare-and-set, not a re-stamp" + ); + } + + /// A demotion below `teacher` must take the published calendar with it and + /// settle the bookings on it. Nothing else can: a slot is listed only on its + /// own teacher's calendar (and hidden from every other reader once its owner + /// is demoted), deleted only by a teacher+, and a booking on one can be + /// decided only by a teacher+ and cancelled only by its requester — who is + /// refused the moment the window opens. So a slot left behind here is a row + /// no route can reach and a seat nothing can ever free. + #[tokio::test] + async fn a_demotion_withdraws_the_calendar_and_settles_its_bookings() { + use crate::domain::appointment_slot::AppointmentSlot; + use crate::domain::appointment::{AppointmentReason, AppointmentStatus}; + use crate::service::appointment; + use crate::domain::timestamp::Timestamp; + + let db = init_mem().await.unwrap(); + let staff = |name: &'static str, db: Database| async move { + let teacher = a_user(name, &db).await; + set_role(&db, teacher.get_id(), Role::Teacher) + .await + .unwrap() + .0 + }; + let teacher = staff("ogretmen", db.clone()).await; + let other = staff("digerogretmen", db.clone()).await; + let student = a_user("ogrenci", &db).await; + let soon = |offset| Timestamp::from_millis(Timestamp::now().as_millis() + offset); + let reason = || AppointmentReason::try_new("görüşme").unwrap(); + let slot = |owner: &User, offset: i64, db: Database| { + let owner = owner.get_id().clone(); + async move { + AppointmentSlot::create(&owner, soon(offset), soon(offset + 60_000), None, &db) + .await + .unwrap() + } + }; + + let free = slot(&teacher, 60_000, db.clone()).await; + let asked = slot(&teacher, 180_000, db.clone()).await; + let agreed = slot(&teacher, 300_000, db.clone()).await; + let kept = slot(&other, 60_000, db.clone()).await; + + let pending = appointment::book(&db, asked.get_id(), student.get_id(), reason()) + .await + .unwrap(); + let approved = appointment::book(&db, agreed.get_id(), student.get_id(), reason()) + .await + .unwrap(); + appointment::approve(&db, approved.get_id(), teacher.get_id()) + .await + .unwrap(); + let elsewhere = appointment::book(&db, kept.get_id(), student.get_id(), reason()) + .await + .unwrap(); + + set_role(&db, teacher.get_id(), Role::Student) + .await + .unwrap(); + + // The calendar is gone, the booked weeks included. + assert!( + AppointmentSlot::list_for_teacher(teacher.get_id(), &db) + .await + .unwrap() + .is_empty() + ); + for slot in [&free, &asked, &agreed] { + assert!( + AppointmentSlot::read(slot.get_id(), &db) + .await + .unwrap() + .is_none(), + "a slot only a teacher+ could reach outlived the role" + ); + } + // Both bookings — the pending request and the confirmed meeting — ended + // in a state their requester can still read, saying who dropped it. + for booking in [&pending, &approved] { + let after = appointment::read(&db, booking.get_id()) + .await + .unwrap() + .expect("the requester keeps the row"); + assert_eq!(after.get_status(), AppointmentStatus::Cancelled); + assert_eq!(after.get_cancelled_by(), Some(teacher.get_id())); + assert!(after.get_cancel_reason().is_some(), "and why"); + } + // The seat each held died with its slot row, so nothing is pinned: no + // live booking is left pointing at a slot that no longer exists. + let mut result = db + .query( + "SELECT VALUE id FROM appointment \ + WHERE status IN ['pending', 'approved'] AND slot.starts_at = NONE", + ) + .await + .unwrap() + .check() + .unwrap(); + assert!(result.take::>(0).unwrap().is_empty()); + + // Another teacher's calendar is nobody else's business. + assert_eq!( + AppointmentSlot::list_for_teacher(other.get_id(), &db) + .await + .unwrap() + .len(), + 1 + ); + assert_eq!( + appointment::read(&db, elsewhere.get_id()) + .await + .unwrap() + .unwrap() + .get_status(), + AppointmentStatus::Pending + ); + } +} diff --git a/src/web/appointments.rs b/src/web/appointments.rs index 8822e22..b19059d 100644 --- a/src/web/appointments.rs +++ b/src/web/appointments.rs @@ -412,7 +412,7 @@ async fn list_slots( .filter(|teacher| seen.insert(teacher.key().to_string())) .cloned() .collect(); - let people: HashMap = User::list_by_ids(&teachers, &st.db) + let people: HashMap = crate::service::user::list_by_ids(&st.db, &teachers) .await? .iter() .filter(|teacher| teacher.get_role().at_least(Role::Teacher)) @@ -546,7 +546,7 @@ async fn book( .ok_or(AppError::NotFound)?; // The slot row is not the grant: a teacher demoted since publishing keeps // their rows, and those rows must be inert. Their live role decides. - if !User::read(slot.get_teacher(), &st.db) + if !crate::service::user::read(&st.db, slot.get_teacher()) .await? .is_some_and(|teacher| teacher.get_role().at_least(Role::Teacher)) { @@ -889,10 +889,10 @@ mod tests { .hash_async() .await .unwrap(); - let user = User::create(Username::try_new(username).unwrap(), hash, db) + let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) .await .unwrap(); - user.set_role(role, db).await.unwrap().0 + crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0 } /// All five `can_manage` sites are `RequireTeacher` today, so this is @@ -914,7 +914,8 @@ mod tests { assert!(can_manage(&slot, &owner)); for role in [Role::Student, Role::Parent] { - let demoted = owner.clone().set_role(role, &db).await.unwrap().0; + let demoted = + crate::service::user::set_role(&db, owner.get_id(), role).await.unwrap().0; assert!( !can_manage(&slot, &demoted), "{role:?} slot owner still decides its bookings" diff --git a/src/web/attendance.rs b/src/web/attendance.rs index b59b474..90a6fb5 100644 --- a/src/web/attendance.rs +++ b/src/web/attendance.rs @@ -200,7 +200,7 @@ async fn user_report( let target = UserId::from_key(&user); ensure_can_observe(&caller, &target, &st.db).await?; // User must exist — a missing user is a 404, not an empty report. - User::read(&target, &st.db) + crate::service::user::read(&st.db, &target) .await? .ok_or(AppError::NotFound)?; // Only an exactly-teacher caller is narrowed to their managed courses; diff --git a/src/web/auth.rs b/src/web/auth.rs index a550d02..6de3924 100644 --- a/src/web/auth.rs +++ b/src/web/auth.rs @@ -12,7 +12,7 @@ use utoipa_axum::routes; use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS}; use crate::domain::builder::BuilderSession; use crate::domain::role::Role as DomainRole; -use crate::domain::user::{Password, PasswordHash, User, Username}; +use crate::domain::user::{Password, PasswordHash, Username}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::rate_limit::{RateLimitConfig, RateLimiter}; use crate::service; @@ -118,7 +118,8 @@ async fn register( } .into()); } - // Hash BEFORE the availability check inside `User::create`, never after: the + // Hash BEFORE the availability check inside the user-create path, never + // after: the // ~33ms of argon2 is what makes both outcomes cost the same, so a taken // username can't be spotted by a fast reply. The only work the taken path // skips is the insert itself, orders of magnitude below hashing. @@ -126,12 +127,12 @@ async fn register( // Built once, before the branch: the created and the taken path answer with // the very same value, so they cannot be told apart by construction rather // than by keeping two field lists in sync. Every fresh account starts as a - // student (`User::create`), so this holds whichever way the insert goes. + // student (`service::user::create`), so this holds whichever way the insert goes. let body = RegisterResponse { username: username.as_str().to_string(), role: DomainRole::Student.into(), }; - match User::create(username, password_hash, &db).await { + match crate::service::user::create(&db, username, password_hash).await { Ok(_) => {} // Taken. Log the real reason server-side; the caller gets the same 201 // and the same body, because telling the two apart is the whole thing @@ -174,7 +175,7 @@ async fn login( let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?; // Usernames are stored trimmed (see `Username::try_new`); trim the lookup // the same way so a padded login attempt matches the canonical name. - let user = match User::find_by_username(req.username.trim(), &db).await? { + let user = match crate::service::user::find_by_username(&db, req.username.trim()).await? { // Verification is `.await`ed so argon2 runs on the blocking pool instead // of stalling an async worker; that rules out a match guard, which // cannot await. diff --git a/src/web/bank_questions.rs b/src/web/bank_questions.rs index bdfac29..cc2cd42 100644 --- a/src/web/bank_questions.rs +++ b/src/web/bank_questions.rs @@ -948,10 +948,10 @@ mod tests { .hash_async() .await .unwrap(); - let user = User::create(Username::try_new(username).unwrap(), hash, db) + let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) .await .unwrap(); - user.set_role(role, db).await.unwrap().0 + crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0 } /// Every bank route is `RequireTeacher` today, so this is pinned at the @@ -977,7 +977,10 @@ mod tests { assert!(ensure_owner(&question, &owner).is_ok()); for role in [Role::Student, Role::Parent] { - let demoted = owner.clone().set_role(role, &db).await.unwrap().0; + let demoted = crate::service::user::set_role(&db, owner.get_id(), role) + .await + .unwrap() + .0; assert!( !can_see(&question, &demoted), "{role:?} owner still reads their template" diff --git a/src/web/board_ws.rs b/src/web/board_ws.rs index 4e5d38a..79ff4fc 100644 --- a/src/web/board_ws.rs +++ b/src/web/board_ws.rs @@ -72,7 +72,7 @@ use crate::domain::board::{Board, BoardId}; use crate::domain::board_stroke::{self, BoardStroke}; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; -use crate::domain::user::{User, UserId}; +use crate::domain::user::UserId; use crate::error::AppError; use crate::state::AppState; use crate::tenant::Slug; @@ -207,7 +207,7 @@ type Step = Result<(), RoomClosed>; /// role barred from the whiteboard outright — must not leave an open socket /// still committing strokes. async fn live_board(board: &BoardId, user: &UserId, db: &Database) -> Result { - let barred = User::read(user, db) + let barred = crate::service::user::read(db, user) .await? .is_none_or(|caller| !caller.get_role().at_least(Role::Student)); if barred { @@ -681,17 +681,17 @@ mod tests { let db = crate::database::init_mem().await.unwrap(); let password = Password::try_new("secret1").unwrap(); - let creator = User::create( + let creator = crate::service::user::create( + &db, Username::try_new("ogretmen").unwrap(), password.hash_async().await.unwrap(), - &db, ) .await .unwrap(); - let mate = User::create( + let mate = crate::service::user::create( + &db, Username::try_new("ogrenci").unwrap(), password.hash_async().await.unwrap(), - &db, ) .await .unwrap(); @@ -713,7 +713,9 @@ mod tests { // Demoted while the socket is open: refused from here on, and with the // frame a denied write already uses — no new frame type. - mate.set_role(Role::Parent, &db).await.unwrap(); + crate::service::user::set_role(&db, mate.get_id(), Role::Parent) + .await + .unwrap(); let err = live_board(board.get_id(), &mate_id, &db).await.unwrap_err(); assert!( matches!(err, AppError::Forbidden(_)), diff --git a/src/web/boards.rs b/src/web/boards.rs index ffa1993..34c7bb6 100644 --- a/src/web/boards.rs +++ b/src/web/boards.rs @@ -138,7 +138,7 @@ async fn resolve_participants( // Absent from this list means "no such user, or below `student`" — the two // are one case here, and telling them apart is what the caller must not be // able to do anyway. - let eligible: Vec = User::list_by_ids(&wanted, db) + let eligible: Vec = crate::service::user::list_by_ids(db, &wanted) .await? .iter() .filter(|found| found.get_role().at_least(Role::Student)) @@ -837,7 +837,7 @@ async fn invite_board( // a source is a whole group, and one member who has left or was never // eligible must not fail the invite for the other twenty-nine. let mut roster = board.get_participants().to_vec(); - for candidate in User::list_by_ids(&invited, &st.db).await? { + for candidate in crate::service::user::list_by_ids(&st.db, &invited).await? { if !candidate.get_role().at_least(Role::Student) { continue; } @@ -919,7 +919,7 @@ mod tests { .check() .unwrap(); let who = async |key: &str| { - User::read(&UserId::from_key(key), &db) + crate::service::user::read(&db, &UserId::from_key(key)) .await .unwrap() .unwrap() diff --git a/src/web/builder.rs b/src/web/builder.rs index 2c0ad73..e188084 100644 --- a/src/web/builder.rs +++ b/src/web/builder.rs @@ -225,7 +225,7 @@ fn path_slug(raw: &str) -> Result { /// below admin → `409`, the repo's verdict for "the row exists, its state /// refuses this". async fn school_admin(username: &str, db: &crate::database::Database) -> Result { - let user = User::find_by_username(username.trim(), db) + let user = crate::service::user::find_by_username(db, username.trim()) .await? .ok_or(AppError::NotFound)?; if user.get_role() != Role::Admin { @@ -356,7 +356,9 @@ async fn create_school( modules.validate()?; let db = st.tenants.create(&slug, &name, modules).await?; - if let Err(err) = User::create_with_role(username, password_hash, Role::Admin, &db).await { + if let Err(err) = + crate::service::user::create_with_role(&db, username, password_hash, Role::Admin).await + { // A school nobody can log into is worse than no school: take the // database back so the very same request can simply be retried. if let Err(cleanup) = st.tenants.drop(&slug).await { @@ -754,7 +756,7 @@ async fn reset_admin_password( let user = school_admin(&req.username, &db).await?; let password_hash = Password::try_new(&req.password)?.hash_async().await?; - User::set_password_hash(user.get_id(), password_hash, &db) + crate::service::user::set_password_hash(&db, user.get_id(), password_hash) .await? .ok_or(AppError::NotFound)?; // The other half: the new password means nothing while a cookie minted diff --git a/src/web/classes.rs b/src/web/classes.rs index 3208617..7a3bb12 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -267,7 +267,7 @@ async fn teacher_or_none(text: Option<&str>, db: &Database) -> Result Result { - let Some(teacher) = User::read(&UserId::from_key(key), db).await? else { + let Some(teacher) = crate::service::user::read(db, &UserId::from_key(key)).await? else { return Err(AppError::Validation(ValidationError::Invalid { field: "teacher_id", reason: "target user does not exist", @@ -654,7 +654,7 @@ async fn user_classes( let target = UserId::from_key(&user); ensure_can_observe(&caller, &target, &st.db).await?; // User must exist — a missing user is a 404, not an empty page. - User::read(&target, &st.db) + crate::service::user::read(&st.db, &target) .await? .ok_or(AppError::NotFound)?; // A linked parent reads this too, and is no more entitled to the office's @@ -745,7 +745,7 @@ async fn add_member( class.require_open(&st.db).await?; let target = UserId::from_key(&req.user_id); - let Some(target_user) = User::read(&target, &st.db).await? else { + let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { return Err(AppError::Validation(ValidationError::Invalid { field: "user_id", reason: "target user does not exist", @@ -1493,25 +1493,28 @@ mod tests { #[tokio::test] async fn an_empty_teacher_is_no_teacher_and_a_student_is_never_one() { use crate::domain::role::Role; - use crate::domain::user::{Password, User, Username}; + use crate::domain::user::{Password, Username}; let db = crate::database::init_mem().await.unwrap(); assert!(teacher_or_none(None, &db).await.unwrap().is_none()); assert!(teacher_or_none(Some(""), &db).await.unwrap().is_none()); let make = async |name: &str, role: Role| { - let user = User::create( + let user = crate::service::user::create( + &db, Username::try_new(name).unwrap(), Password::try_new("secret1") .unwrap() .hash_async() .await .unwrap(), - &db, ) .await .unwrap(); - user.set_role(role, &db).await.unwrap().0 + crate::service::user::set_role(&db, user.get_id(), role) + .await + .unwrap() + .0 }; let student = make("ali", Role::Student).await; let teacher = make("ada", Role::Teacher).await; diff --git a/src/web/courses.rs b/src/web/courses.rs index 9a52348..1aa313b 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -690,7 +690,7 @@ async fn enroll( service::course::require_open(&st.db, &course).await?; let target = UserId::from_key(&req.user_id); - let Some(target_user) = User::read(&target, &st.db).await? else { + let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { return Err(AppError::Validation(ValidationError::Invalid { field: "user_id", reason: "target user does not exist", @@ -1308,10 +1308,10 @@ mod tests { .hash_async() .await .unwrap(); - let user = User::create(Username::try_new(username).unwrap(), hash, db) + let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) .await .unwrap(); - user.set_role(role, db).await.unwrap().0 + crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0 } /// A course `creator` made, with nobody assigned. @@ -1340,7 +1340,10 @@ mod tests { assert!(owns_course(&course, &creator)); for role in [Role::Student, Role::Parent] { - let demoted = creator.clone().set_role(role, &db).await.unwrap().0; + let demoted = crate::service::user::set_role(&db, creator.get_id(), role) + .await + .unwrap() + .0; assert!( !can_manage_course(&course, &demoted), "{role:?} creator still manages the course" @@ -1371,7 +1374,10 @@ mod tests { // ...but never an owner, assigned or not. assert!(!owns_course(&course, &assigned)); - let demoted = assigned.set_role(Role::Student, &db).await.unwrap().0; + let demoted = crate::service::user::set_role(&db, assigned.get_id(), Role::Student) + .await + .unwrap() + .0; assert!(!can_manage_course(&course, &demoted)); } @@ -1430,7 +1436,9 @@ mod tests { let db = init_mem().await.unwrap(); let creator = user("teacher", Role::Teacher, &db).await; let course = course(&creator, &db).await; - creator.set_role(Role::Student, &db).await.unwrap(); + crate::service::user::set_role(&db, creator.get_id(), Role::Student) + .await + .unwrap(); for role in [Role::Manager, Role::Admin] { let boss = user(&format!("boss{}", role.as_str()), role, &db).await; diff --git a/src/web/dto.rs b/src/web/dto.rs index 0d11559..666cc9b 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -136,7 +136,7 @@ pub async fn person_map( .into_iter() .filter(|id| seen.insert(id.key().to_string())) .collect(); - let users = User::list_by_ids(&unique, db).await?; + let users = crate::service::user::list_by_ids(db, &unique).await?; Ok(users .iter() .map(|user| (user.get_id().key().to_string(), PersonRef::new(user))) diff --git a/src/web/events.rs b/src/web/events.rs index 6a2ef5e..68c82cd 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -517,7 +517,7 @@ async fn mark( }; // Target user must exist. - let Some(target_user) = User::read(&target, &st.db).await? else { + let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { return Err(AppError::Validation(ValidationError::Invalid { field: "user_id", reason: "target user does not exist", @@ -759,7 +759,7 @@ async fn register( Some(ref key) => UserId::from_key(key), None => user.get_id().clone(), }; - let Some(target_user) = User::read(&target, &st.db).await? else { + let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { return Err(AppError::Validation(ValidationError::Invalid { field: "user_id", reason: "target user does not exist", @@ -835,7 +835,7 @@ async fn unregister( // stranded, and a volume written before `Registration::register` claimed // the holder's row already carries some. if &target != user.get_id() - && let Some(target_user) = User::read(&target, &st.db).await? + && let Some(target_user) = crate::service::user::read(&st.db, &target).await? && target_user.get_role().at_least(Role::Teacher) { return Err(AppError::Forbidden( @@ -865,10 +865,10 @@ mod tests { .hash_async() .await .unwrap(); - let user = User::create(Username::try_new(username).unwrap(), hash, db) + let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) .await .unwrap(); - user.set_role(role, db).await.unwrap().0 + crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0 } /// `can_manage` is only reached behind `RequireTeacher` today, so this is @@ -892,7 +892,10 @@ mod tests { assert!(can_manage(&event, &creator)); for role in [Role::Student, Role::Parent] { - let demoted = creator.clone().set_role(role, &db).await.unwrap().0; + let demoted = crate::service::user::set_role(&db, creator.get_id(), role) + .await + .unwrap() + .0; assert!( !can_manage(&event, &demoted), "{role:?} creator still manages the event" diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index 0011dff..e61ef9d 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -671,7 +671,7 @@ async fn grade( } // Target user must exist. - let Some(target_user) = User::read(&target, &st.db).await? else { + let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { return Err(AppError::Validation(ValidationError::Invalid { field: "user_id", reason: "target user does not exist", diff --git a/src/web/extractor.rs b/src/web/extractor.rs index a6f9af5..c9e2289 100644 --- a/src/web/extractor.rs +++ b/src/web/extractor.rs @@ -50,7 +50,7 @@ where return Err(AppError::Unauthorized); } - User::read(session.user(), &db) + service::user::read(&db, session.user()) .await? .ok_or(AppError::Unauthorized) } diff --git a/src/web/homework.rs b/src/web/homework.rs index dd767b3..6580490 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -1160,7 +1160,7 @@ async fn grade_homework( } // Target user must exist. - let Some(target_user) = User::read(&target, &st.db).await? else { + let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { return Err(AppError::Validation(ValidationError::Invalid { field: "user", reason: "target user does not exist", @@ -1476,7 +1476,7 @@ async fn homework_report( let target = UserId::from_key(&user); ensure_can_observe(&caller, &target, &st.db).await?; // User must exist — a missing user is a 404, not an empty report. - User::read(&target, &st.db) + crate::service::user::read(&st.db, &target) .await? .ok_or(AppError::NotFound)?; // Only an exactly-teacher caller is narrowed to their managed courses; diff --git a/src/web/marks.rs b/src/web/marks.rs index 5ea9970..e7d291d 100644 --- a/src/web/marks.rs +++ b/src/web/marks.rs @@ -203,7 +203,7 @@ async fn user_marks( let target = UserId::from_key(&user); ensure_can_observe(&caller, &target, &st.db).await?; // User must exist — a missing user is a 404, not an empty report. - User::read(&target, &st.db) + crate::service::user::read(&st.db, &target) .await? .ok_or(AppError::NotFound)?; // Only an exactly-teacher caller is narrowed to their managed courses; diff --git a/src/web/meals.rs b/src/web/meals.rs index 59360f7..37c1e5a 100644 --- a/src/web/meals.rs +++ b/src/web/meals.rs @@ -676,7 +676,7 @@ async fn update_profile( let target = UserId::from_key(&user); // Only a student eats off the school's menus; a profile on anyone else is // a typo, and a typo here is an allergy filed against the wrong person. - if User::read(&target, &st.db) + if crate::service::user::read(&st.db, &target) .await? .ok_or(AppError::NotFound)? .get_role() @@ -803,7 +803,7 @@ async fn booking_target( }, ))?); if ParentLink::exists(caller.get_id(), &target, db).await? - && User::read(&target, db) + && crate::service::user::read(db, &target) .await? .is_some_and(|target| target.get_role() == Role::Student) { @@ -1143,7 +1143,7 @@ async fn mark_attendance( let student = UserId::from_key(&req.student_id); // The target must exist; no booking is required, since a walk-in was still // served and the record is operationally true. - if User::read(&student, &st.db).await?.is_none() { + if crate::service::user::read(&st.db, &student).await?.is_none() { return Err(AppError::Validation(ValidationError::Invalid { field: "student_id", reason: "target user does not exist", @@ -1347,10 +1347,9 @@ async fn ensure_can_read_money( // The link row alone is not the grant: a link whose student side changed // role must be inert, so the target's live role is re-read. A missing or // non-student target falls through to the same 403 — a parent never gets an - // existence oracle. if caller.get_role() == Role::Parent && ParentLink::exists(caller.get_id(), target, db).await? - && User::read(target, db) + && crate::service::user::read(db, target) .await? .is_some_and(|target| target.get_role() == Role::Student) { @@ -1497,7 +1496,7 @@ async fn record_credit( // promoted to staff keeps what they owed), and the student rule alone made // that debt permanently unsettleable — there is no other route that // appends a credit. A typo'd staff id has no lines, so it still 400s. - if User::read(&student, &st.db) + if crate::service::user::read(&st.db, &student) .await? .ok_or(AppError::NotFound)? .get_role() diff --git a/src/web/messages.rs b/src/web/messages.rs index ea6f420..e5647d6 100644 --- a/src/web/messages.rs +++ b/src/web/messages.rs @@ -120,7 +120,7 @@ async fn load_people(messages: &[Message], db: &Database) -> Result Result<(), AppError> { - if User::read(target, db) + if crate::service::user::read(db, target) .await? .is_some_and(|user| user.get_role().at_least(Role::Teacher)) { @@ -414,22 +414,21 @@ mod tests { let db = crate::database::init_mem().await.unwrap(); let office = UserId::from_key("office"); - let teacher = User::create( + let teacher = crate::service::user::create( + &db, Username::try_new("ada").unwrap(), Password::try_new("secret1") .unwrap() .hash_async() .await .unwrap(), - &db, ) .await - .unwrap() - .set_role(Role::Teacher, &db) - .await - .unwrap() - .0; - + .unwrap(); + crate::service::user::set_role(&db, teacher.get_id(), Role::Teacher) + .await + .unwrap() + .0; let assigned = async |db: &Database| { let class = ClassGroup::create( &office, diff --git a/src/web/payments.rs b/src/web/payments.rs index 63aa1f9..5f0f13a 100644 --- a/src/web/payments.rs +++ b/src/web/payments.rs @@ -434,7 +434,7 @@ async fn assign_plan( let student = UserId::from_key(&student_id); // A fee record belongs to a student; billing anyone else is a typo, and // a typo here is money against the wrong person. - let is_student = User::read(&student, &st.db) + let is_student = crate::service::user::read(&st.db, &student) .await? .is_some_and(|user| user.get_role() == Role::Student); let (status, reason) = if is_student { @@ -791,7 +791,7 @@ async fn ensure_can_read_payments( // existence oracle. if caller.get_role() == Role::Parent && ParentLink::exists(caller.get_id(), target, db).await? - && User::read(target, db) + && crate::service::user::read(db, target) .await? .is_some_and(|target| target.get_role() == Role::Student) { diff --git a/src/web/pomodoro.rs b/src/web/pomodoro.rs index 927f85b..377a67e 100644 --- a/src/web/pomodoro.rs +++ b/src/web/pomodoro.rs @@ -225,7 +225,7 @@ async fn user_pomodoro( let target = UserId::from_key(&user); ensure_can_observe(&caller, &target, &st.db).await?; // User must exist — a missing user is a 404, not an empty log. - User::read(&target, &st.db) + crate::service::user::read(&st.db, &target) .await? .ok_or(AppError::NotFound)?; let sessions = PomodoroSession::list_for_user(&target, &st.db).await?; diff --git a/src/web/sessions.rs b/src/web/sessions.rs index 7d70fe1..e955496 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -101,7 +101,7 @@ pub(crate) async fn resolve_session_teacher( Some(key) if key == caller.get_id().key() => return Ok(caller.clone()), Some(key) => UserId::from_key(key), }; - let Some(user) = User::read(&target, db).await? else { + let Some(user) = crate::service::user::read(db, &target).await? else { return Err(AppError::Validation(ValidationError::Invalid { field: "teacher_id", reason: "session teacher does not exist", @@ -325,7 +325,7 @@ async fn mark_roll_call( let target = UserId::from_key(&req.user_id); // Target user must exist. - let Some(target_user) = User::read(&target, &st.db).await? else { + let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { return Err(AppError::Validation(ValidationError::Invalid { field: "user_id", reason: "target user does not exist", @@ -466,7 +466,7 @@ async fn remove_roll_call( // to delete without the manager+ this guard exists to require. A target // whose user row is gone can only be a student's stale row (marking checks // the role at write time), so it stays the session teacher's to clear. - let staff_row = User::read(&target, &st.db) + let staff_row = crate::service::user::read(&st.db, &target) .await? .is_some_and(|target_user| target_user.get_role().at_least(Role::Teacher)); if staff_row && !user.get_role().at_least(Role::Manager) { diff --git a/src/web/tenant_state.rs b/src/web/tenant_state.rs index 9ba6136..9671757 100644 --- a/src/web/tenant_state.rs +++ b/src/web/tenant_state.rs @@ -183,7 +183,7 @@ mod tests { use crate::database::init_mem_tenants; use crate::db::session; use crate::domain::builder::{Builder, BuilderSession}; - use crate::domain::user::{Password, User, Username}; + use crate::domain::user::{Password, Username}; use crate::tenant::DEMO_SLUG; use crate::web::{CurrentUser, RequireBuilder}; @@ -204,14 +204,14 @@ mod tests { .await .expect("the demo school"); - let user = User::create( + let user = crate::service::user::create( + &school, Username::try_new("ada").unwrap(), Password::try_new("secret1") .unwrap() .hash_async() .await .unwrap(), - &school, ) .await .unwrap(); diff --git a/src/web/users.rs b/src/web/users.rs index d9e2817..aaab134 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -147,18 +147,18 @@ async fn apply_profile( let birth_date = merge_field(req.birth_date.as_deref(), BirthDate::try_new)?; let display_name = merge_field(req.display_name.as_deref(), DisplayName::try_new)?; let bio = merge_field(req.bio.as_deref(), Bio::try_new)?; - let updated = user - .set_profile( - name, - surname, - email, - phone, - birth_date, - display_name, - bio, - db, - ) - .await?; + let updated = crate::service::user::set_profile( + db, + user.get_id(), + name, + surname, + email, + phone, + birth_date, + display_name, + bio, + ) + .await?; Ok(UserResponse::new(&updated)) } @@ -174,9 +174,14 @@ async fn apply_preferences( let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?; let language = merge_field(req.language.as_deref(), Language::try_from_str)?; let palette_color = merge_field(req.palette_color.as_deref(), PaletteColor::try_from_str)?; - let updated = user - .set_preferences(theme, language, palette_color, db) - .await?; + let updated = crate::service::user::set_preferences( + db, + user.get_id(), + theme, + language, + palette_color, + ) + .await?; Ok(UserResponse::new(&updated)) } @@ -246,7 +251,8 @@ async fn search_users( "students and parents may only search staff (teacher or higher)", )); } - let (users, total) = User::search(&req.q, role, allowed, limit, offset, &st.db).await?; + let (users, total) = + crate::service::user::search(&st.db, &req.q, role, allowed, limit, offset).await?; let items = users.iter().map(PersonRef::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -274,7 +280,7 @@ async fn list_users( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let (users, total) = User::list_all(limit, offset, &st.db).await?; + let (users, total) = crate::service::user::list_all(&st.db, limit, offset).await?; let items = users.iter().map(UserResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -351,7 +357,7 @@ async fn get_user( _admin: RequireAdmin, Path(id): Path, ) -> Result, AppError> { - let user = User::read(&UserId::from_key(&id), &st.db) + let user = crate::service::user::read(&st.db, &UserId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; Ok(Json(UserResponse::new(&user))) @@ -382,7 +388,7 @@ async fn update_user_profile( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - let user = User::read(&UserId::from_key(&id), &st.db) + let user = crate::service::user::read(&st.db, &UserId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; Ok(Json(apply_profile(user, &req, &st.db).await?)) @@ -413,7 +419,7 @@ async fn update_user_preferences( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - let user = User::read(&UserId::from_key(&id), &st.db) + let user = crate::service::user::read(&st.db, &UserId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; Ok(Json(apply_preferences(user, &req, &st.db).await?)) @@ -473,16 +479,13 @@ async fn set_role( if &target == admin.get_id() { return Err(AppError::Forbidden("cannot change your own role")); } - let user = User::read(&target, &st.db) - .await? - .ok_or(AppError::NotFound)?; - // The role write and every sweep it owes commit together ([`User::set_role`] - // carries the whole list and the reasoning behind each arm). The write - // ordering *within* a request is closed from the other end: a handler that - // assigns a teacher-only role re-reads the live role after its write - // ([`super::undo_if_demoted`]), so a demotion racing an assignment is caught - // by whichever side is second. - let (updated, boards) = user.set_role(role, &st.db).await?; + // The role write and every sweep it owes commit together + // ([`crate::service::user::set_role`] carries the whole list and the + // reasoning behind each arm). The write ordering *within* a request is + // closed from the other end: a handler that assigns a teacher-only role + // re-reads the live role after its write ([`super::undo_if_demoted`]), so + // a demotion racing an assignment is caught by whichever side is second. + let (updated, boards) = crate::service::user::set_role(&st.db, &target, role).await?; // Whiteboard rooms the commit above changed, prompted with the same frames // their own routes publish — after the commit, because the room re-reads the // database before it acts on a frame. A room whose creator was demoted is @@ -543,7 +546,7 @@ async fn students_page( .iter() .map(|link| link.get_student().clone()) .collect(); - let mut students = User::list_by_ids(&ids, db).await?; + let mut students = crate::service::user::list_by_ids(db, &ids).await?; // The link row alone is not the grant, exactly as [`ensure_can_observe`] // says: a link whose student side changed role (a sweep lost a race with // `link_student`) is inert everywhere else, so it must not name a person @@ -590,7 +593,7 @@ async fn link_student( Path(id): Path, Json(req): Json, ) -> Result, AppError> { - let parent = User::read(&UserId::from_key(&id), &st.db) + let parent = crate::service::user::read(&st.db, &UserId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if parent.get_role() != Role::Parent { @@ -599,7 +602,9 @@ async fn link_student( reason: "students can only be tied to a parent account", })); } - let Some(student) = User::read(&UserId::from_key(&req.user_id), &st.db).await? else { + let Some(student) = + crate::service::user::read(&st.db, &UserId::from_key(&req.user_id)).await? + else { return Err(AppError::Validation(ValidationError::Invalid { field: "user_id", reason: "target user does not exist", @@ -644,7 +649,7 @@ async fn list_parent_students( Query(page): Query, ) -> Result>, AppError> { let parent = UserId::from_key(&id); - User::read(&parent, &st.db) + crate::service::user::read(&st.db, &parent) .await? .ok_or(AppError::NotFound)?; Ok(Json(students_page(&parent, page, &st.db).await?)) @@ -1065,7 +1070,7 @@ async fn ensure_may_read_profile( async fn readable_profile_user(st: &AppState, caller: &User, id: &str) -> Result { let target = UserId::from_key(id); ensure_may_read_profile(caller, &target, &st.db).await?; - User::read(&target, &st.db).await?.ok_or(AppError::NotFound) + crate::service::user::read(&st.db, &target).await?.ok_or(AppError::NotFound) } /// The caller's own public profile — what everyone else sees of them. @@ -1160,7 +1165,7 @@ async fn upload_my_avatar( let file = ulid::Ulid::new().to_string(); store_blob(&st, &file, &upload.data, || async { - match User::set_avatar(user.get_id(), &file, &upload.content_type, size, &st.db).await? { + match crate::service::user::set_avatar(&st.db, user.get_id(), &file, &upload.content_type, size).await? { // Row written; the picture this one replaced comes off disk. Some(before) => Ok(((), before.get_avatar_file().map(str::to_string))), // The account went away mid-upload — the fresh blob is an orphan. @@ -1281,7 +1286,7 @@ async fn delete_avatar( /// Clear the row's avatar and take its blob off disk — the shared tail of the /// self and moderation deletes. A row without one (or no row at all) is a 404. async fn drop_avatar(st: &AppState, user: &UserId) -> Result { - let before = User::clear_avatar(user, &st.db) + let before = crate::service::user::clear_avatar(&st.db, user) .await? .ok_or(AppError::NotFound)?; let Some(file) = before.get_avatar_file() else { diff --git a/src/web/work.rs b/src/web/work.rs index bd9438c..527092d 100644 --- a/src/web/work.rs +++ b/src/web/work.rs @@ -8,7 +8,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::domain::timestamp::Timestamp; -use crate::domain::user::{User, UserId}; +use crate::domain::user::UserId; use crate::domain::work_entry::{WorkEntry, WorkEntryId, out_before_in_error}; use crate::error::{AppError, ErrorResponse}; use crate::state::AppState; @@ -159,7 +159,7 @@ async fn user_work( let (limit, offset) = page.resolve()?; let target = UserId::from_key(&user); // User must exist — a missing user is a 404, not an empty log. - User::read(&target, &st.db) + crate::service::user::read(&st.db, &target) .await? .ok_or(AppError::NotFound)?; let (entries, total) = WorkEntry::list_for_user(&target, limit, offset, &st.db).await?; diff --git a/tests/builder_api.rs b/tests/builder_api.rs index fe3f511..5915c66 100644 --- a/tests/builder_api.rs +++ b/tests/builder_api.rs @@ -387,14 +387,14 @@ async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions .get(&hezarfen_backend::tenant::Slug::try_new("gamma").unwrap()) .await .unwrap(); - hezarfen_backend::domain::user::User::create( + hezarfen_backend::db::user::create( + &gamma_db, Username::try_new("veli").unwrap(), Password::try_new("secret1") .unwrap() .hash_async() .await .unwrap(), - &gamma_db, ) .await .unwrap(); diff --git a/tests/integration.rs b/tests/integration.rs index 632284a..38b246e 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -5234,7 +5234,7 @@ async fn admin_manages_roles_with_guards() { /// * `src/web/users.rs:453` — `PATCH /users/{id}/role`, the *only* path that /// writes `user.role` from a caller's string (`Role::try_from_str`). /// * `src/web/auth.rs:114` — `POST /auth/register`, hardcoded `Role::Student` -/// (`User::create` → `create_with_role`, `src/domain/user.rs:334`). +/// (`service::user::create` → `create_with_role`, `src/db/user.rs`). /// * `src/web/users.rs:231` — the user-search `?role=` filter (a read). /// * `src/web/events.rs:89` — a role-audience event stores a role string of /// its own on the event row. @@ -6367,7 +6367,7 @@ async fn promotion_via_role_endpoint_sweeps_enrollments() { assert!(rows.is_empty(), "enrollment rows deleted from the DB"); } -/// Regression: `User::create` pre-checks the username and then inserts, so two +/// Regression: `db::user::create` pre-checks the username and then inserts, so two /// concurrent registrations of the same name could both pass the check; the /// loser then hit the unique index and surfaced as a raw 500. A lost race must /// answer the same uniform 201 as the winner (the "taken" reply is deliberately @@ -6865,7 +6865,9 @@ async fn admin_seed_creates_working_admin() { let (app, db) = app_and_db().await; let username = Username::try_new("root").unwrap(); let password = Password::try_new("secret1").unwrap(); - User::ensure_admin(username, password, &db).await.unwrap(); + hezarfen_backend::service::user::ensure_admin(&db, username, password) + .await + .unwrap(); let creds = json!({ "school": "demo", "username": "root", "password": "secret1" }); let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; @@ -6885,7 +6887,9 @@ async fn admin_seed_is_idempotent() { for _ in 0..2 { let username = Username::try_new("root").unwrap(); let password = Password::try_new("secret1").unwrap(); - User::ensure_admin(username, password, &db).await.unwrap(); + hezarfen_backend::service::user::ensure_admin(&db, username, password) + .await + .unwrap(); } let cookie = { @@ -6909,7 +6913,9 @@ async fn admin_seed_refuses_existing_non_admin() { let username = Username::try_new("squatter").unwrap(); let password = Password::try_new("attacker-pw").unwrap(); - User::ensure_admin(username, password, &db).await.unwrap(); + hezarfen_backend::service::user::ensure_admin(&db, username, password) + .await + .unwrap(); // Still a student: the admin-only listing stays closed... let res = send(&app, "GET", "/users", Some(&cookie), None).await; diff --git a/tests/regress_admin_floor.rs b/tests/regress_admin_floor.rs index 1b04227..77803c1 100644 --- a/tests/regress_admin_floor.rs +++ b/tests/regress_admin_floor.rs @@ -13,7 +13,7 @@ use axum::http::StatusCode; use common::{app_and_db, login_as, me_id, send}; use hezarfen_backend::database::Database; use hezarfen_backend::domain::role::Role; -use hezarfen_backend::domain::user::{User, UserId}; +use hezarfen_backend::domain::user::UserId; use serde_json::json; use surrealdb::types::RecordId; @@ -79,8 +79,8 @@ async fn set_role_refuses_the_last_admin() { let ada = login_as(&app, &db, "ada", "admin").await; let ada_id = UserId::from_key(&me_id(&app, &ada).await); - let user = User::read(&ada_id, &db).await.unwrap().unwrap(); - let refused = user.set_role(Role::Student, &db).await; + hezarfen_backend::db::user::read(&db, &ada_id).await.unwrap().unwrap(); + let refused = hezarfen_backend::service::user::set_role(&db, &ada_id, Role::Student).await; assert!(refused.is_err(), "the sole admin was demoted"); assert_eq!(admin_count(&db).await, 1, "the admin row was still lowered"); @@ -97,8 +97,12 @@ async fn set_role_refuses_the_last_admin() { ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - let ada_row = User::read(&ada_id, &db).await.unwrap().unwrap(); - assert!(ada_row.set_role(Role::Student, &db).await.is_ok()); + hezarfen_backend::db::user::read(&db, &ada_id).await.unwrap().unwrap(); + assert!( + hezarfen_backend::service::user::set_role(&db, &ada_id, Role::Student) + .await + .is_ok() + ); assert_eq!(admin_count(&db).await, 1); } diff --git a/tests/regress_role_sweep.rs b/tests/regress_role_sweep.rs index 3ff91b5..fbbab41 100644 --- a/tests/regress_role_sweep.rs +++ b/tests/regress_role_sweep.rs @@ -29,7 +29,7 @@ use hezarfen_backend::domain::event::EventId; use hezarfen_backend::domain::registration::Registration; use hezarfen_backend::domain::role::Role; use hezarfen_backend::domain::timestamp::Timestamp; -use hezarfen_backend::domain::user::{User, UserId}; +use hezarfen_backend::domain::user::UserId; use serde_json::json; /// How many rows `sql` selects ids for. @@ -51,11 +51,11 @@ async fn counter(sql: &str, db: &Database) -> i64 { /// Demote through the real path — the sweeps ride the role write. async fn demote(user: &UserId, to: Role, db: &Database) { - User::read(user, db) + hezarfen_backend::db::user::read(db, user) .await .unwrap() - .expect("the account is there") - .set_role(to, db) + .expect("the account is there"); + hezarfen_backend::service::user::set_role(db, user, to) .await .unwrap(); }