Merge branch 'layer-split/user'
Browse files at this commit45 changed files +1412 -1203
- src/ai/server.rs +1 -1
- src/constant.rs +2 -2
- src/database.rs +2 -2
- src/db/cap.rs +1 -1
- src/db/exam_attempt.rs +2 -2
- src/db/mod.rs +1 -0
- src/db/user.rs +719 -0
- src/domain/board.rs +2 -2
- src/domain/class_member.rs +9 -6
- src/domain/class_pump.rs +1 -1
- src/domain/event.rs +3 -3
- src/domain/homework_submission.rs +2 -2
- src/domain/parent_link.rs +1 -1
- src/domain/registration.rs +4 -4
- src/domain/user.rs +26 -1046
- src/service/course.rs +2 -2
- src/service/exam_attempt.rs +3 -3
- src/service/mod.rs +1 -0
- src/service/user.rs +477 -0
- src/web/appointments.rs +6 -5
- src/web/attendance.rs +1 -1
- src/web/auth.rs +6 -5
- src/web/bank_questions.rs +6 -3
- src/web/board_ws.rs +9 -7
- src/web/boards.rs +3 -3
- src/web/builder.rs +5 -3
- src/web/classes.rs +10 -7
- src/web/dto.rs +1 -1
- src/web/events.rs +9 -6
- src/web/exams/mod.rs +1 -1
- src/web/extractor.rs +1 -1
- src/web/homework.rs +2 -2
- src/web/marks.rs +1 -1
- src/web/meals.rs +5 -6
- src/web/messages.rs +2 -2
- src/web/mod.rs +9 -10
- src/web/payments.rs +2 -2
- src/web/pomodoro.rs +1 -1
- src/web/tenant_state.rs +3 -3
- src/web/users.rs +42 -37
- src/web/work.rs +2 -2
- tests/builder_api.rs +2 -2
- tests/integration.rs +11 -5
- tests/regress_admin_floor.rs +9 -5
- tests/regress_role_sweep.rs +4 -4
src/ai/server.rsmodified+1 -1
| @@ -704,7 +704,7 @@ async fn principal( | |||
| 704 | // Both the bare key (`abc`, as a REST path spells it) and the record form | 704 | // Both the bare key (`abc`, as a REST path spells it) and the record form |
| 705 | // (`user:abc`) are accepted. | 705 | // (`user:abc`) are accepted. |
| 706 | let key = who.strip_prefix("user:").unwrap_or(who); | 706 | let key = who.strip_prefix("user:").unwrap_or(who); |
| 707 | - User::read(&UserId::from_key(key), db) | 707 | + crate::db::user::read(db, &UserId::from_key(key)) |
| 708 | .await | 708 | .await |
| 709 | .map_err(|e| ("unavailable", format!("could not load `{who}`: {e}")))? | 709 | .map_err(|e| ("unavailable", format!("could not load `{who}`: {e}")))? |
| 710 | .ok_or_else(|| ("unknown_user", format!("no user `{who}`"))) | 710 | .ok_or_else(|| ("unknown_user", format!("no user `{who}`"))) |
src/constant.rsmodified+2 -2
| @@ -969,7 +969,7 @@ pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count"; | |||
| 969 | pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count"; | 969 | pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count"; |
| 970 | /// The column a *grant* claim moves and puts back, so its transaction writes | 970 | /// The column a *grant* claim moves and puts back, so its transaction writes |
| 971 | /// the holder's own `user` record — the one key | 971 | /// the holder's own `user` record — the one key |
| 972 | -/// [`crate::domain::user::User::set_role`] writes (see | 972 | +/// [`crate::service::user::set_role`] writes (see |
| 973 | /// [`crate::db::cap::role_claim`]). Any `option<int>` on the row would do: | 973 | /// [`crate::db::cap::role_claim`]). Any `option<int>` on the row would do: |
| 974 | /// the claim nets zero and never reads it, so this is an alias rather than a | 974 | /// the claim nets zero and never reads it, so this is an alias rather than a |
| 975 | /// column of its own — a new one would mean a migration on a SCHEMAFULL table | 975 | /// 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"; | |||
| 1202 | /// an `event` row. | 1202 | /// an `event` row. |
| 1203 | /// | 1203 | /// |
| 1204 | /// This is `Event::registration_capacity`'s `Conflict` arm re-spelled in | 1204 | /// This is `Event::registration_capacity`'s `Conflict` arm re-spelled in |
| 1205 | -/// SurrealQL, because the role cascade (`User::set_role`) frees a demoted | 1205 | +/// SurrealQL, because the role cascade (`service::user::set_role`) frees a demoted |
| 1206 | /// parent's seats *inside* its transaction and cannot call Rust from there. The | 1206 | /// parent's seats *inside* its transaction and cannot call Rust from there. The |
| 1207 | /// audience conjunct is what keeps it that arm and only that arm: an event that | 1207 | /// audience conjunct is what keeps it that arm and only that arm: an event that |
| 1208 | /// takes no registrations is refused earlier, by the `Validation` arm, so a | 1208 | /// takes no registrations is refused earlier, by the `Validation` arm, so a |
src/database.rsmodified+2 -2
| @@ -545,8 +545,8 @@ mod tests { | |||
| 545 | #[test] | 545 | #[test] |
| 546 | fn the_admin_seed_mints_the_role_with_the_row() { | 546 | fn the_admin_seed_mints_the_role_with_the_row() { |
| 547 | let source = | 547 | let source = |
| 548 | - std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/domain/user.rs")) | 548 | + std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/service/user.rs")) |
| 549 | - .expect("read user.rs"); | 549 | + .expect("read service/user.rs"); |
| 550 | let start = source | 550 | let start = source |
| 551 | .find("pub async fn ensure_admin") | 551 | .find("pub async fn ensure_admin") |
| 552 | .expect("ensure_admin is declared"); | 552 | .expect("ensure_admin is declared"); |
src/db/cap.rsmodified+1 -1
| @@ -454,7 +454,7 @@ pub(crate) async fn touch_and_create<T: SurrealValue + Clone>( | |||
| 454 | /// The statements that put a transaction's write on a **user's own record** | 454 | /// The statements that put a transaction's write on a **user's own record** |
| 455 | /// while the role that row still carries may hold the grant being written — | 455 | /// while the role that row still carries may hold the grant being written — |
| 456 | /// [`touch_and_create`]'s trick pointed at the one key | 456 | /// [`touch_and_create`]'s trick pointed at the one key |
| 457 | -/// [`crate::domain::user::User::set_role`] writes. | 457 | +/// [`crate::service::user::set_role`] writes. |
| 458 | /// | 458 | /// |
| 459 | /// WHY: a demotion sheds every grant the old role implied, and it does that in | 459 | /// WHY: a demotion sheds every grant the old role implied, and it does that in |
| 460 | /// the role write's own transaction — but its sweeps are *snapshots* | 460 | /// the role write's own transaction — but its sweeps are *snapshots* |
src/db/exam_attempt.rsmodified+2 -2
| @@ -370,10 +370,10 @@ mod tests { | |||
| 370 | .hash_async() | 370 | .hash_async() |
| 371 | .await | 371 | .await |
| 372 | .unwrap(); | 372 | .unwrap(); |
| 373 | - crate::domain::user::User::create( | 373 | + crate::db::user::create( |
| 374 | + db, | ||
| 374 | crate::domain::user::Username::try_new("ogrenci").unwrap(), | 375 | crate::domain::user::Username::try_new("ogrenci").unwrap(), |
| 375 | hash, | 376 | hash, |
| 376 | - db, | ||
| 377 | ) | 377 | ) |
| 378 | .await | 378 | .await |
| 379 | .unwrap() | 379 | .unwrap() |
src/db/mod.rsmodified+1 -0
| @@ -17,3 +17,4 @@ pub mod page; | |||
| 17 | pub mod payment_ledger; | 17 | pub mod payment_ledger; |
| 18 | pub mod session; | 18 | pub mod session; |
| 19 | pub mod settings; | 19 | pub mod settings; |
| 20 | +pub mod user; | ||
src/db/user.rsadded+719 -0
| @@ -0,0 +1,719 @@ | |||
| 1 | +//! The `user` table: the row mint (with the duplicate-username mapping), row | ||
| 2 | +//! reads and listings, the admin-floor count, the role cascade transaction, | ||
| 3 | +//! and the field-scoped writers. The workflows that sequence these under | ||
| 4 | +//! [`crate::service::user::ADMIN_FLOOR_LOCK`] live in | ||
| 5 | +//! [`crate::service::user`]. | ||
| 6 | + | ||
| 7 | +use surrealdb::types::{RecordId, SurrealValue}; | ||
| 8 | + | ||
| 9 | +use crate::constant::{ | ||
| 10 | + APPOINTMENT_SLOT_TABLE, APPOINTMENT_TABLE, BOARD_TABLE, CLASS_GROUP_TABLE, | ||
| 11 | + CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE, COURSE_TABLE, ENROLLMENT_COUNT_FIELD, | ||
| 12 | + ENROLLMENT_TABLE, PARENT_LINK_TABLE, REGISTRATION_COUNT_FIELD, REGISTRATION_FROZEN_GUARD, | ||
| 13 | + REGISTRATION_TABLE, | ||
| 14 | +}; | ||
| 15 | +use crate::database::{Database, transaction_with_retry, write_with_retry}; | ||
| 16 | +use crate::db::field_update::FieldUpdate; | ||
| 17 | +use crate::db::page::PagedList; | ||
| 18 | +use crate::domain::appointment::AppointmentStatus; | ||
| 19 | +use crate::domain::board::Board; | ||
| 20 | +use crate::domain::note_file::FileContentType; | ||
| 21 | +use crate::domain::preferences::{Language, PaletteColor, Theme}; | ||
| 22 | +use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; | ||
| 23 | +use crate::domain::role::Role; | ||
| 24 | +use crate::domain::text_fold::{search_fold, search_fold_sql}; | ||
| 25 | +use crate::domain::timestamp::Timestamp; | ||
| 26 | +use crate::domain::user::{PasswordHash, User, UserId, Username}; | ||
| 27 | +use crate::error::AppError; | ||
| 28 | + | ||
| 29 | +/// Register a new account. New users always start as [`Role::Student`]; | ||
| 30 | +/// elevation is a separate, admin-only action | ||
| 31 | +/// (see [`crate::service::user::set_role`]). | ||
| 32 | +pub async fn create( | ||
| 33 | + db: &Database, | ||
| 34 | + username: Username, | ||
| 35 | + password_hash: PasswordHash, | ||
| 36 | +) -> Result<User, AppError> { | ||
| 37 | + create_with_role(db, username, password_hash, Role::Student).await | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +/// The one row-minting path. `role` is written *with* the row rather than | ||
| 41 | +/// patched on afterwards, which is what makes the admin seed atomic: a | ||
| 42 | +/// create-then-promote pair can be interrupted between its halves (a SIGKILL, | ||
| 43 | +/// or a cancelled future), and the row left behind is an ordinary student | ||
| 44 | +/// account that [`crate::service::user::ensure_admin`] must then refuse to | ||
| 45 | +/// touch — a deployment with no admin and no way for a later boot to repair it. | ||
| 46 | +pub async fn create_with_role( | ||
| 47 | + db: &Database, | ||
| 48 | + username: Username, | ||
| 49 | + password_hash: PasswordHash, | ||
| 50 | + role: Role, | ||
| 51 | +) -> Result<User, AppError> { | ||
| 52 | + if find_by_username(db, username.as_str()).await?.is_some() { | ||
| 53 | + return Err(AppError::Conflict("username already taken")); | ||
| 54 | + } | ||
| 55 | + let user = User { | ||
| 56 | + id: UserId::generate(), | ||
| 57 | + username, | ||
| 58 | + password_hash, | ||
| 59 | + role, | ||
| 60 | + name: None, | ||
| 61 | + surname: None, | ||
| 62 | + email: None, | ||
| 63 | + phone: None, | ||
| 64 | + birth_date: None, | ||
| 65 | + theme: None, | ||
| 66 | + language: None, | ||
| 67 | + palette_color: None, | ||
| 68 | + display_name: None, | ||
| 69 | + bio: None, | ||
| 70 | + avatar_file: None, | ||
| 71 | + avatar_content_type: None, | ||
| 72 | + avatar_size: None, | ||
| 73 | + }; | ||
| 74 | + let created: Result<Option<User>, surrealdb::Error> = | ||
| 75 | + db.create(user.id.record()).content(user.clone()).await; | ||
| 76 | + match created { | ||
| 77 | + Ok(Some(created)) => Ok(created), | ||
| 78 | + Ok(None) => Err(AppError::Internal("failed to create user".into())), | ||
| 79 | + // The availability pre-check above is not atomic with the insert: | ||
| 80 | + // two concurrent registrations can both pass it, and the loser then | ||
| 81 | + // trips the unique username index. That loss is the same condition | ||
| 82 | + // as the sequential duplicate, so report the same 409 — not a 500. | ||
| 83 | + Err(err) => { | ||
| 84 | + if find_by_username(db, user.username.as_str()) | ||
| 85 | + .await? | ||
| 86 | + .is_some() | ||
| 87 | + { | ||
| 88 | + Err(AppError::Conflict("username already taken")) | ||
| 89 | + } else { | ||
| 90 | + Err(err.into()) | ||
| 91 | + } | ||
| 92 | + } | ||
| 93 | + } | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +pub async fn read(db: &Database, id: &UserId) -> Result<Option<User>, AppError> { | ||
| 97 | + Ok(db.select(id.record()).await?) | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +pub async fn list_all( | ||
| 101 | + db: &Database, | ||
| 102 | + limit: Option<i64>, | ||
| 103 | + offset: i64, | ||
| 104 | +) -> Result<(Vec<User>, i64), AppError> { | ||
| 105 | + PagedList::new("user", "ORDER BY id DESC") | ||
| 106 | + .run(limit, offset, db) | ||
| 107 | + .await | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +/// Fetch the users behind `ids` in one query. Ids with no row are simply | ||
| 111 | +/// absent from the result — the caller decides how to degrade. | ||
| 112 | +pub async fn list_by_ids(db: &Database, ids: &[UserId]) -> Result<Vec<User>, AppError> { | ||
| 113 | + if ids.is_empty() { | ||
| 114 | + return Ok(Vec::new()); | ||
| 115 | + } | ||
| 116 | + let records: Vec<RecordId> = ids.iter().map(UserId::record).collect(); | ||
| 117 | + let mut result = db | ||
| 118 | + .query("SELECT * FROM user WHERE id IN $ids") | ||
| 119 | + .bind(("ids", records)) | ||
| 120 | + .await? | ||
| 121 | + .check()?; | ||
| 122 | + Ok(result.take::<Vec<User>>(0)?) | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +/// Every user holding exactly `role` — e.g. the roster of a role-targeted | ||
| 126 | +/// event. Exact match, not `at_least`: "all teachers" means teachers, not | ||
| 127 | +/// managers and admins too. | ||
| 128 | +pub async fn list_by_role(db: &Database, role: Role) -> Result<Vec<User>, AppError> { | ||
| 129 | + let mut result = db | ||
| 130 | + .query("SELECT * FROM user WHERE role = $role ORDER BY id DESC") | ||
| 131 | + .bind(("role", role)) | ||
| 132 | + .await? | ||
| 133 | + .check()?; | ||
| 134 | + Ok(result.take::<Vec<User>>(0)?) | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +/// Would lowering `target` out of `admin` leave the school with none? Both | ||
| 138 | +/// halves are asked of the **live** rows in one round trip: is that row an | ||
| 139 | +/// admin right now, and does any other admin exist. It asks for one id per | ||
| 140 | +/// half rather than a `count()` — a count over an indexed field compared | ||
| 141 | +/// against a plan-time value answers `{count: N}` on the real server, and | ||
| 142 | +/// neither half needs a number. | ||
| 143 | +/// | ||
| 144 | +/// Caller must hold | ||
| 145 | +/// [`crate::service::user::ADMIN_FLOOR_LOCK`] for the answer to still be | ||
| 146 | +/// true by the time it is acted on. | ||
| 147 | +pub async fn would_orphan_admins(db: &Database, target: &UserId) -> Result<bool, AppError> { | ||
| 148 | + let mut result = db | ||
| 149 | + .query( | ||
| 150 | + "SELECT VALUE id FROM user WHERE id = $usr AND role = $role;\n\ | ||
| 151 | + SELECT VALUE id FROM user WHERE role = $role AND id != $usr LIMIT 1", | ||
| 152 | + ) | ||
| 153 | + .bind(("role", Role::Admin)) | ||
| 154 | + .bind(("usr", target.record())) | ||
| 155 | + .await? | ||
| 156 | + .check()?; | ||
| 157 | + let is_admin = !result.take::<Vec<RecordId>>(0)?.is_empty(); | ||
| 158 | + let others = !result.take::<Vec<RecordId>>(1)?.is_empty(); | ||
| 159 | + Ok(is_admin && !others) | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +/// Case- and diacritic-insensitive fragment search over username, name, | ||
| 163 | +/// and surname. Needle and columns both go through | ||
| 164 | +/// [`crate::domain::text_fold`], so `ilker` finds `İLKER` and back — | ||
| 165 | +/// backs the user pickers. `role` narrows to one role (e.g. only students | ||
| 166 | +/// for an enroll picker); `None` searches everyone. `allowed_roles` | ||
| 167 | +/// narrows the *visible* set (the roles a non-staff caller may message — | ||
| 168 | +/// see [`Role::messageable_roles`]); it is part of the query, not a | ||
| 169 | +/// post-filter, so `total` counts only what the caller may see. A blank | ||
| 170 | +/// `query` | ||
| 171 | +/// matches everyone, so blank + `role` is a role-scoped listing. Returns | ||
| 172 | +/// every match, ordered by username; the HTTP layer pages the result like | ||
| 173 | +/// any other list (no built-in cap — an over-broad fragment is windowed | ||
| 174 | +/// by `?limit`). | ||
| 175 | +pub async fn search( | ||
| 176 | + db: &Database, | ||
| 177 | + query: &str, | ||
| 178 | + role: Option<Role>, | ||
| 179 | + allowed_roles: Option<&[Role]>, | ||
| 180 | + limit: Option<i64>, | ||
| 181 | + offset: i64, | ||
| 182 | +) -> Result<(Vec<User>, i64), AppError> { | ||
| 183 | + let needle = search_fold(query.trim()); | ||
| 184 | + let text_clause = format!( | ||
| 185 | + "({} CONTAINS $q OR {} CONTAINS $q OR {} CONTAINS $q)", | ||
| 186 | + search_fold_sql("username"), | ||
| 187 | + search_fold_sql("name ?? ''"), | ||
| 188 | + search_fold_sql("surname ?? ''"), | ||
| 189 | + ); | ||
| 190 | + let mut clauses = Vec::new(); | ||
| 191 | + if !needle.is_empty() { | ||
| 192 | + clauses.push(text_clause.as_str()); | ||
| 193 | + } | ||
| 194 | + if role.is_some() { | ||
| 195 | + clauses.push("role = $role"); | ||
| 196 | + } | ||
| 197 | + if allowed_roles.is_some() { | ||
| 198 | + clauses.push("role IN $allowed"); | ||
| 199 | + } | ||
| 200 | + let where_clause = if clauses.is_empty() { | ||
| 201 | + "true".to_string() | ||
| 202 | + } else { | ||
| 203 | + clauses.join(" AND ") | ||
| 204 | + }; | ||
| 205 | + let mut list = PagedList::new(format!("user WHERE {where_clause}"), "ORDER BY username") | ||
| 206 | + .bind("q", needle); | ||
| 207 | + if let Some(role) = role { | ||
| 208 | + list = list.bind("role", role); | ||
| 209 | + } | ||
| 210 | + if let Some(allowed) = allowed_roles { | ||
| 211 | + list = list.bind("allowed", allowed.to_vec()); | ||
| 212 | + } | ||
| 213 | + list.run(limit, offset, db).await | ||
| 214 | +} | ||
| 215 | + | ||
| 216 | +/// The role write and every sweep it owes, in one transaction — the | ||
| 217 | +/// statement list behind [`crate::service::user::set_role`]. See there for | ||
| 218 | +/// the floor that guards it and the arm-by-arm reasoning; what follows is | ||
| 219 | +/// the store side. | ||
| 220 | +/// | ||
| 221 | +/// Writes *only* the `role` field of the user row (never the whole row): | ||
| 222 | +/// the row mixes admin-owned (role) and self-service (profile, preferences) | ||
| 223 | +/// fields, and each writer starts from a snapshot read at request start. A | ||
| 224 | +/// whole-row write would carry the snapshot's copy of the *other* group back | ||
| 225 | +/// over a concurrent edit — an in-flight profile save silently reverting an | ||
| 226 | +/// admin's demotion, or this write erasing a profile edit that raced it. | ||
| 227 | +/// [`crate::db::user::set_profile`] and | ||
| 228 | +/// [`crate::db::user::set_preferences`] are scoped for the same reason. | ||
| 229 | +/// | ||
| 230 | +/// What is swept, and why the conditions differ: | ||
| 231 | +/// | ||
| 232 | +/// * **Non-student** sheds class memberships, *every* enrollment row | ||
| 233 | +/// (hand-placed ones included — only students enroll, and a kept row | ||
| 234 | +/// would grant nothing and count a seat) and the parent links observing | ||
| 235 | +/// them. Memberships and enrollments were already one transaction and | ||
| 236 | +/// still are: released apart, an enrollment row could be left tagged with | ||
| 237 | +/// a class whose counters had been given back, so the class passed its | ||
| 238 | +/// zero-zero delete guard and no sweep could ever reach the row again. | ||
| 239 | +/// * **Parent** additionally frees event seats, comes off every whiteboard | ||
| 240 | +/// roster and has the boards they *created* closed — permanently | ||
| 241 | +/// read-only, rows kept, because a room whose creator is demoted is | ||
| 242 | +/// commandable by nobody at all (see the statement's own note). The seat | ||
| 243 | +/// is the one thing on a signup list nothing | ||
| 244 | +/// else could remove: staff free their own by hand (`unregister` allows | ||
| 245 | +/// the self case) but a parent can reach no such door, so a promotion | ||
| 246 | +/// strands nothing and only this demotion does. A list that has already | ||
| 247 | +/// **frozen** ([`REGISTRATION_FROZEN_GUARD`]) is left exactly as it | ||
| 248 | +/// stands — past the freeze it is historical record, re-registering | ||
| 249 | +/// answers 409, and rewriting it here would be irrecoverable. A signup | ||
| 250 | +/// whose event record is *gone* has no seat to hand back and no list that | ||
| 251 | +/// can freeze, so it is deleted rather than skipped: skipped, it is | ||
| 252 | +/// stranded forever (`unregister` 404s on the missing event). | ||
| 253 | +/// * **Below teacher** gives up course staffing and homeroom-teacher | ||
| 254 | +/// columns — only teacher+ may hold either — and the published | ||
| 255 | +/// appointment calendar, whose live bookings are cancelled in the same | ||
| 256 | +/// breath. Nothing else could ever reach those: a slot is listed only on | ||
| 257 | +/// its own teacher's calendar and deleted only by a teacher+, so after the | ||
| 258 | +/// demotion neither its owner nor a manager has a route that yields its | ||
| 259 | +/// id, and a booking on it can be neither decided (teacher+ only) nor | ||
| 260 | +/// cancelled once its window opens — leaving the slot's `occupied` seat | ||
| 261 | +/// pinned at one and the slot itself undeletable forever. The requester | ||
| 262 | +/// keeps the row, `cancelled`, with the teacher on `cancelled_by` and the | ||
| 263 | +/// reason on `cancel_reason`; the slot it pointed at is gone, so the | ||
| 264 | +/// booking renders without a window | ||
| 265 | +/// ([`crate::domain::appointment::Appointment`]'s reader already treats a | ||
| 266 | +/// vanished slot that way). There is no notification anywhere in | ||
| 267 | +/// this crate, so a settled row the person can read is the strongest | ||
| 268 | +/// defined end available — and the alternative, deleting it, would make a | ||
| 269 | +/// confirmed meeting vanish with no trace at all. | ||
| 270 | +/// | ||
| 271 | +/// The returned boards are the rooms whose roster this changed, plus those | ||
| 272 | +/// the user created — whose roster is untouched but which are now closed, | ||
| 273 | +/// and they carry that stamp because the close is written first. Publishing | ||
| 274 | +/// to them is the caller's job: an in-process | ||
| 275 | +/// fan-out cannot sit inside a database transaction, and a room told before | ||
| 276 | +/// the commit would re-read the pre-commit state. | ||
| 277 | +/// | ||
| 278 | +/// Admissible for [`transaction_with_retry`] by construction: `SELECT`, | ||
| 279 | +/// `UPDATE` and `DELETE` only, so no statement can answer "already exists" | ||
| 280 | +/// and every lost round is a plain re-send. | ||
| 281 | +pub async fn set_role_cascade( | ||
| 282 | + db: &Database, | ||
| 283 | + target: &UserId, | ||
| 284 | + role: Role, | ||
| 285 | +) -> Result<(User, Vec<Board>), AppError> { | ||
| 286 | + // Built as a statement list rather than one string so the result slot | ||
| 287 | + // of the board write is *counted*, not hand-tallied against arms that | ||
| 288 | + // may or may not be in the batch. Slot 0 is `BEGIN`, as everywhere. | ||
| 289 | + let mut batch = vec![ | ||
| 290 | + "BEGIN TRANSACTION".to_string(), | ||
| 291 | + "UPDATE $usr SET role = $role RETURN AFTER".to_string(), | ||
| 292 | + ]; | ||
| 293 | + if role != Role::Student { | ||
| 294 | + batch.push(format!( | ||
| 295 | + "LET $links = (DELETE {CLASS_MEMBER_TABLE} WHERE user = $usr RETURN BEFORE)" | ||
| 296 | + )); | ||
| 297 | + batch.push(format!( | ||
| 298 | + "FOR $link IN ($links ?? []) {{ UPDATE $link.class SET \ | ||
| 299 | + {CLASS_MEMBER_COUNT_FIELD} = \ | ||
| 300 | + math::max([({CLASS_MEMBER_COUNT_FIELD} ?? 0) - 1, 0]); }}" | ||
| 301 | + )); | ||
| 302 | + batch.push(format!( | ||
| 303 | + "LET $rows = (DELETE {ENROLLMENT_TABLE} WHERE user = $usr RETURN BEFORE)" | ||
| 304 | + )); | ||
| 305 | + batch.push(format!( | ||
| 306 | + "FOR $row IN ($rows ?? []) {{ UPDATE $row.course SET \ | ||
| 307 | + {ENROLLMENT_COUNT_FIELD} = \ | ||
| 308 | + math::max([({ENROLLMENT_COUNT_FIELD} ?? 0) - 1, 0]); }}" | ||
| 309 | + )); | ||
| 310 | + batch.push(format!("DELETE {PARENT_LINK_TABLE} WHERE student = $usr")); | ||
| 311 | + } | ||
| 312 | + let mut board_slot = None; | ||
| 313 | + if role == Role::Parent { | ||
| 314 | + batch.push(format!( | ||
| 315 | + "LET $signups = (SELECT * FROM {REGISTRATION_TABLE} WHERE user = $usr)" | ||
| 316 | + )); | ||
| 317 | + // Row and seat move together per signup, the way `unregister` does: | ||
| 318 | + // the seats are independent facts on unrelated events. A missing | ||
| 319 | + // event matches nothing in the guard *and* nothing in the counter | ||
| 320 | + // write, which is precisely the orphan rule. | ||
| 321 | + batch.push(format!( | ||
| 322 | + "FOR $signup IN ($signups ?? []) {{ \ | ||
| 323 | + IF array::len((SELECT VALUE id FROM $signup.event \ | ||
| 324 | + WHERE {REGISTRATION_FROZEN_GUARD})) = 0 {{ \ | ||
| 325 | + LET $freed = (DELETE $signup.id RETURN BEFORE); \ | ||
| 326 | + UPDATE $signup.event SET {REGISTRATION_COUNT_FIELD} = \ | ||
| 327 | + math::max([({REGISTRATION_COUNT_FIELD} ?? 0) - array::len($freed), 0]); \ | ||
| 328 | + }}; }}" | ||
| 329 | + )); | ||
| 330 | + // A room whose *creator* is demoted can never be ended by anyone: | ||
| 331 | + // the whiteboard is closed to parents outright, so the creator is | ||
| 332 | + // 404'd off their own board, `clear`/`lock`/`close`/`delete` are | ||
| 333 | + // creator-only for everyone else, and `Board::list_for_user` is the | ||
| 334 | + // crate's only enumeration — no manager or admin can so much as find | ||
| 335 | + // the id. Its participants meanwhile keep drawing (the room re-derives | ||
| 336 | + // membership per frame and they still pass), into a board only the | ||
| 337 | + // 50 000-stroke lifetime cap could ever retire. So the demotion | ||
| 338 | + // retires it, with the same compare-and-set [`Board::close`] uses: an | ||
| 339 | + // already-closed board keeps its first stamp. Closed and not deleted | ||
| 340 | + // because the marks are the participants' work too — they keep reading | ||
| 341 | + // the board and its whole history, and the creator's `board_count` | ||
| 342 | + // seat stays taken, which is correct while the row it counts exists. | ||
| 343 | + // Stamped *before* the roster strip so the strip's `RETURN AFTER` | ||
| 344 | + // carries the closed row the caller fans out. | ||
| 345 | + batch.push(format!( | ||
| 346 | + "UPDATE {BOARD_TABLE} SET closed_at = $now WHERE creator = $usr AND closed_at = NONE" | ||
| 347 | + )); | ||
| 348 | + board_slot = Some(batch.len()); | ||
| 349 | + batch.push(format!( | ||
| 350 | + "UPDATE {BOARD_TABLE} SET participants -= $usr \ | ||
| 351 | + WHERE $usr IN participants OR creator = $usr RETURN AFTER" | ||
| 352 | + )); | ||
| 353 | + } | ||
| 354 | + if role != Role::Parent { | ||
| 355 | + batch.push(format!("DELETE {PARENT_LINK_TABLE} WHERE parent = $usr")); | ||
| 356 | + } | ||
| 357 | + if !role.at_least(Role::Teacher) { | ||
| 358 | + batch.push(format!( | ||
| 359 | + "UPDATE {COURSE_TABLE} SET teachers -= $usr WHERE $usr IN teachers" | ||
| 360 | + )); | ||
| 361 | + batch.push(format!( | ||
| 362 | + "UPDATE {CLASS_GROUP_TABLE} SET teacher = NONE WHERE teacher = $usr" | ||
| 363 | + )); | ||
| 364 | + // The published calendar goes too, and the bookings on it are | ||
| 365 | + // settled first: a slot only its own teacher can list and only a | ||
| 366 | + // teacher+ can delete is reachable by nobody once that teacher is | ||
| 367 | + // demoted, and a live booking on one is worse — nobody can approve, | ||
| 368 | + // reject or (past its start) cancel it, so it pins the slot's | ||
| 369 | + // `occupied` seat forever. Cancelled rather than deleted so the | ||
| 370 | + // person who asked is left with a settled booking they can still | ||
| 371 | + // read, carrying who dropped it and why; the slot row (and with it | ||
| 372 | + // the seat) goes, which is what makes this convergent. | ||
| 373 | + batch.push(format!( | ||
| 374 | + "LET $slots = (SELECT VALUE id FROM {APPOINTMENT_SLOT_TABLE} WHERE teacher = $usr)" | ||
| 375 | + )); | ||
| 376 | + batch.push(format!( | ||
| 377 | + "UPDATE {APPOINTMENT_TABLE} SET status = '{cancelled}', cancelled_by = $usr, \ | ||
| 378 | + cancel_reason = 'the teacher no longer holds a teaching role' \ | ||
| 379 | + WHERE slot IN $slots AND status IN ['{pending}', '{approved}']", | ||
| 380 | + cancelled = AppointmentStatus::Cancelled.as_str(), | ||
| 381 | + pending = AppointmentStatus::Pending.as_str(), | ||
| 382 | + approved = AppointmentStatus::Approved.as_str(), | ||
| 383 | + )); | ||
| 384 | + // Deleting the slots is also what makes a *concurrent* booking safe: | ||
| 385 | + // `Appointment::book` claims the slot row this deletes, so the two | ||
| 386 | + // collide in the store and the loser re-sends. A slot *published* | ||
| 387 | + // concurrently shares no key with any of this, which is why | ||
| 388 | + // `AppointmentSlot::insert_claimed` claims the user row instead. | ||
| 389 | + batch.push(format!( | ||
| 390 | + "DELETE {APPOINTMENT_SLOT_TABLE} WHERE id IN $slots" | ||
| 391 | + )); | ||
| 392 | + } | ||
| 393 | + let sql = format!("{};\nCOMMIT TRANSACTION;", batch.join(";\n")); | ||
| 394 | + let (mut result, mut errors) = transaction_with_retry( | ||
| 395 | + db, | ||
| 396 | + &sql, | ||
| 397 | + &[ | ||
| 398 | + ("usr".into(), target.record().into_value()), | ||
| 399 | + ("role".into(), role.into_value()), | ||
| 400 | + ("now".into(), Timestamp::now().as_millis().into_value()), | ||
| 401 | + ], | ||
| 402 | + &[], | ||
| 403 | + ) | ||
| 404 | + .await?; | ||
| 405 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 406 | + return Err(error.into()); | ||
| 407 | + } | ||
| 408 | + let updated = result | ||
| 409 | + .take::<Vec<User>>(1)? | ||
| 410 | + .into_iter() | ||
| 411 | + .next() | ||
| 412 | + .ok_or(AppError::NotFound)?; | ||
| 413 | + let boards = match board_slot { | ||
| 414 | + Some(slot) => result.take::<Vec<Board>>(slot)?, | ||
| 415 | + None => Vec::new(), | ||
| 416 | + }; | ||
| 417 | + Ok((updated, boards)) | ||
| 418 | +} | ||
| 419 | + | ||
| 420 | +/// Write the personal-info and public-profile fields the request actually | ||
| 421 | +/// carried — everything a person edits about themselves except the avatar | ||
| 422 | +/// blob, which needs its own writer ([`set_avatar`]). Every | ||
| 423 | +/// column is nullable, so each argument is an outer/inner `Option`: `None` | ||
| 424 | +/// = omitted (not written at all), `Some(None)` = cleared, `Some(Some(v))` | ||
| 425 | +/// = set. Merging the request against the current row is the HTTP layer's | ||
| 426 | +/// job; the caller authorizes. | ||
| 427 | +/// | ||
| 428 | +/// Request-scoped, not merely field-scoped: nothing guards the row across | ||
| 429 | +/// the handler's read and this write, so re-sending the snapshot's value | ||
| 430 | +/// for an omitted field would revert a concurrent PATCH of that field — | ||
| 431 | +/// two profile edits (a name and a phone) used to lose each other. See | ||
| 432 | +/// [`set_role_cascade`] for why no writer here touches the whole row. | ||
| 433 | +// One argument per nullable column is the point: folding them into a struct | ||
| 434 | +// would just re-spell the HTTP DTO here and cost the compiler's check that | ||
| 435 | +// every column was considered at the call site. | ||
| 436 | +#[allow(clippy::too_many_arguments)] | ||
| 437 | +pub async fn set_profile( | ||
| 438 | + db: &Database, | ||
| 439 | + id: &UserId, | ||
| 440 | + name: Option<Option<PersonName>>, | ||
| 441 | + surname: Option<Option<PersonName>>, | ||
| 442 | + email: Option<Option<Email>>, | ||
| 443 | + phone: Option<Option<Phone>>, | ||
| 444 | + birth_date: Option<Option<BirthDate>>, | ||
| 445 | + display_name: Option<Option<DisplayName>>, | ||
| 446 | + bio: Option<Option<Bio>>, | ||
| 447 | +) -> Result<User, AppError> { | ||
| 448 | + FieldUpdate::new(id.record()) | ||
| 449 | + .set("name", name) | ||
| 450 | + .set("surname", surname) | ||
| 451 | + .set("email", email) | ||
| 452 | + .set("phone", phone) | ||
| 453 | + .set("birth_date", birth_date) | ||
| 454 | + .set("display_name", display_name) | ||
| 455 | + .set("bio", bio) | ||
| 456 | + .run::<User>(db) | ||
| 457 | + .await | ||
| 458 | +} | ||
| 459 | + | ||
| 460 | +/// Point the row at a freshly uploaded avatar blob, returning the row *as | ||
| 461 | +/// it was* — the caller deletes `before.get_avatar_file()` off disk. Losing | ||
| 462 | +/// `RETURN BEFORE` here strands the replaced blob forever: no route ever | ||
| 463 | +/// deletes a user, so nothing else would collect it. | ||
| 464 | +/// | ||
| 465 | +/// Field-scoped for the same reason as [`set_profile`]: an avatar | ||
| 466 | +/// upload must not carry a stale snapshot's role back over an admin's | ||
| 467 | +/// change. `None` means the row is gone. | ||
| 468 | +/// | ||
| 469 | +/// Sent through [`write_with_retry`] like every other single-statement row | ||
| 470 | +/// write here, unguarded or not: the user row is contended (preferences, | ||
| 471 | +/// profile, role all write it), and a lost round wrote nothing, so | ||
| 472 | +/// re-sending it is the recovery rather than a 500 in the caller's face. | ||
| 473 | +pub async fn set_avatar( | ||
| 474 | + db: &Database, | ||
| 475 | + id: &UserId, | ||
| 476 | + file: &str, | ||
| 477 | + content_type: &FileContentType, | ||
| 478 | + size: i64, | ||
| 479 | +) -> Result<Option<User>, AppError> { | ||
| 480 | + let rows: Vec<User> = write_with_retry( | ||
| 481 | + db, | ||
| 482 | + "UPDATE $u SET avatar_file = $file, avatar_content_type = $ct, avatar_size = $size \ | ||
| 483 | + RETURN BEFORE", | ||
| 484 | + &[ | ||
| 485 | + ("u".into(), id.record().into_value()), | ||
| 486 | + ("file".into(), file.to_string().into_value()), | ||
| 487 | + ("ct".into(), content_type.clone().into_value()), | ||
| 488 | + ("size".into(), size.into_value()), | ||
| 489 | + ], | ||
| 490 | + ) | ||
| 491 | + .await?; | ||
| 492 | + Ok(rows.into_iter().next()) | ||
| 493 | +} | ||
| 494 | + | ||
| 495 | +/// Drop the avatar, returning the row as it was so the caller can delete | ||
| 496 | +/// the blob. Same `RETURN BEFORE` contract as [`set_avatar`]. | ||
| 497 | +pub async fn clear_avatar(db: &Database, id: &UserId) -> Result<Option<User>, AppError> { | ||
| 498 | + let rows: Vec<User> = write_with_retry( | ||
| 499 | + db, | ||
| 500 | + "UPDATE $u SET avatar_file = NONE, avatar_content_type = NONE, \ | ||
| 501 | + avatar_size = NONE RETURN BEFORE", | ||
| 502 | + &[("u".into(), id.record().into_value())], | ||
| 503 | + ) | ||
| 504 | + .await?; | ||
| 505 | + Ok(rows.into_iter().next()) | ||
| 506 | +} | ||
| 507 | + | ||
| 508 | +/// Replace a user's password hash — the builder's admin-password reset | ||
| 509 | +/// (`POST /schools/{slug}/admin-password`). Only the credential is | ||
| 510 | +/// rewritten; revoking the sessions minted under the old one is the | ||
| 511 | +/// caller's second half | ||
| 512 | +/// ([`crate::db::session::delete_by_user`]), because a reset | ||
| 513 | +/// that leaves a stolen cookie working resets nothing. | ||
| 514 | +pub async fn set_password_hash( | ||
| 515 | + db: &Database, | ||
| 516 | + id: &UserId, | ||
| 517 | + password_hash: PasswordHash, | ||
| 518 | +) -> Result<Option<User>, AppError> { | ||
| 519 | + let rows: Vec<User> = write_with_retry( | ||
| 520 | + db, | ||
| 521 | + "UPDATE $u SET password_hash = $hash RETURN AFTER", | ||
| 522 | + &[ | ||
| 523 | + ("u".into(), id.record().into_value()), | ||
| 524 | + ("hash".into(), password_hash.into_value()), | ||
| 525 | + ], | ||
| 526 | + ) | ||
| 527 | + .await?; | ||
| 528 | + Ok(rows.into_iter().next()) | ||
| 529 | +} | ||
| 530 | + | ||
| 531 | +/// Write the UI-preference fields the request actually carried. Same | ||
| 532 | +/// contract as [`set_profile`]: `None` = omitted (not written), | ||
| 533 | +/// `Some(None)` = cleared back to "never chose", `Some(Some(v))` = set. | ||
| 534 | +pub async fn set_preferences( | ||
| 535 | + db: &Database, | ||
| 536 | + id: &UserId, | ||
| 537 | + theme: Option<Option<Theme>>, | ||
| 538 | + language: Option<Option<Language>>, | ||
| 539 | + palette_color: Option<Option<PaletteColor>>, | ||
| 540 | +) -> Result<User, AppError> { | ||
| 541 | + FieldUpdate::new(id.record()) | ||
| 542 | + .set("theme", theme) | ||
| 543 | + .set("language", language) | ||
| 544 | + .set("palette_color", palette_color) | ||
| 545 | + .run::<User>(db) | ||
| 546 | + .await | ||
| 547 | +} | ||
| 548 | + | ||
| 549 | +pub async fn find_by_username(db: &Database, username: &str) -> Result<Option<User>, AppError> { | ||
| 550 | + let mut result = db | ||
| 551 | + .query("SELECT * FROM user WHERE username = $username LIMIT 1") | ||
| 552 | + .bind(("username", username.to_string())) | ||
| 553 | + .await? | ||
| 554 | + .check()?; | ||
| 555 | + Ok(result.take::<Vec<User>>(0)?.into_iter().next()) | ||
| 556 | +} | ||
| 557 | + | ||
| 558 | +#[cfg(test)] | ||
| 559 | +mod tests { | ||
| 560 | + use super::*; | ||
| 561 | + use crate::database::init_mem; | ||
| 562 | + use crate::domain::user::Password; | ||
| 563 | + | ||
| 564 | + fn png() -> FileContentType { | ||
| 565 | + FileContentType::try_new("image/png").unwrap() | ||
| 566 | + } | ||
| 567 | + | ||
| 568 | + async fn a_user(username: &str, db: &Database) -> User { | ||
| 569 | + create( | ||
| 570 | + db, | ||
| 571 | + Username::try_new(username).unwrap(), | ||
| 572 | + Password::try_new("secret1") | ||
| 573 | + .unwrap() | ||
| 574 | + .hash_async() | ||
| 575 | + .await | ||
| 576 | + .unwrap(), | ||
| 577 | + ) | ||
| 578 | + .await | ||
| 579 | + .unwrap() | ||
| 580 | + } | ||
| 581 | + | ||
| 582 | + #[tokio::test] | ||
| 583 | + async fn a_stale_profile_write_cannot_revert_a_role_change() { | ||
| 584 | + let db = init_mem().await.unwrap(); | ||
| 585 | + let user = a_user("aysenur", &db).await; | ||
| 586 | + | ||
| 587 | + // A PATCH /users/me handler reads its snapshot (role = student)... | ||
| 588 | + let stale = read(&db, user.get_id()).await.unwrap().unwrap(); | ||
| 589 | + | ||
| 590 | + // ...then an admin's role change commits before the profile save runs. | ||
| 591 | + crate::service::user::set_role(&db, user.get_id(), Role::Teacher) | ||
| 592 | + .await | ||
| 593 | + .unwrap(); | ||
| 594 | + | ||
| 595 | + // The in-flight save lands from the stale snapshot. It must write only | ||
| 596 | + // the profile fields — not carry the snapshot's old role back over the | ||
| 597 | + // admin's change. | ||
| 598 | + let name = PersonName::try_new("name", "Ayşenur").unwrap(); | ||
| 599 | + set_profile( | ||
| 600 | + &db, | ||
| 601 | + stale.get_id(), | ||
| 602 | + Some(Some(name.clone())), | ||
| 603 | + None, | ||
| 604 | + None, | ||
| 605 | + None, | ||
| 606 | + None, | ||
| 607 | + None, | ||
| 608 | + None, | ||
| 609 | + ) | ||
| 610 | + .await | ||
| 611 | + .unwrap(); | ||
| 612 | + | ||
| 613 | + let after = read(&db, user.get_id()).await.unwrap().unwrap(); | ||
| 614 | + assert_eq!( | ||
| 615 | + after.get_role(), | ||
| 616 | + Role::Teacher, | ||
| 617 | + "the role change must survive the racing profile write" | ||
| 618 | + ); | ||
| 619 | + assert_eq!( | ||
| 620 | + after.get_name(), | ||
| 621 | + Some(&name), | ||
| 622 | + "the profile edit itself lands" | ||
| 623 | + ); | ||
| 624 | + } | ||
| 625 | + | ||
| 626 | + #[tokio::test] | ||
| 627 | + async fn an_avatar_upload_cannot_revert_a_role_change() { | ||
| 628 | + let db = init_mem().await.unwrap(); | ||
| 629 | + let user = a_user("berk", &db).await; | ||
| 630 | + | ||
| 631 | + // The upload handler holds its snapshot (role = student)... | ||
| 632 | + let stale = read(&db, user.get_id()).await.unwrap().unwrap(); | ||
| 633 | + | ||
| 634 | + // ...an admin promotes and the person edits their bio, both while the | ||
| 635 | + // blob is still being written... | ||
| 636 | + crate::service::user::set_role(&db, user.get_id(), Role::Teacher) | ||
| 637 | + .await | ||
| 638 | + .unwrap(); | ||
| 639 | + let display_name = DisplayName::try_new("Berk").unwrap(); | ||
| 640 | + set_profile( | ||
| 641 | + &db, | ||
| 642 | + user.get_id(), | ||
| 643 | + None, | ||
| 644 | + None, | ||
| 645 | + None, | ||
| 646 | + None, | ||
| 647 | + None, | ||
| 648 | + Some(Some(display_name.clone())), | ||
| 649 | + None, | ||
| 650 | + ) | ||
| 651 | + .await | ||
| 652 | + .unwrap(); | ||
| 653 | + | ||
| 654 | + // ...and only then does the avatar land, from the stale row's id. | ||
| 655 | + set_avatar(&db, stale.get_id(), "blob-1", &png(), 42) | ||
| 656 | + .await | ||
| 657 | + .unwrap() | ||
| 658 | + .expect("the row exists"); | ||
| 659 | + | ||
| 660 | + let after = read(&db, user.get_id()).await.unwrap().unwrap(); | ||
| 661 | + assert_eq!( | ||
| 662 | + after.get_role(), | ||
| 663 | + Role::Teacher, | ||
| 664 | + "the role change must survive the racing avatar write" | ||
| 665 | + ); | ||
| 666 | + assert_eq!( | ||
| 667 | + after.get_display_name(), | ||
| 668 | + Some(&display_name), | ||
| 669 | + "and so must every other column the avatar write never named" | ||
| 670 | + ); | ||
| 671 | + assert_eq!(after.get_avatar_file(), Some("blob-1")); | ||
| 672 | + assert_eq!(after.get_avatar_content_type(), Some(&png())); | ||
| 673 | + assert_eq!(after.get_avatar_size(), Some(42)); | ||
| 674 | + } | ||
| 675 | + | ||
| 676 | + /// The blob cleanup is built entirely on `RETURN BEFORE`: without the old | ||
| 677 | + /// `avatar_file` coming back, every replace strands a file on disk that no | ||
| 678 | + /// route ever collects. | ||
| 679 | + #[tokio::test] | ||
| 680 | + async fn the_avatar_writers_return_the_replaced_blob() { | ||
| 681 | + let db = init_mem().await.unwrap(); | ||
| 682 | + let user = a_user("ceyda", &db).await; | ||
| 683 | + | ||
| 684 | + let before = set_avatar(&db, user.get_id(), "blob-1", &png(), 10) | ||
| 685 | + .await | ||
| 686 | + .unwrap() | ||
| 687 | + .expect("the row exists"); | ||
| 688 | + assert_eq!(before.get_avatar_file(), None, "no blob to collect yet"); | ||
| 689 | + | ||
| 690 | + let before = set_avatar(&db, user.get_id(), "blob-2", &png(), 20) | ||
| 691 | + .await | ||
| 692 | + .unwrap() | ||
| 693 | + .expect("the row exists"); | ||
| 694 | + assert_eq!( | ||
| 695 | + before.get_avatar_file(), | ||
| 696 | + Some("blob-1"), | ||
| 697 | + "the replaced blob is what the caller must delete" | ||
| 698 | + ); | ||
| 699 | + | ||
| 700 | + let before = clear_avatar(&db, user.get_id()) | ||
| 701 | + .await | ||
| 702 | + .unwrap() | ||
| 703 | + .expect("the row exists"); | ||
| 704 | + assert_eq!(before.get_avatar_file(), Some("blob-2")); | ||
| 705 | + | ||
| 706 | + let after = read(&db, user.get_id()).await.unwrap().unwrap(); | ||
| 707 | + assert_eq!(after.get_avatar_file(), None); | ||
| 708 | + assert_eq!(after.get_avatar_content_type(), None); | ||
| 709 | + assert_eq!(after.get_avatar_size(), None); | ||
| 710 | + | ||
| 711 | + assert!( | ||
| 712 | + clear_avatar(&db, &UserId::from_key("yok")) | ||
| 713 | + .await | ||
| 714 | + .unwrap() | ||
| 715 | + .is_none(), | ||
| 716 | + "a missing row is None, not an error" | ||
| 717 | + ); | ||
| 718 | + } | ||
| 719 | +} | ||
src/domain/board.rsmodified+2 -2
| @@ -48,7 +48,7 @@ use crate::validate::validate_required; | |||
| 48 | /// read, one user-list read and one field write. | 48 | /// read, one user-list read and one field write. |
| 49 | /// | 49 | /// |
| 50 | /// **A leaf**: nothing under it takes another lock. Note it does not reach the | 50 | /// **A leaf**: nothing under it takes another lock. Note it does not reach the |
| 51 | -/// demotion sweep in [`crate::domain::user::User::set_role`], which strips ids | 51 | +/// demotion sweep in [`crate::service::user::set_role`], which strips ids |
| 52 | /// from every roster inside the role write's own transaction — an invite that | 52 | /// from every roster inside the role write's own transaction — an invite that |
| 53 | /// read a roster before that sweep can put a swept id back, which the boot | 53 | /// read a roster before that sweep can put a swept id back, which the boot |
| 54 | /// repair and the room's own live gate both still catch. | 54 | /// repair and the room's own live gate both still catch. |
| @@ -310,7 +310,7 @@ impl Board { | |||
| 310 | 310 | ||
| 311 | // The demotion sweep — stripping a user off every roster they are listed | 311 | // The demotion sweep — stripping a user off every roster they are listed |
| 312 | // on, deleting nothing, and handing the affected rooms back so the caller | 312 | // on, deleting nothing, and handing the affected rooms back so the caller |
| 313 | - // can prompt them — lives in [`crate::domain::user::User::set_role`], where | 313 | + // can prompt them — lives in [`crate::service::user::set_role`], where |
| 314 | // it commits with the role write that invalidates the membership. | 314 | // it commits with the role write that invalidates the membership. |
| 315 | 315 | ||
| 316 | /// Retire the board: permanently read-only, history still readable. | 316 | /// Retire the board: permanently read-only, history still readable. |
src/domain/class_member.rsmodified+9 -6
| @@ -544,10 +544,10 @@ pub(crate) mod tests { | |||
| 544 | .hash_async() | 544 | .hash_async() |
| 545 | .await | 545 | .await |
| 546 | .unwrap(); | 546 | .unwrap(); |
| 547 | - let account = crate::domain::user::User::create( | 547 | + let account = crate::db::user::create( |
| 548 | + &db, | ||
| 548 | crate::domain::user::Username::try_new("ogrenci").unwrap(), | 549 | crate::domain::user::Username::try_new("ogrenci").unwrap(), |
| 549 | hash, | 550 | hash, |
| 550 | - &db, | ||
| 551 | ) | 551 | ) |
| 552 | .await | 552 | .await |
| 553 | .unwrap(); | 553 | .unwrap(); |
| @@ -565,10 +565,13 @@ pub(crate) mod tests { | |||
| 565 | .await | 565 | .await |
| 566 | .unwrap(); | 566 | .unwrap(); |
| 567 | 567 | ||
| 568 | - account | 568 | + crate::service::user::set_role( |
| 569 | - .set_role(crate::domain::role::Role::Teacher, &db) | 569 | + &db, |
| 570 | - .await | 570 | + account.get_id(), |
| 571 | - .unwrap(); | 571 | + crate::domain::role::Role::Teacher, |
| 572 | + ) | ||
| 573 | + .await | ||
| 574 | + .unwrap(); | ||
| 572 | assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); | 575 | assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); |
| 573 | for class in [&first, &second] { | 576 | for class in [&first, &second] { |
| 574 | assert_eq!( | 577 | assert_eq!( |
src/domain/class_pump.rsmodified+1 -1
| @@ -347,7 +347,7 @@ impl Axis { | |||
| 347 | // The sweep a role change *off* `student` owes — every class membership (each | 347 | // The sweep a role change *off* `student` owes — every class membership (each |
| 348 | // class getting its member count back) and every enrollment row (each course | 348 | // class getting its member count back) and every enrollment row (each course |
| 349 | // getting its seat back) — is two of the arms of | 349 | // getting its seat back) — is two of the arms of |
| 350 | -// [`crate::domain::user::User::set_role`], because it belongs in the same | 350 | +// [`crate::service::user::set_role`], because it belongs in the same |
| 351 | // transaction as the role write that invalidates them. It stays one fact with | 351 | // transaction as the role write that invalidates them. It stays one fact with |
| 352 | // the counters either way: released separately, a failure between the halves | 352 | // the counters either way: released separately, a failure between the halves |
| 353 | // left enrollment rows tagged `source = class_group:X` while the class had its | 353 | // left enrollment rows tagged `source = class_group:X` while the class had its |
src/domain/event.rsmodified+3 -3
| @@ -147,13 +147,13 @@ impl EventAudience { | |||
| 147 | /// are kept; the caller degrades their display like any stale reference. | 147 | /// are kept; the caller degrades their display like any stale reference. |
| 148 | pub async fn members(&self, event: &EventId, db: &Database) -> Result<Vec<UserId>, AppError> { | 148 | pub async fn members(&self, event: &EventId, db: &Database) -> Result<Vec<UserId>, AppError> { |
| 149 | match self { | 149 | match self { |
| 150 | - EventAudience::School => Ok(User::list_all(None, 0, db) | 150 | + EventAudience::School => Ok(crate::db::user::list_all(db, None, 0) |
| 151 | .await? | 151 | .await? |
| 152 | .0 | 152 | .0 |
| 153 | .iter() | 153 | .iter() |
| 154 | .map(|user| user.get_id().clone()) | 154 | .map(|user| user.get_id().clone()) |
| 155 | .collect()), | 155 | .collect()), |
| 156 | - EventAudience::Role { role } => Ok(User::list_by_role(*role, db) | 156 | + EventAudience::Role { role } => Ok(crate::db::user::list_by_role(db, *role) |
| 157 | .await? | 157 | .await? |
| 158 | .iter() | 158 | .iter() |
| 159 | .map(|user| user.get_id().clone()) | 159 | .map(|user| user.get_id().clone()) |
| @@ -359,7 +359,7 @@ mod tests { | |||
| 359 | /// The forcing function behind the one rule with two spellings: the freeze | 359 | /// The forcing function behind the one rule with two spellings: the freeze |
| 360 | /// this file decides in Rust ([`Event::registration_capacity`]) and | 360 | /// this file decides in Rust ([`Event::registration_capacity`]) and |
| 361 | /// [`crate::constant::REGISTRATION_FROZEN_GUARD`], its SurrealQL copy, which | 361 | /// [`crate::constant::REGISTRATION_FROZEN_GUARD`], its SurrealQL copy, which |
| 362 | - /// the role cascade (`User::set_role`) carries because it frees a demoted | 362 | + /// the role cascade (`service::user::set_role`) carries because it frees a demoted |
| 363 | /// parent's seats inside a transaction and cannot call Rust from there. | 363 | /// parent's seats inside a transaction and cannot call Rust from there. |
| 364 | /// | 364 | /// |
| 365 | /// Every schedule shape is put to both, including the three the SQL is most | 365 | /// Every schedule shape is put to both, including the three the SQL is most |
src/domain/homework_submission.rsmodified+2 -2
| @@ -413,10 +413,10 @@ mod tests { | |||
| 413 | .hash_async() | 413 | .hash_async() |
| 414 | .await | 414 | .await |
| 415 | .unwrap(); | 415 | .unwrap(); |
| 416 | - crate::domain::user::User::create( | 416 | + crate::db::user::create( |
| 417 | + db, | ||
| 417 | crate::domain::user::Username::try_new(username).unwrap(), | 418 | crate::domain::user::Username::try_new(username).unwrap(), |
| 418 | hash, | 419 | hash, |
| 419 | - db, | ||
| 420 | ) | 420 | ) |
| 421 | .await | 421 | .await |
| 422 | .unwrap() | 422 | .unwrap() |
src/domain/parent_link.rsmodified+1 -1
| @@ -122,7 +122,7 @@ impl ParentLink { | |||
| 122 | 122 | ||
| 123 | // Both role-change sweeps (the observed student leaving `student`, the | 123 | // Both role-change sweeps (the observed student leaving `student`, the |
| 124 | // observing parent leaving `parent`) live in | 124 | // observing parent leaving `parent`) live in |
| 125 | - // [`crate::domain::user::User::set_role`]: they commit with the role write | 125 | + // [`crate::service::user::set_role`]: they commit with the role write |
| 126 | // itself, so there is no window where a link outlives the role that | 126 | // itself, so there is no window where a link outlives the role that |
| 127 | // justified it. | 127 | // justified it. |
| 128 | } | 128 | } |
src/domain/registration.rsmodified+4 -4
| @@ -5,7 +5,7 @@ use crate::database::Database; | |||
| 5 | use crate::db::cap; | 5 | use crate::db::cap; |
| 6 | use crate::domain::event::{Event, EventId}; | 6 | use crate::domain::event::{Event, EventId}; |
| 7 | use crate::domain::role::Role; | 7 | use crate::domain::role::Role; |
| 8 | -use crate::domain::user::{User, UserId}; | 8 | +use crate::domain::user::UserId; |
| 9 | use crate::error::AppError; | 9 | use crate::error::AppError; |
| 10 | 10 | ||
| 11 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 11 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| @@ -77,7 +77,7 @@ impl Registration { | |||
| 77 | /// | 77 | /// |
| 78 | /// The seat is claimed on the event row, so the same statement says nothing | 78 | /// The seat is claimed on the event row, so the same statement says nothing |
| 79 | /// about the *user* it is for — and a fall to `parent` is the one demotion | 79 | /// about the *user* it is for — and a fall to `parent` is the one demotion |
| 80 | - /// whose sweep ([`crate::domain::user::User::set_role`]) can miss a seat and | 80 | + /// whose sweep ([`crate::service::user::set_role`]) can miss a seat and |
| 81 | /// leave it unfreeable: `unregister` refuses a non-student target and a | 81 | /// leave it unfreeable: `unregister` refuses a non-student target and a |
| 82 | /// parent cannot reach the route at all. So the transaction also claims the | 82 | /// parent cannot reach the route at all. So the transaction also claims the |
| 83 | /// holder's own record ([`cap::role_claim`]), which is the key that | 83 | /// holder's own record ([`cap::role_claim`]), which is the key that |
| @@ -133,7 +133,7 @@ impl Registration { | |||
| 133 | // the reads that tell them apart. | 133 | // the reads that tell them apart. |
| 134 | cap::Claimed::Full => match Event::read(event, db).await? { | 134 | cap::Claimed::Full => match Event::read(event, db).await? { |
| 135 | None => Err(AppError::NotFound), | 135 | None => Err(AppError::NotFound), |
| 136 | - Some(_) => match User::read(user, db).await? { | 136 | + Some(_) => match crate::db::user::read(db, user).await? { |
| 137 | Some(held) if held.get_role() == Role::Parent => Err(AppError::Forbidden( | 137 | Some(held) if held.get_role() == Role::Parent => Err(AppError::Forbidden( |
| 138 | "that account was demoted to parent while this request ran — \ | 138 | "that account was demoted to parent while this request ran — \ |
| 139 | only students can be registered for", | 139 | only students can be registered for", |
| @@ -194,7 +194,7 @@ impl Registration { | |||
| 194 | 194 | ||
| 195 | // The demotion sweep — freeing every seat a fall to `parent` would strand, | 195 | // The demotion sweep — freeing every seat a fall to `parent` would strand, |
| 196 | // and leaving a list that has already frozen exactly as it stands — is an | 196 | // and leaving a list that has already frozen exactly as it stands — is an |
| 197 | - // arm of [`crate::domain::user::User::set_role`], so the seat comes back in | 197 | + // arm of [`crate::service::user::set_role`], so the seat comes back in |
| 198 | // the same transaction as the role that invalidated it. The freeze it obeys | 198 | // the same transaction as the role that invalidated it. The freeze it obeys |
| 199 | // is [`Event::registration_capacity`]'s `Conflict` arm, re-spelled for | 199 | // is [`Event::registration_capacity`]'s `Conflict` arm, re-spelled for |
| 200 | // SurrealQL as [`crate::constant::REGISTRATION_FROZEN_GUARD`] and held to it | 200 | // SurrealQL as [`crate::constant::REGISTRATION_FROZEN_GUARD`] and held to it |
src/domain/user.rsmodified+26 -1046
| @@ -1,60 +1,30 @@ | |||
| 1 | +//! Pure user shapes: the typed id, the credential newtypes (username, | ||
| 2 | +//! password, argon2 hash — with their blocking-pool discipline), and the row | ||
| 3 | +//! itself. Persistence lives in [`crate::db::user`]; the admin seed and the | ||
| 4 | +//! role change in [`crate::service::user`]. | ||
| 5 | + | ||
| 1 | use std::sync::OnceLock; | 6 | use std::sync::OnceLock; |
| 2 | 7 | ||
| 3 | use argon2::password_hash::SaltString; | 8 | use argon2::password_hash::SaltString; |
| 4 | use argon2::{Argon2, PasswordHasher, PasswordVerifier}; | 9 | use argon2::{Argon2, PasswordHasher, PasswordVerifier}; |
| 5 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 10 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 6 | 11 | ||
| 7 | -use crate::constant::{ | 12 | +use crate::constant::{AI_PRINCIPAL_KEY, DECOY_PASSWORD, USER_TABLE}; |
| 8 | - AI_PRINCIPAL_KEY, APPOINTMENT_SLOT_TABLE, APPOINTMENT_TABLE, BOARD_TABLE, CLASS_GROUP_TABLE, | ||
| 9 | - CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE, COURSE_TABLE, DECOY_PASSWORD, | ||
| 10 | - ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE, PARENT_LINK_TABLE, REGISTRATION_COUNT_FIELD, | ||
| 11 | - REGISTRATION_FROZEN_GUARD, REGISTRATION_TABLE, USER_TABLE, | ||
| 12 | -}; | ||
| 13 | -use crate::database::{Database, transaction_with_retry, write_with_retry}; | ||
| 14 | -use crate::db::field_update::FieldUpdate; | ||
| 15 | -use crate::db::page::PagedList; | ||
| 16 | -use crate::domain::appointment::AppointmentStatus; | ||
| 17 | -use crate::domain::board::Board; | ||
| 18 | use crate::domain::monotonic_id::next_ulid; | 13 | use crate::domain::monotonic_id::next_ulid; |
| 19 | use crate::domain::note_file::FileContentType; | 14 | use crate::domain::note_file::FileContentType; |
| 20 | use crate::domain::preferences::{Language, PaletteColor, Theme}; | 15 | use crate::domain::preferences::{Language, PaletteColor, Theme}; |
| 21 | use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; | 16 | use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; |
| 22 | use crate::domain::role::Role; | 17 | use crate::domain::role::Role; |
| 23 | -use crate::domain::text_fold::{search_fold, search_fold_sql}; | ||
| 24 | -use crate::domain::timestamp::Timestamp; | ||
| 25 | use crate::error::{AppError, ValidationError}; | 18 | use crate::error::{AppError, ValidationError}; |
| 26 | use crate::validate::{validate_password, validate_username}; | 19 | use crate::validate::{validate_password, validate_username}; |
| 27 | 20 | ||
| 28 | -/// One role demotion at a time, school-wide. | ||
| 29 | -/// | ||
| 30 | -/// The invariant it protects is "the school always keeps an admin", and that | ||
| 31 | -/// guard is a count-then-write: read whether another admin exists, then lower | ||
| 32 | -/// this row. SurrealDB conflict-checks neither side of that pair — a | ||
| 33 | -/// `BEGIN…COMMIT` does not serialize a cross-record count against a concurrent | ||
| 34 | -/// update (write-skew, see [`crate::db::cap`]) and a statement that only | ||
| 35 | -/// *reads* the rival's row never collides with it. So two admins demoting each | ||
| 36 | -/// other both counted the other and both committed, leaving **zero** admins and | ||
| 37 | -/// a school nobody can administer: `ensure_admin` refuses to promote an | ||
| 38 | -/// existing non-admin row on every later boot, so the only way back was hand-run | ||
| 39 | -/// SurrealQL against the volume. | ||
| 40 | -/// | ||
| 41 | -/// Serializing the pair is what closes it, the same argument | ||
| 42 | -/// [`crate::service::settings::SETTINGS_LOCK`] makes one level up: the deployment | ||
| 43 | -/// runs one process by contract (stop-the-world upgrades), so process-wide is | ||
| 44 | -/// deployment-wide. A per-row counter (the [`crate::db::cap`] shape) does | ||
| 45 | -/// not fit — the count being capped is over *every* user row, with no parent | ||
| 46 | -/// record to hold it and no place to seed one without a backfill. | ||
| 47 | -/// | ||
| 48 | -/// **Lock order:** taken alone. Nothing is locked while it is held. | ||
| 49 | -static ADMIN_FLOOR_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); | ||
| 50 | - | ||
| 51 | /// Typed user record id (`user:<ulid>`). | 21 | /// Typed user record id (`user:<ulid>`). |
| 52 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 22 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 53 | pub struct UserId(RecordId); | 23 | pub struct UserId(RecordId); |
| 54 | 24 | ||
| 55 | impl UserId { | 25 | impl UserId { |
| 56 | /// Minted from the process-wide monotonic generator, not `Ulid::new()`: | 26 | /// Minted from the process-wide monotonic generator, not `Ulid::new()`: |
| 57 | - /// users list `id DESC` (newest first, [`User::list_all`]) and page by | 27 | + /// users list `id DESC` (newest first, [`crate::db::user::list_all`]) and page by |
| 58 | /// offset over that order, and a random low half scrambles rows minted in | 28 | /// offset over that order, and a random low half scrambles rows minted in |
| 59 | /// the same millisecond. Not a secret: the session token is separate | 29 | /// the same millisecond. Not a secret: the session token is separate |
| 60 | /// (32-byte CSPRNG, `web::auth`), so id order carries no authority. | 30 | /// (32-byte CSPRNG, `web::auth`), so id order carries no authority. |
| @@ -224,35 +194,37 @@ impl PasswordHash { | |||
| 224 | } | 194 | } |
| 225 | 195 | ||
| 226 | #[derive(Debug, Clone, SurrealValue)] | 196 | #[derive(Debug, Clone, SurrealValue)] |
| 197 | +/// Fields are crate-visible: [`crate::db::user`] mints rows and the role | ||
| 198 | +/// cascade reads the id, exactly as the other split domains do. | ||
| 227 | pub struct User { | 199 | pub struct User { |
| 228 | - id: UserId, | 200 | + pub(crate) id: UserId, |
| 229 | - username: Username, | 201 | + pub(crate) username: Username, |
| 230 | - password_hash: PasswordHash, | 202 | + pub(crate) password_hash: PasswordHash, |
| 231 | - role: Role, | 203 | + pub(crate) role: Role, |
| 232 | // Personal info, identical for every role. All optional: accounts are | 204 | // Personal info, identical for every role. All optional: accounts are |
| 233 | // created from bare credentials and filled in later, and rows from before | 205 | // created from bare credentials and filled in later, and rows from before |
| 234 | // these fields existed simply read back as `None`. | 206 | // these fields existed simply read back as `None`. |
| 235 | - name: Option<PersonName>, | 207 | + pub(crate) name: Option<PersonName>, |
| 236 | - surname: Option<PersonName>, | 208 | + pub(crate) surname: Option<PersonName>, |
| 237 | - email: Option<Email>, | 209 | + pub(crate) email: Option<Email>, |
| 238 | - phone: Option<Phone>, | 210 | + pub(crate) phone: Option<Phone>, |
| 239 | - birth_date: Option<BirthDate>, | 211 | + pub(crate) birth_date: Option<BirthDate>, |
| 240 | // Frontend UI preferences. Optional like the personal info: `None` means | 212 | // Frontend UI preferences. Optional like the personal info: `None` means |
| 241 | // "never chose", which the frontend renders as the device preference. | 213 | // "never chose", which the frontend renders as the device preference. |
| 242 | - theme: Option<Theme>, | 214 | + pub(crate) theme: Option<Theme>, |
| 243 | - language: Option<Language>, | 215 | + pub(crate) language: Option<Language>, |
| 244 | - palette_color: Option<PaletteColor>, | 216 | + pub(crate) palette_color: Option<PaletteColor>, |
| 245 | // The public profile: what other people see instead of the credentials. | 217 | // The public profile: what other people see instead of the credentials. |
| 246 | // Optional like everything above — a profile is written after the account | 218 | // Optional like everything above — a profile is written after the account |
| 247 | // exists, so rows from before these fields existed read back as `None`, | 219 | // exists, so rows from before these fields existed read back as `None`, |
| 248 | // which is exactly a fresh account that never filled one in. The avatar is | 220 | // which is exactly a fresh account that never filled one in. The avatar is |
| 249 | // a blob on disk (`FILES_PATH`) like every other upload; only its name, | 221 | // a blob on disk (`FILES_PATH`) like every other upload; only its name, |
| 250 | // type and size live on the row. | 222 | // type and size live on the row. |
| 251 | - display_name: Option<DisplayName>, | 223 | + pub(crate) display_name: Option<DisplayName>, |
| 252 | - bio: Option<Bio>, | 224 | + pub(crate) bio: Option<Bio>, |
| 253 | - avatar_file: Option<String>, | 225 | + pub(crate) avatar_file: Option<String>, |
| 254 | - avatar_content_type: Option<FileContentType>, | 226 | + pub(crate) avatar_content_type: Option<FileContentType>, |
| 255 | - avatar_size: Option<i64>, | 227 | + pub(crate) avatar_size: Option<i64>, |
| 256 | } | 228 | } |
| 257 | 229 | ||
| 258 | impl User { | 230 | impl User { |
| @@ -354,1003 +326,11 @@ impl User { | |||
| 354 | self.avatar_size | 326 | self.avatar_size |
| 355 | } | 327 | } |
| 356 | 328 | ||
| 357 | - /// Register a new account. New users always start as [`Role::Student`]; | ||
| 358 | - /// elevation is a separate, admin-only action (see [`User::set_role`]). | ||
| 359 | - pub async fn create( | ||
| 360 | - username: Username, | ||
| 361 | - password_hash: PasswordHash, | ||
| 362 | - db: &Database, | ||
| 363 | - ) -> Result<User, AppError> { | ||
| 364 | - Self::create_with_role(username, password_hash, Role::Student, db).await | ||
| 365 | - } | ||
| 366 | - | ||
| 367 | - /// The one row-minting path. `role` is written *with* the row rather than | ||
| 368 | - /// patched on afterwards, which is what makes the admin seed atomic: a | ||
| 369 | - /// create-then-promote pair can be interrupted between its halves (a SIGKILL, | ||
| 370 | - /// or a cancelled future), and the row left behind is an ordinary student | ||
| 371 | - /// account that [`User::ensure_admin`] must then refuse to touch — a | ||
| 372 | - /// deployment with no admin and no way for a later boot to repair it. | ||
| 373 | - pub async fn create_with_role( | ||
| 374 | - username: Username, | ||
| 375 | - password_hash: PasswordHash, | ||
| 376 | - role: Role, | ||
| 377 | - db: &Database, | ||
| 378 | - ) -> Result<User, AppError> { | ||
| 379 | - if Self::find_by_username(username.as_str(), db) | ||
| 380 | - .await? | ||
| 381 | - .is_some() | ||
| 382 | - { | ||
| 383 | - return Err(AppError::Conflict("username already taken")); | ||
| 384 | - } | ||
| 385 | - let user = User { | ||
| 386 | - id: UserId::generate(), | ||
| 387 | - username, | ||
| 388 | - password_hash, | ||
| 389 | - role, | ||
| 390 | - name: None, | ||
| 391 | - surname: None, | ||
| 392 | - email: None, | ||
| 393 | - phone: None, | ||
| 394 | - birth_date: None, | ||
| 395 | - theme: None, | ||
| 396 | - language: None, | ||
| 397 | - palette_color: None, | ||
| 398 | - display_name: None, | ||
| 399 | - bio: None, | ||
| 400 | - avatar_file: None, | ||
| 401 | - avatar_content_type: None, | ||
| 402 | - avatar_size: None, | ||
| 403 | - }; | ||
| 404 | - let created: Result<Option<User>, surrealdb::Error> = | ||
| 405 | - db.create(user.id.record()).content(user.clone()).await; | ||
| 406 | - match created { | ||
| 407 | - Ok(Some(created)) => Ok(created), | ||
| 408 | - Ok(None) => Err(AppError::Internal("failed to create user".into())), | ||
| 409 | - // The availability pre-check above is not atomic with the insert: | ||
| 410 | - // two concurrent registrations can both pass it, and the loser then | ||
| 411 | - // trips the unique username index. That loss is the same condition | ||
| 412 | - // as the sequential duplicate, so report the same 409 — not a 500. | ||
| 413 | - Err(err) => { | ||
| 414 | - if Self::find_by_username(user.username.as_str(), db) | ||
| 415 | - .await? | ||
| 416 | - .is_some() | ||
| 417 | - { | ||
| 418 | - Err(AppError::Conflict("username already taken")) | ||
| 419 | - } else { | ||
| 420 | - Err(err.into()) | ||
| 421 | - } | ||
| 422 | - } | ||
| 423 | - } | ||
| 424 | - } | ||
| 425 | - | ||
| 426 | - /// Idempotent startup seed: guarantee an admin account with this username. | ||
| 427 | - /// Missing → created directly with [`Role::Admin`]. Already an admin → | ||
| 428 | - /// nothing to do (the stored password stays whatever it is — the seed never | ||
| 429 | - /// rewrites credentials). Taken by a non-admin → refuse to touch it and log | ||
| 430 | - /// a warning: silently promoting an account someone else registered would | ||
| 431 | - /// be a privilege escalation, so that conflict is resolved out-of-band. | ||
| 432 | - pub async fn ensure_admin( | ||
| 433 | - username: Username, | ||
| 434 | - password: Password, | ||
| 435 | - db: &Database, | ||
| 436 | - ) -> Result<(), AppError> { | ||
| 437 | - match Self::find_by_username(username.as_str(), db).await? { | ||
| 438 | - Some(user) if user.role == Role::Admin => Ok(()), | ||
| 439 | - Some(_) => { | ||
| 440 | - tracing::warn!( | ||
| 441 | - "ADMIN_USERNAME names an existing non-admin account; refusing to promote it. \ | ||
| 442 | - Grant the role through an existing admin or the manual SurrealQL path." | ||
| 443 | - ); | ||
| 444 | - Ok(()) | ||
| 445 | - } | ||
| 446 | - None => { | ||
| 447 | - // One statement, admin from birth. Never create-then-promote: | ||
| 448 | - // an interruption between those two writes leaves a student row | ||
| 449 | - // holding ADMIN_USERNAME, which the `Some(_)` arm above then | ||
| 450 | - // refuses to promote — forever, on every subsequent boot. There | ||
| 451 | - // is no marker that could tell such a row apart from a stranger | ||
| 452 | - // who registered the name first, so the hole cannot be healed | ||
| 453 | - // later; it has to be impossible to open. | ||
| 454 | - Self::create_with_role(username, password.hash_async().await?, Role::Admin, db) | ||
| 455 | - .await?; | ||
| 456 | - // No `username` field: with OTLP on every event is exported as a | ||
| 457 | - // log record, so an account name here leaves the process. | ||
| 458 | - tracing::info!("seeded the admin account named by ADMIN_USERNAME"); | ||
| 459 | - Ok(()) | ||
| 460 | - } | ||
| 461 | - } | ||
| 462 | - } | ||
| 463 | - | ||
| 464 | - pub async fn read(id: &UserId, db: &Database) -> Result<Option<User>, AppError> { | ||
| 465 | - Ok(db.select(id.record()).await?) | ||
| 466 | - } | ||
| 467 | - | ||
| 468 | - pub async fn list_all( | ||
| 469 | - limit: Option<i64>, | ||
| 470 | - offset: i64, | ||
| 471 | - db: &Database, | ||
| 472 | - ) -> Result<(Vec<User>, i64), AppError> { | ||
| 473 | - PagedList::new("user", "ORDER BY id DESC") | ||
| 474 | - .run(limit, offset, db) | ||
| 475 | - .await | ||
| 476 | - } | ||
| 477 | - | ||
| 478 | - /// Fetch the users behind `ids` in one query. Ids with no row are simply | ||
| 479 | - /// absent from the result — the caller decides how to degrade. | ||
| 480 | - pub async fn list_by_ids(ids: &[UserId], db: &Database) -> Result<Vec<User>, AppError> { | ||
| 481 | - if ids.is_empty() { | ||
| 482 | - return Ok(Vec::new()); | ||
| 483 | - } | ||
| 484 | - let records: Vec<RecordId> = ids.iter().map(UserId::record).collect(); | ||
| 485 | - let mut result = db | ||
| 486 | - .query("SELECT * FROM user WHERE id IN $ids") | ||
| 487 | - .bind(("ids", records)) | ||
| 488 | - .await? | ||
| 489 | - .check()?; | ||
| 490 | - Ok(result.take::<Vec<User>>(0)?) | ||
| 491 | - } | ||
| 492 | - | ||
| 493 | - /// Every user holding exactly `role` — e.g. the roster of a role-targeted | ||
| 494 | - /// event. Exact match, not `at_least`: "all teachers" means teachers, not | ||
| 495 | - /// managers and admins too. | ||
| 496 | - pub async fn list_by_role(role: Role, db: &Database) -> Result<Vec<User>, AppError> { | ||
| 497 | - let mut result = db | ||
| 498 | - .query("SELECT * FROM user WHERE role = $role ORDER BY id DESC") | ||
| 499 | - .bind(("role", role)) | ||
| 500 | - .await? | ||
| 501 | - .check()?; | ||
| 502 | - Ok(result.take::<Vec<User>>(0)?) | ||
| 503 | - } | ||
| 504 | - | ||
| 505 | - /// Would lowering `target` out of `admin` leave the school with none? Both | ||
| 506 | - /// halves are asked of the **live** rows in one round trip: is that row an | ||
| 507 | - /// admin right now, and does any other admin exist. It asks for one id per | ||
| 508 | - /// half rather than a `count()` — a count over an indexed field compared | ||
| 509 | - /// against a plan-time value answers `{count: N}` on the real server, and | ||
| 510 | - /// neither half needs a number. | ||
| 511 | - async fn would_orphan_admins(target: &UserId, db: &Database) -> Result<bool, AppError> { | ||
| 512 | - let mut result = db | ||
| 513 | - .query( | ||
| 514 | - "SELECT VALUE id FROM user WHERE id = $usr AND role = $role;\n\ | ||
| 515 | - SELECT VALUE id FROM user WHERE role = $role AND id != $usr LIMIT 1", | ||
| 516 | - ) | ||
| 517 | - .bind(("role", Role::Admin)) | ||
| 518 | - .bind(("usr", target.record())) | ||
| 519 | - .await? | ||
| 520 | - .check()?; | ||
| 521 | - let is_admin = !result.take::<Vec<RecordId>>(0)?.is_empty(); | ||
| 522 | - let others = !result.take::<Vec<RecordId>>(1)?.is_empty(); | ||
| 523 | - Ok(is_admin && !others) | ||
| 524 | - } | ||
| 525 | - | ||
| 526 | - /// Case- and diacritic-insensitive fragment search over username, name, | ||
| 527 | - /// and surname. Needle and columns both go through | ||
| 528 | - /// [`crate::domain::text_fold`], so `ilker` finds `İLKER` and back — | ||
| 529 | - /// backs the user pickers. `role` narrows to one role (e.g. only students | ||
| 530 | - /// for an enroll picker); `None` searches everyone. `allowed_roles` | ||
| 531 | - /// narrows the *visible* set (the roles a non-staff caller may message — | ||
| 532 | - /// see [`Role::messageable_roles`]); it is part of the query, not a | ||
| 533 | - /// post-filter, so `total` counts only what the caller may see. A blank | ||
| 534 | - /// `query` | ||
| 535 | - /// matches everyone, so blank + `role` is a role-scoped listing. Returns | ||
| 536 | - /// every match, ordered by username; the HTTP layer pages the result like | ||
| 537 | - /// any other list (no built-in cap — an over-broad fragment is windowed | ||
| 538 | - /// by `?limit`). | ||
| 539 | - pub async fn search( | ||
| 540 | - query: &str, | ||
| 541 | - role: Option<Role>, | ||
| 542 | - allowed_roles: Option<&[Role]>, | ||
| 543 | - limit: Option<i64>, | ||
| 544 | - offset: i64, | ||
| 545 | - db: &Database, | ||
| 546 | - ) -> Result<(Vec<User>, i64), AppError> { | ||
| 547 | - let needle = search_fold(query.trim()); | ||
| 548 | - let text_clause = format!( | ||
| 549 | - "({} CONTAINS $q OR {} CONTAINS $q OR {} CONTAINS $q)", | ||
| 550 | - search_fold_sql("username"), | ||
| 551 | - search_fold_sql("name ?? ''"), | ||
| 552 | - search_fold_sql("surname ?? ''"), | ||
| 553 | - ); | ||
| 554 | - let mut clauses = Vec::new(); | ||
| 555 | - if !needle.is_empty() { | ||
| 556 | - clauses.push(text_clause.as_str()); | ||
| 557 | - } | ||
| 558 | - if role.is_some() { | ||
| 559 | - clauses.push("role = $role"); | ||
| 560 | - } | ||
| 561 | - if allowed_roles.is_some() { | ||
| 562 | - clauses.push("role IN $allowed"); | ||
| 563 | - } | ||
| 564 | - let where_clause = if clauses.is_empty() { | ||
| 565 | - "true".to_string() | ||
| 566 | - } else { | ||
| 567 | - clauses.join(" AND ") | ||
| 568 | - }; | ||
| 569 | - let mut list = PagedList::new(format!("user WHERE {where_clause}"), "ORDER BY username") | ||
| 570 | - .bind("q", needle); | ||
| 571 | - if let Some(role) = role { | ||
| 572 | - list = list.bind("role", role); | ||
| 573 | - } | ||
| 574 | - if let Some(allowed) = allowed_roles { | ||
| 575 | - list = list.bind("allowed", allowed.to_vec()); | ||
| 576 | - } | ||
| 577 | - list.run(limit, offset, db).await | ||
| 578 | - } | ||
| 579 | - | ||
| 580 | - /// Overwrite this user's role **and** shed every grant the new role may not | ||
| 581 | - /// hold, in one transaction. The caller is responsible for authorizing it. | ||
| 582 | - /// | ||
| 583 | - /// Refuses (`Conflict`) to lower the school's last admin, however the | ||
| 584 | - /// request is spelled and however many demotions are in flight at once — | ||
| 585 | - /// see [`ADMIN_FLOOR_LOCK`] for why that guard cannot live in the | ||
| 586 | - /// transaction below. | ||
| 587 | - /// | ||
| 588 | - /// Writes *only* the `role` field of the user row (never the whole row): | ||
| 589 | - /// the row mixes admin-owned (role) and self-service (profile, preferences) | ||
| 590 | - /// fields, and each writer starts from a snapshot read at request start. A | ||
| 591 | - /// whole-row write would carry the snapshot's copy of the *other* group back | ||
| 592 | - /// over a concurrent edit — an in-flight profile save silently reverting an | ||
| 593 | - /// admin's demotion, or this write erasing a profile edit that raced it. | ||
| 594 | - /// [`User::set_profile`] and [`User::set_preferences`] are scoped for the | ||
| 595 | - /// same reason. | ||
| 596 | - /// | ||
| 597 | - /// One transaction and not eight statements, which is what this used to be: | ||
| 598 | - /// a sweep that errored answered 500 with the role already lowered and some | ||
| 599 | - /// of the old grants still standing — exactly the state the sweeps exist to | ||
| 600 | - /// prevent, and a crash between them left it with nobody to answer to. | ||
| 601 | - /// Nothing here is a security hole either way (every gate re-reads the live | ||
| 602 | - /// role, `web::mod`), but the residue pollutes rosters, counts and signup | ||
| 603 | - /// lists, and one of those, the event seat, nothing could ever free again. | ||
| 604 | - /// | ||
| 605 | - /// What is swept, and why the conditions differ: | ||
| 606 | - /// | ||
| 607 | - /// * **Non-student** sheds class memberships, *every* enrollment row | ||
| 608 | - /// (hand-placed ones included — only students enroll, and a kept row | ||
| 609 | - /// would grant nothing and count a seat) and the parent links observing | ||
| 610 | - /// them. Memberships and enrollments were already one transaction and | ||
| 611 | - /// still are: released apart, an enrollment row could be left tagged with | ||
| 612 | - /// a class whose counters had been given back, so the class passed its | ||
| 613 | - /// zero-zero delete guard and no sweep could ever reach the row again. | ||
| 614 | - /// * **Parent** additionally frees event seats, comes off every whiteboard | ||
| 615 | - /// roster and has the boards they *created* closed — permanently | ||
| 616 | - /// read-only, rows kept, because a room whose creator is demoted is | ||
| 617 | - /// commandable by nobody at all (see the statement's own note). The seat | ||
| 618 | - /// is the one thing on a signup list nothing | ||
| 619 | - /// else could remove: staff free their own by hand (`unregister` allows | ||
| 620 | - /// the self case) but a parent can reach no such door, so a promotion | ||
| 621 | - /// strands nothing and only this demotion does. A list that has already | ||
| 622 | - /// **frozen** ([`REGISTRATION_FROZEN_GUARD`]) is left exactly as it | ||
| 623 | - /// stands — past the freeze it is historical record, re-registering | ||
| 624 | - /// answers 409, and rewriting it here would be irrecoverable. A signup | ||
| 625 | - /// whose event record is *gone* has no seat to hand back and no list that | ||
| 626 | - /// can freeze, so it is deleted rather than skipped: skipped, it is | ||
| 627 | - /// stranded forever (`unregister` 404s on the missing event). | ||
| 628 | - /// * **Below teacher** gives up course staffing and homeroom-teacher | ||
| 629 | - /// columns — only teacher+ may hold either — and the published | ||
| 630 | - /// appointment calendar, whose live bookings are cancelled in the same | ||
| 631 | - /// breath. Nothing else could ever reach those: a slot is listed only on | ||
| 632 | - /// its own teacher's calendar and deleted only by a teacher+, so after the | ||
| 633 | - /// demotion neither its owner nor a manager has a route that yields its | ||
| 634 | - /// id, and a booking on it can be neither decided (teacher+ only) nor | ||
| 635 | - /// cancelled once its window opens — leaving the slot's `occupied` seat | ||
| 636 | - /// pinned at one and the slot itself undeletable forever. The requester | ||
| 637 | - /// keeps the row, `cancelled`, with the teacher on `cancelled_by` and the | ||
| 638 | - /// reason on `cancel_reason`; the slot it pointed at is gone, so the | ||
| 639 | - /// booking renders without a window | ||
| 640 | - /// ([`crate::domain::appointment::Appointment`]'s reader already treats a | ||
| 641 | - /// vanished slot that way). There is no notification anywhere in | ||
| 642 | - /// this crate, so a settled row the person can read is the strongest | ||
| 643 | - /// defined end available — and the alternative, deleting it, would make a | ||
| 644 | - /// confirmed meeting vanish with no trace at all. | ||
| 645 | - /// | ||
| 646 | - /// The returned boards are the rooms whose roster this changed, plus those | ||
| 647 | - /// the user created — whose roster is untouched but which are now closed, | ||
| 648 | - /// and they carry that stamp because the close is written first. Publishing | ||
| 649 | - /// to them is the caller's job: an in-process | ||
| 650 | - /// fan-out cannot sit inside a database transaction, and a room told before | ||
| 651 | - /// the commit would re-read the pre-commit state. | ||
| 652 | - /// | ||
| 653 | - /// Admissible for [`transaction_with_retry`] by construction: `SELECT`, | ||
| 654 | - /// `UPDATE` and `DELETE` only, so no statement can answer "already exists" | ||
| 655 | - /// and every lost round is a plain re-send. | ||
| 656 | - pub async fn set_role(self, role: Role, db: &Database) -> Result<(User, Vec<Board>), AppError> { | ||
| 657 | - // The admin floor, held from the count to the commit ([`ADMIN_FLOOR_LOCK`] | ||
| 658 | - // for why a transaction cannot do this). Asked on the *live* rows rather | ||
| 659 | - // than `self.role`, so a snapshot that predates a promotion cannot skip | ||
| 660 | - // the check, and cheap enough to ask on every demotion: one round trip | ||
| 661 | - // on an admin-only route. | ||
| 662 | - let _floor = if role == Role::Admin { | ||
| 663 | - None | ||
| 664 | - } else { | ||
| 665 | - let guard = ADMIN_FLOOR_LOCK.lock().await; | ||
| 666 | - if Self::would_orphan_admins(&self.id, db).await? { | ||
| 667 | - return Err(AppError::Conflict( | ||
| 668 | - "the school must keep at least one admin — promote another account first", | ||
| 669 | - )); | ||
| 670 | - } | ||
| 671 | - Some(guard) | ||
| 672 | - }; | ||
| 673 | - // Built as a statement list rather than one string so the result slot | ||
| 674 | - // of the board write is *counted*, not hand-tallied against arms that | ||
| 675 | - // may or may not be in the batch. Slot 0 is `BEGIN`, as everywhere. | ||
| 676 | - let mut batch = vec![ | ||
| 677 | - "BEGIN TRANSACTION".to_string(), | ||
| 678 | - "UPDATE $usr SET role = $role RETURN AFTER".to_string(), | ||
| 679 | - ]; | ||
| 680 | - if role != Role::Student { | ||
| 681 | - batch.push(format!( | ||
| 682 | - "LET $links = (DELETE {CLASS_MEMBER_TABLE} WHERE user = $usr RETURN BEFORE)" | ||
| 683 | - )); | ||
| 684 | - batch.push(format!( | ||
| 685 | - "FOR $link IN ($links ?? []) {{ UPDATE $link.class SET \ | ||
| 686 | - {CLASS_MEMBER_COUNT_FIELD} = \ | ||
| 687 | - math::max([({CLASS_MEMBER_COUNT_FIELD} ?? 0) - 1, 0]); }}" | ||
| 688 | - )); | ||
| 689 | - batch.push(format!( | ||
| 690 | - "LET $rows = (DELETE {ENROLLMENT_TABLE} WHERE user = $usr RETURN BEFORE)" | ||
| 691 | - )); | ||
| 692 | - batch.push(format!( | ||
| 693 | - "FOR $row IN ($rows ?? []) {{ UPDATE $row.course SET \ | ||
| 694 | - {ENROLLMENT_COUNT_FIELD} = \ | ||
| 695 | - math::max([({ENROLLMENT_COUNT_FIELD} ?? 0) - 1, 0]); }}" | ||
| 696 | - )); | ||
| 697 | - batch.push(format!("DELETE {PARENT_LINK_TABLE} WHERE student = $usr")); | ||
| 698 | - } | ||
| 699 | - let mut board_slot = None; | ||
| 700 | - if role == Role::Parent { | ||
| 701 | - batch.push(format!( | ||
| 702 | - "LET $signups = (SELECT * FROM {REGISTRATION_TABLE} WHERE user = $usr)" | ||
| 703 | - )); | ||
| 704 | - // Row and seat move together per signup, the way `unregister` does: | ||
| 705 | - // the seats are independent facts on unrelated events. A missing | ||
| 706 | - // event matches nothing in the guard *and* nothing in the counter | ||
| 707 | - // write, which is precisely the orphan rule. | ||
| 708 | - batch.push(format!( | ||
| 709 | - "FOR $signup IN ($signups ?? []) {{ \ | ||
| 710 | - IF array::len((SELECT VALUE id FROM $signup.event \ | ||
| 711 | - WHERE {REGISTRATION_FROZEN_GUARD})) = 0 {{ \ | ||
| 712 | - LET $freed = (DELETE $signup.id RETURN BEFORE); \ | ||
| 713 | - UPDATE $signup.event SET {REGISTRATION_COUNT_FIELD} = \ | ||
| 714 | - math::max([({REGISTRATION_COUNT_FIELD} ?? 0) - array::len($freed), 0]); \ | ||
| 715 | - }}; }}" | ||
| 716 | - )); | ||
| 717 | - // A room whose *creator* is demoted can never be ended by anyone: | ||
| 718 | - // the whiteboard is closed to parents outright, so the creator is | ||
| 719 | - // 404'd off their own board, `clear`/`lock`/`close`/`delete` are | ||
| 720 | - // creator-only for everyone else, and `Board::list_for_user` is the | ||
| 721 | - // crate's only enumeration — no manager or admin can so much as find | ||
| 722 | - // the id. Its participants meanwhile keep drawing (the room re-derives | ||
| 723 | - // membership per frame and they still pass), into a board only the | ||
| 724 | - // 50 000-stroke lifetime cap could ever retire. So the demotion | ||
| 725 | - // retires it, with the same compare-and-set [`Board::close`] uses: an | ||
| 726 | - // already-closed board keeps its first stamp. Closed and not deleted | ||
| 727 | - // because the marks are the participants' work too — they keep reading | ||
| 728 | - // the board and its whole history, and the creator's `board_count` | ||
| 729 | - // seat stays taken, which is correct while the row it counts exists. | ||
| 730 | - // Stamped *before* the roster strip so the strip's `RETURN AFTER` | ||
| 731 | - // carries the closed row the caller fans out. | ||
| 732 | - batch.push(format!( | ||
| 733 | - "UPDATE {BOARD_TABLE} SET closed_at = $now WHERE creator = $usr AND closed_at = NONE" | ||
| 734 | - )); | ||
| 735 | - board_slot = Some(batch.len()); | ||
| 736 | - batch.push(format!( | ||
| 737 | - "UPDATE {BOARD_TABLE} SET participants -= $usr \ | ||
| 738 | - WHERE $usr IN participants OR creator = $usr RETURN AFTER" | ||
| 739 | - )); | ||
| 740 | - } | ||
| 741 | - if role != Role::Parent { | ||
| 742 | - batch.push(format!("DELETE {PARENT_LINK_TABLE} WHERE parent = $usr")); | ||
| 743 | - } | ||
| 744 | - if !role.at_least(Role::Teacher) { | ||
| 745 | - batch.push(format!( | ||
| 746 | - "UPDATE {COURSE_TABLE} SET teachers -= $usr WHERE $usr IN teachers" | ||
| 747 | - )); | ||
| 748 | - batch.push(format!( | ||
| 749 | - "UPDATE {CLASS_GROUP_TABLE} SET teacher = NONE WHERE teacher = $usr" | ||
| 750 | - )); | ||
| 751 | - // The published calendar goes too, and the bookings on it are | ||
| 752 | - // settled first: a slot only its own teacher can list and only a | ||
| 753 | - // teacher+ can delete is reachable by nobody once that teacher is | ||
| 754 | - // demoted, and a live booking on one is worse — nobody can approve, | ||
| 755 | - // reject or (past its start) cancel it, so it pins the slot's | ||
| 756 | - // `occupied` seat forever. Cancelled rather than deleted so the | ||
| 757 | - // person who asked is left with a settled booking they can still | ||
| 758 | - // read, carrying who dropped it and why; the slot row (and with it | ||
| 759 | - // the seat) goes, which is what makes this convergent. | ||
| 760 | - batch.push(format!( | ||
| 761 | - "LET $slots = (SELECT VALUE id FROM {APPOINTMENT_SLOT_TABLE} WHERE teacher = $usr)" | ||
| 762 | - )); | ||
| 763 | - batch.push(format!( | ||
| 764 | - "UPDATE {APPOINTMENT_TABLE} SET status = '{cancelled}', cancelled_by = $usr, \ | ||
| 765 | - cancel_reason = 'the teacher no longer holds a teaching role' \ | ||
| 766 | - WHERE slot IN $slots AND status IN ['{pending}', '{approved}']", | ||
| 767 | - cancelled = AppointmentStatus::Cancelled.as_str(), | ||
| 768 | - pending = AppointmentStatus::Pending.as_str(), | ||
| 769 | - approved = AppointmentStatus::Approved.as_str(), | ||
| 770 | - )); | ||
| 771 | - // Deleting the slots is also what makes a *concurrent* booking safe: | ||
| 772 | - // `Appointment::book` claims the slot row this deletes, so the two | ||
| 773 | - // collide in the store and the loser re-sends. A slot *published* | ||
| 774 | - // concurrently shares no key with any of this, which is why | ||
| 775 | - // `crate::db::appointment_slot::insert_claimed` claims the user row instead. | ||
| 776 | - batch.push(format!( | ||
| 777 | - "DELETE {APPOINTMENT_SLOT_TABLE} WHERE id IN $slots" | ||
| 778 | - )); | ||
| 779 | - } | ||
| 780 | - let sql = format!("{};\nCOMMIT TRANSACTION;", batch.join(";\n")); | ||
| 781 | - let (mut result, mut errors) = transaction_with_retry( | ||
| 782 | - db, | ||
| 783 | - &sql, | ||
| 784 | - &[ | ||
| 785 | - ("usr".into(), self.id.record().into_value()), | ||
| 786 | - ("role".into(), role.into_value()), | ||
| 787 | - ("now".into(), Timestamp::now().as_millis().into_value()), | ||
| 788 | - ], | ||
| 789 | - &[], | ||
| 790 | - ) | ||
| 791 | - .await?; | ||
| 792 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 793 | - return Err(error.into()); | ||
| 794 | - } | ||
| 795 | - let updated = result | ||
| 796 | - .take::<Vec<User>>(1)? | ||
| 797 | - .into_iter() | ||
| 798 | - .next() | ||
| 799 | - .ok_or(AppError::NotFound)?; | ||
| 800 | - let boards = match board_slot { | ||
| 801 | - Some(slot) => result.take::<Vec<Board>>(slot)?, | ||
| 802 | - None => Vec::new(), | ||
| 803 | - }; | ||
| 804 | - Ok((updated, boards)) | ||
| 805 | - } | ||
| 806 | - | ||
| 807 | - /// Write the personal-info and public-profile fields the request actually | ||
| 808 | - /// carried — everything a person edits about themselves except the avatar | ||
| 809 | - /// blob, which needs its own writer ([`User::set_avatar`]). Every | ||
| 810 | - /// column is nullable, so each argument is an outer/inner `Option`: `None` | ||
| 811 | - /// = omitted (not written at all), `Some(None)` = cleared, `Some(Some(v))` | ||
| 812 | - /// = set. Merging the request against the current row is the HTTP layer's | ||
| 813 | - /// job; the caller authorizes. | ||
| 814 | - /// | ||
| 815 | - /// Request-scoped, not merely field-scoped: nothing guards the row across | ||
| 816 | - /// the handler's read and this write, so re-sending the snapshot's value | ||
| 817 | - /// for an omitted field would revert a concurrent PATCH of that field — | ||
| 818 | - /// two profile edits (a name and a phone) used to lose each other. See | ||
| 819 | - /// [`User::set_role`] for why no writer here touches the whole row. | ||
| 820 | - // One argument per nullable column is the point: folding them into a struct | ||
| 821 | - // would just re-spell the HTTP DTO here and cost the compiler's check that | ||
| 822 | - // every column was considered at the call site. | ||
| 823 | - #[allow(clippy::too_many_arguments)] | ||
| 824 | - pub async fn set_profile( | ||
| 825 | - self, | ||
| 826 | - name: Option<Option<PersonName>>, | ||
| 827 | - surname: Option<Option<PersonName>>, | ||
| 828 | - email: Option<Option<Email>>, | ||
| 829 | - phone: Option<Option<Phone>>, | ||
| 830 | - birth_date: Option<Option<BirthDate>>, | ||
| 831 | - display_name: Option<Option<DisplayName>>, | ||
| 832 | - bio: Option<Option<Bio>>, | ||
| 833 | - db: &Database, | ||
| 834 | - ) -> Result<User, AppError> { | ||
| 835 | - FieldUpdate::new(self.id.record()) | ||
| 836 | - .set("name", name) | ||
| 837 | - .set("surname", surname) | ||
| 838 | - .set("email", email) | ||
| 839 | - .set("phone", phone) | ||
| 840 | - .set("birth_date", birth_date) | ||
| 841 | - .set("display_name", display_name) | ||
| 842 | - .set("bio", bio) | ||
| 843 | - .run::<User>(db) | ||
| 844 | - .await | ||
| 845 | - } | ||
| 846 | - | ||
| 847 | - /// Point the row at a freshly uploaded avatar blob, returning the row *as | ||
| 848 | - /// it was* — the caller deletes `before.get_avatar_file()` off disk. Losing | ||
| 849 | - /// `RETURN BEFORE` here strands the replaced blob forever: no route ever | ||
| 850 | - /// deletes a user, so nothing else would collect it. | ||
| 851 | - /// | ||
| 852 | - /// Field-scoped for the same reason as [`User::set_profile`]: an avatar | ||
| 853 | - /// upload must not carry a stale snapshot's role back over an admin's | ||
| 854 | - /// change. `None` means the row is gone. | ||
| 855 | - /// | ||
| 856 | - /// Sent through [`write_with_retry`] like every other single-statement row | ||
| 857 | - /// write here, unguarded or not: the user row is contended (preferences, | ||
| 858 | - /// profile, role all write it), and a lost round wrote nothing, so | ||
| 859 | - /// re-sending it is the recovery rather than a 500 in the caller's face. | ||
| 860 | - pub async fn set_avatar( | ||
| 861 | - id: &UserId, | ||
| 862 | - file: &str, | ||
| 863 | - content_type: &FileContentType, | ||
| 864 | - size: i64, | ||
| 865 | - db: &Database, | ||
| 866 | - ) -> Result<Option<User>, AppError> { | ||
| 867 | - let rows: Vec<User> = write_with_retry( | ||
| 868 | - db, | ||
| 869 | - "UPDATE $u SET avatar_file = $file, avatar_content_type = $ct, avatar_size = $size \ | ||
| 870 | - RETURN BEFORE", | ||
| 871 | - &[ | ||
| 872 | - ("u".into(), id.record().into_value()), | ||
| 873 | - ("file".into(), file.to_string().into_value()), | ||
| 874 | - ("ct".into(), content_type.clone().into_value()), | ||
| 875 | - ("size".into(), size.into_value()), | ||
| 876 | - ], | ||
| 877 | - ) | ||
| 878 | - .await?; | ||
| 879 | - Ok(rows.into_iter().next()) | ||
| 880 | - } | ||
| 881 | - | ||
| 882 | - /// Drop the avatar, returning the row as it was so the caller can delete | ||
| 883 | - /// the blob. Same `RETURN BEFORE` contract as [`User::set_avatar`]. | ||
| 884 | - pub async fn clear_avatar(id: &UserId, db: &Database) -> Result<Option<User>, AppError> { | ||
| 885 | - let rows: Vec<User> = write_with_retry( | ||
| 886 | - db, | ||
| 887 | - "UPDATE $u SET avatar_file = NONE, avatar_content_type = NONE, \ | ||
| 888 | - avatar_size = NONE RETURN BEFORE", | ||
| 889 | - &[("u".into(), id.record().into_value())], | ||
| 890 | - ) | ||
| 891 | - .await?; | ||
| 892 | - Ok(rows.into_iter().next()) | ||
| 893 | - } | ||
| 894 | - | ||
| 895 | - /// Replace a user's password hash — the builder's admin-password reset | ||
| 896 | - /// (`POST /schools/{slug}/admin-password`). Only the credential is | ||
| 897 | - /// rewritten; revoking the sessions minted under the old one is the | ||
| 898 | - /// caller's second half | ||
| 899 | - /// ([`crate::db::session::delete_by_user`]), because a reset | ||
| 900 | - /// that leaves a stolen cookie working resets nothing. | ||
| 901 | - pub async fn set_password_hash( | ||
| 902 | - id: &UserId, | ||
| 903 | - password_hash: PasswordHash, | ||
| 904 | - db: &Database, | ||
| 905 | - ) -> Result<Option<User>, AppError> { | ||
| 906 | - let rows: Vec<User> = write_with_retry( | ||
| 907 | - db, | ||
| 908 | - "UPDATE $u SET password_hash = $hash RETURN AFTER", | ||
| 909 | - &[ | ||
| 910 | - ("u".into(), id.record().into_value()), | ||
| 911 | - ("hash".into(), password_hash.into_value()), | ||
| 912 | - ], | ||
| 913 | - ) | ||
| 914 | - .await?; | ||
| 915 | - Ok(rows.into_iter().next()) | ||
| 916 | - } | ||
| 917 | - | ||
| 918 | - /// Write the UI-preference fields the request actually carried. Same | ||
| 919 | - /// contract as [`User::set_profile`]: `None` = omitted (not written), | ||
| 920 | - /// `Some(None)` = cleared back to "never chose", `Some(Some(v))` = set. | ||
| 921 | - pub async fn set_preferences( | ||
| 922 | - self, | ||
| 923 | - theme: Option<Option<Theme>>, | ||
| 924 | - language: Option<Option<Language>>, | ||
| 925 | - palette_color: Option<Option<PaletteColor>>, | ||
| 926 | - db: &Database, | ||
| 927 | - ) -> Result<User, AppError> { | ||
| 928 | - FieldUpdate::new(self.id.record()) | ||
| 929 | - .set("theme", theme) | ||
| 930 | - .set("language", language) | ||
| 931 | - .set("palette_color", palette_color) | ||
| 932 | - .run::<User>(db) | ||
| 933 | - .await | ||
| 934 | - } | ||
| 935 | - | ||
| 936 | - pub async fn find_by_username(username: &str, db: &Database) -> Result<Option<User>, AppError> { | ||
| 937 | - let mut result = db | ||
| 938 | - .query("SELECT * FROM user WHERE username = $username LIMIT 1") | ||
| 939 | - .bind(("username", username.to_string())) | ||
| 940 | - .await? | ||
| 941 | - .check()?; | ||
| 942 | - Ok(result.take::<Vec<User>>(0)?.into_iter().next()) | ||
| 943 | - } | ||
| 944 | } | 329 | } |
| 945 | 330 | ||
| 946 | #[cfg(test)] | 331 | #[cfg(test)] |
| 947 | mod tests { | 332 | mod tests { |
| 948 | use super::*; | 333 | use super::*; |
| 949 | - use crate::database::init_mem; | ||
| 950 | - | ||
| 951 | - /// The board result slot is an *index* into a batch whose length depends on | ||
| 952 | - /// which arms the role selected, so it is the one number in the cascade a | ||
| 953 | - /// silent mistake would not show up in the store: pointed at the wrong | ||
| 954 | - /// statement it yields an empty list, and every whiteboard room whose roster | ||
| 955 | - /// just changed is simply never told. Assert the rows come back. | ||
| 956 | - #[tokio::test] | ||
| 957 | - async fn the_cascade_returns_the_boards_it_stripped() { | ||
| 958 | - use crate::domain::board::{Board, BoardTitle}; | ||
| 959 | - | ||
| 960 | - let db = init_mem().await.unwrap(); | ||
| 961 | - let creator = User::create( | ||
| 962 | - Username::try_new("ogretmen").unwrap(), | ||
| 963 | - Password::try_new("secret1").unwrap().hash().unwrap(), | ||
| 964 | - &db, | ||
| 965 | - ) | ||
| 966 | - .await | ||
| 967 | - .unwrap(); | ||
| 968 | - let guest = User::create( | ||
| 969 | - Username::try_new("ogrenci").unwrap(), | ||
| 970 | - Password::try_new("secret1").unwrap().hash().unwrap(), | ||
| 971 | - &db, | ||
| 972 | - ) | ||
| 973 | - .await | ||
| 974 | - .unwrap(); | ||
| 975 | - let board = Board::create( | ||
| 976 | - creator.get_id(), | ||
| 977 | - BoardTitle::try_new("Geometri").unwrap(), | ||
| 978 | - vec![guest.get_id().clone()], | ||
| 979 | - &db, | ||
| 980 | - ) | ||
| 981 | - .await | ||
| 982 | - .unwrap(); | ||
| 983 | - | ||
| 984 | - // A promotion touches no roster and must report none. | ||
| 985 | - let (guest, boards) = guest.set_role(Role::Teacher, &db).await.unwrap(); | ||
| 986 | - assert!( | ||
| 987 | - boards.is_empty(), | ||
| 988 | - "only a demotion to parent strips rosters" | ||
| 989 | - ); | ||
| 990 | - | ||
| 991 | - let (_, boards) = guest.set_role(Role::Parent, &db).await.unwrap(); | ||
| 992 | - assert_eq!(boards.len(), 1, "the stripped room must be reported back"); | ||
| 993 | - assert_eq!(boards[0].get_id(), board.get_id()); | ||
| 994 | - assert!( | ||
| 995 | - boards[0].get_participants().is_empty(), | ||
| 996 | - "and carry the roster the room is about to be told about" | ||
| 997 | - ); | ||
| 998 | - } | ||
| 999 | - | ||
| 1000 | - /// The half the roster strip cannot reach: the board's **creator**. Demoted, | ||
| 1001 | - /// they are 404'd off their own room, every command on it is creator-only | ||
| 1002 | - /// for everyone else, and nothing in the crate lists a board a caller is not | ||
| 1003 | - /// on — so the room could be cleared, locked, closed and deleted by nobody | ||
| 1004 | - /// while its participants kept drawing on it. The demotion closes it, and | ||
| 1005 | - /// closing is *all* it does: the roster, the row and every mark stay | ||
| 1006 | - /// readable. | ||
| 1007 | - #[tokio::test] | ||
| 1008 | - async fn a_demoted_creator_s_board_is_closed_and_still_readable() { | ||
| 1009 | - use crate::domain::board::{Board, BoardTitle}; | ||
| 1010 | - use crate::domain::board_stroke::{BOARD_CLOSED, BoardStroke}; | ||
| 1011 | - | ||
| 1012 | - let db = init_mem().await.unwrap(); | ||
| 1013 | - let creator = a_user("ogretmen", &db).await; | ||
| 1014 | - let guest = a_user("ogrenci", &db).await; | ||
| 1015 | - let board = Board::create( | ||
| 1016 | - creator.get_id(), | ||
| 1017 | - BoardTitle::try_new("Geometri").unwrap(), | ||
| 1018 | - vec![guest.get_id().clone()], | ||
| 1019 | - &db, | ||
| 1020 | - ) | ||
| 1021 | - .await | ||
| 1022 | - .unwrap(); | ||
| 1023 | - let mark = |epoch| { | ||
| 1024 | - let (id, author, db) = (board.get_id().clone(), guest.get_id().clone(), db.clone()); | ||
| 1025 | - async move { BoardStroke::append(&id, &author, "{\"p\":[1]}", epoch, &db).await } | ||
| 1026 | - }; | ||
| 1027 | - mark(0).await.unwrap(); | ||
| 1028 | - | ||
| 1029 | - let (creator, boards) = creator.set_role(Role::Parent, &db).await.unwrap(); | ||
| 1030 | - assert_eq!(boards.len(), 1, "the room must be reported back"); | ||
| 1031 | - let stamp = boards[0] | ||
| 1032 | - .get_closed_at() | ||
| 1033 | - .expect("and carry the closing stamp the room is told about"); | ||
| 1034 | - | ||
| 1035 | - // Stored, not merely reported — and nothing else moved. | ||
| 1036 | - let stored = Board::read(board.get_id(), &db).await.unwrap().unwrap(); | ||
| 1037 | - assert_eq!(stored.get_closed_at(), Some(stamp)); | ||
| 1038 | - assert_eq!( | ||
| 1039 | - stored.get_participants(), | ||
| 1040 | - [guest.get_id().clone()], | ||
| 1041 | - "closing must not empty the roster it did not touch" | ||
| 1042 | - ); | ||
| 1043 | - assert_eq!( | ||
| 1044 | - BoardStroke::history(board.get_id(), None, false, None, 0, &db) | ||
| 1045 | - .await | ||
| 1046 | - .unwrap() | ||
| 1047 | - .1, | ||
| 1048 | - 1, | ||
| 1049 | - "the marks the participants drew stay on disk" | ||
| 1050 | - ); | ||
| 1051 | - | ||
| 1052 | - // Read-only for the participants who are still on it. | ||
| 1053 | - assert!( | ||
| 1054 | - matches!(mark(0).await, Err(AppError::Conflict(BOARD_CLOSED))), | ||
| 1055 | - "a closed board must refuse every write with the terminal answer" | ||
| 1056 | - ); | ||
| 1057 | - | ||
| 1058 | - // The stamp is the record: a re-run of the sweep must not move it. | ||
| 1059 | - tokio::time::sleep(std::time::Duration::from_millis(2)).await; | ||
| 1060 | - creator.set_role(Role::Parent, &db).await.unwrap(); | ||
| 1061 | - assert_eq!( | ||
| 1062 | - Board::read(board.get_id(), &db) | ||
| 1063 | - .await | ||
| 1064 | - .unwrap() | ||
| 1065 | - .unwrap() | ||
| 1066 | - .get_closed_at(), | ||
| 1067 | - Some(stamp), | ||
| 1068 | - "the close is a compare-and-set, not a re-stamp" | ||
| 1069 | - ); | ||
| 1070 | - } | ||
| 1071 | - | ||
| 1072 | - /// A demotion below `teacher` must take the published calendar with it and | ||
| 1073 | - /// settle the bookings on it. Nothing else can: a slot is listed only on its | ||
| 1074 | - /// own teacher's calendar (and hidden from every other reader once its owner | ||
| 1075 | - /// is demoted), deleted only by a teacher+, and a booking on one can be | ||
| 1076 | - /// decided only by a teacher+ and cancelled only by its requester — who is | ||
| 1077 | - /// refused the moment the window opens. So a slot left behind here is a row | ||
| 1078 | - /// no route can reach and a seat nothing can ever free. | ||
| 1079 | - #[tokio::test] | ||
| 1080 | - async fn a_demotion_withdraws_the_calendar_and_settles_its_bookings() { | ||
| 1081 | - use crate::domain::appointment::AppointmentReason; | ||
| 1082 | - use crate::service::appointment; | ||
| 1083 | - use crate::service::appointment_slot; | ||
| 1084 | - | ||
| 1085 | - let db = init_mem().await.unwrap(); | ||
| 1086 | - let staff = |name: &'static str, db: Database| async move { | ||
| 1087 | - a_user(name, &db) | ||
| 1088 | - .await | ||
| 1089 | - .set_role(Role::Teacher, &db) | ||
| 1090 | - .await | ||
| 1091 | - .unwrap() | ||
| 1092 | - .0 | ||
| 1093 | - }; | ||
| 1094 | - let teacher = staff("ogretmen", db.clone()).await; | ||
| 1095 | - let other = staff("digerogretmen", db.clone()).await; | ||
| 1096 | - let student = a_user("ogrenci", &db).await; | ||
| 1097 | - let soon = |offset| Timestamp::from_millis(Timestamp::now().as_millis() + offset); | ||
| 1098 | - let reason = || AppointmentReason::try_new("görüşme").unwrap(); | ||
| 1099 | - let slot = |owner: &User, offset: i64, db: Database| { | ||
| 1100 | - let owner = owner.get_id().clone(); | ||
| 1101 | - async move { | ||
| 1102 | - appointment_slot::create(&db, &owner, soon(offset), soon(offset + 60_000), None) | ||
| 1103 | - .await | ||
| 1104 | - .unwrap() | ||
| 1105 | - } | ||
| 1106 | - }; | ||
| 1107 | - | ||
| 1108 | - let free = slot(&teacher, 60_000, db.clone()).await; | ||
| 1109 | - let asked = slot(&teacher, 180_000, db.clone()).await; | ||
| 1110 | - let agreed = slot(&teacher, 300_000, db.clone()).await; | ||
| 1111 | - let kept = slot(&other, 60_000, db.clone()).await; | ||
| 1112 | - | ||
| 1113 | - let pending = appointment::book(&db, asked.get_id(), student.get_id(), reason()) | ||
| 1114 | - .await | ||
| 1115 | - .unwrap(); | ||
| 1116 | - let approved = appointment::book(&db, agreed.get_id(), student.get_id(), reason()) | ||
| 1117 | - .await | ||
| 1118 | - .unwrap(); | ||
| 1119 | - appointment::approve(&db, approved.get_id(), teacher.get_id()) | ||
| 1120 | - .await | ||
| 1121 | - .unwrap(); | ||
| 1122 | - let elsewhere = appointment::book(&db, kept.get_id(), student.get_id(), reason()) | ||
| 1123 | - .await | ||
| 1124 | - .unwrap(); | ||
| 1125 | - | ||
| 1126 | - teacher.clone().set_role(Role::Student, &db).await.unwrap(); | ||
| 1127 | - | ||
| 1128 | - // The calendar is gone, the booked weeks included. | ||
| 1129 | - assert!( | ||
| 1130 | - appointment_slot::list_for_teacher(&db, teacher.get_id()) | ||
| 1131 | - .await | ||
| 1132 | - .unwrap() | ||
| 1133 | - .is_empty() | ||
| 1134 | - ); | ||
| 1135 | - for slot in [&free, &asked, &agreed] { | ||
| 1136 | - assert!( | ||
| 1137 | - appointment_slot::read(&db, slot.get_id()) | ||
| 1138 | - .await | ||
| 1139 | - .unwrap() | ||
| 1140 | - .is_none(), | ||
| 1141 | - "a slot only a teacher+ could reach outlived the role" | ||
| 1142 | - ); | ||
| 1143 | - } | ||
| 1144 | - // Both bookings — the pending request and the confirmed meeting — ended | ||
| 1145 | - // in a state their requester can still read, saying who dropped it. | ||
| 1146 | - for booking in [&pending, &approved] { | ||
| 1147 | - let after = appointment::read(&db, booking.get_id()) | ||
| 1148 | - .await | ||
| 1149 | - .unwrap() | ||
| 1150 | - .expect("the requester keeps the row"); | ||
| 1151 | - assert_eq!(after.get_status(), AppointmentStatus::Cancelled); | ||
| 1152 | - assert_eq!(after.get_cancelled_by(), Some(teacher.get_id())); | ||
| 1153 | - assert!(after.get_cancel_reason().is_some(), "and why"); | ||
| 1154 | - } | ||
| 1155 | - // The seat each held died with its slot row, so nothing is pinned: no | ||
| 1156 | - // live booking is left pointing at a slot that no longer exists. | ||
| 1157 | - let mut result = db | ||
| 1158 | - .query( | ||
| 1159 | - "SELECT VALUE id FROM appointment \ | ||
| 1160 | - WHERE status IN ['pending', 'approved'] AND slot.starts_at = NONE", | ||
| 1161 | - ) | ||
| 1162 | - .await | ||
| 1163 | - .unwrap() | ||
| 1164 | - .check() | ||
| 1165 | - .unwrap(); | ||
| 1166 | - assert!(result.take::<Vec<RecordId>>(0).unwrap().is_empty()); | ||
| 1167 | - | ||
| 1168 | - // Another teacher's calendar is nobody else's business. | ||
| 1169 | - assert_eq!( | ||
| 1170 | - appointment_slot::list_for_teacher(&db, other.get_id()) | ||
| 1171 | - .await | ||
| 1172 | - .unwrap() | ||
| 1173 | - .len(), | ||
| 1174 | - 1 | ||
| 1175 | - ); | ||
| 1176 | - assert_eq!( | ||
| 1177 | - appointment::read(&db, elsewhere.get_id()) | ||
| 1178 | - .await | ||
| 1179 | - .unwrap() | ||
| 1180 | - .unwrap() | ||
| 1181 | - .get_status(), | ||
| 1182 | - AppointmentStatus::Pending | ||
| 1183 | - ); | ||
| 1184 | - } | ||
| 1185 | - | ||
| 1186 | - #[tokio::test] | ||
| 1187 | - async fn a_stale_profile_write_cannot_revert_a_role_change() { | ||
| 1188 | - let db = init_mem().await.unwrap(); | ||
| 1189 | - let user = User::create( | ||
| 1190 | - Username::try_new("aysenur").unwrap(), | ||
| 1191 | - Password::try_new("secret1").unwrap().hash().unwrap(), | ||
| 1192 | - &db, | ||
| 1193 | - ) | ||
| 1194 | - .await | ||
| 1195 | - .unwrap(); | ||
| 1196 | - | ||
| 1197 | - // A PATCH /users/me handler reads its snapshot (role = student)... | ||
| 1198 | - let stale = User::read(user.get_id(), &db).await.unwrap().unwrap(); | ||
| 1199 | - | ||
| 1200 | - // ...then an admin's role change commits before the profile save runs. | ||
| 1201 | - User::read(user.get_id(), &db) | ||
| 1202 | - .await | ||
| 1203 | - .unwrap() | ||
| 1204 | - .unwrap() | ||
| 1205 | - .set_role(Role::Teacher, &db) | ||
| 1206 | - .await | ||
| 1207 | - .unwrap(); | ||
| 1208 | - | ||
| 1209 | - // The in-flight save lands from the stale snapshot. It must write only | ||
| 1210 | - // the profile fields — not carry the snapshot's old role back over the | ||
| 1211 | - // admin's change. | ||
| 1212 | - let name = PersonName::try_new("name", "Ayşenur").unwrap(); | ||
| 1213 | - stale | ||
| 1214 | - .set_profile( | ||
| 1215 | - Some(Some(name.clone())), | ||
| 1216 | - None, | ||
| 1217 | - None, | ||
| 1218 | - None, | ||
| 1219 | - None, | ||
| 1220 | - None, | ||
| 1221 | - None, | ||
| 1222 | - &db, | ||
| 1223 | - ) | ||
| 1224 | - .await | ||
| 1225 | - .unwrap(); | ||
| 1226 | - | ||
| 1227 | - let after = User::read(user.get_id(), &db).await.unwrap().unwrap(); | ||
| 1228 | - assert_eq!( | ||
| 1229 | - after.get_role(), | ||
| 1230 | - Role::Teacher, | ||
| 1231 | - "the role change must survive the racing profile write" | ||
| 1232 | - ); | ||
| 1233 | - assert_eq!( | ||
| 1234 | - after.get_name(), | ||
| 1235 | - Some(&name), | ||
| 1236 | - "the profile edit itself lands" | ||
| 1237 | - ); | ||
| 1238 | - } | ||
| 1239 | - | ||
| 1240 | - fn png() -> FileContentType { | ||
| 1241 | - FileContentType::try_new("image/png").unwrap() | ||
| 1242 | - } | ||
| 1243 | - | ||
| 1244 | - async fn a_user(username: &str, db: &Database) -> User { | ||
| 1245 | - User::create( | ||
| 1246 | - Username::try_new(username).unwrap(), | ||
| 1247 | - Password::try_new("secret1").unwrap().hash().unwrap(), | ||
| 1248 | - db, | ||
| 1249 | - ) | ||
| 1250 | - .await | ||
| 1251 | - .unwrap() | ||
| 1252 | - } | ||
| 1253 | - | ||
| 1254 | - #[tokio::test] | ||
| 1255 | - async fn an_avatar_upload_cannot_revert_a_role_change() { | ||
| 1256 | - let db = init_mem().await.unwrap(); | ||
| 1257 | - let user = a_user("berk", &db).await; | ||
| 1258 | - | ||
| 1259 | - // The upload handler holds its snapshot (role = student)... | ||
| 1260 | - let stale = User::read(user.get_id(), &db).await.unwrap().unwrap(); | ||
| 1261 | - | ||
| 1262 | - // ...an admin promotes and the person edits their bio, both while the | ||
| 1263 | - // blob is still being written... | ||
| 1264 | - User::read(user.get_id(), &db) | ||
| 1265 | - .await | ||
| 1266 | - .unwrap() | ||
| 1267 | - .unwrap() | ||
| 1268 | - .set_role(Role::Teacher, &db) | ||
| 1269 | - .await | ||
| 1270 | - .unwrap(); | ||
| 1271 | - let display_name = DisplayName::try_new("Berk").unwrap(); | ||
| 1272 | - User::read(user.get_id(), &db) | ||
| 1273 | - .await | ||
| 1274 | - .unwrap() | ||
| 1275 | - .unwrap() | ||
| 1276 | - .set_profile( | ||
| 1277 | - None, | ||
| 1278 | - None, | ||
| 1279 | - None, | ||
| 1280 | - None, | ||
| 1281 | - None, | ||
| 1282 | - Some(Some(display_name.clone())), | ||
| 1283 | - None, | ||
| 1284 | - &db, | ||
| 1285 | - ) | ||
| 1286 | - .await | ||
| 1287 | - .unwrap(); | ||
| 1288 | - | ||
| 1289 | - // ...and only then does the avatar land, from the stale row's id. | ||
| 1290 | - User::set_avatar(stale.get_id(), "blob-1", &png(), 42, &db) | ||
| 1291 | - .await | ||
| 1292 | - .unwrap() | ||
| 1293 | - .expect("the row exists"); | ||
| 1294 | - | ||
| 1295 | - let after = User::read(user.get_id(), &db).await.unwrap().unwrap(); | ||
| 1296 | - assert_eq!( | ||
| 1297 | - after.get_role(), | ||
| 1298 | - Role::Teacher, | ||
| 1299 | - "the role change must survive the racing avatar write" | ||
| 1300 | - ); | ||
| 1301 | - assert_eq!( | ||
| 1302 | - after.get_display_name(), | ||
| 1303 | - Some(&display_name), | ||
| 1304 | - "and so must every other column the avatar write never named" | ||
| 1305 | - ); | ||
| 1306 | - assert_eq!(after.get_avatar_file(), Some("blob-1")); | ||
| 1307 | - assert_eq!(after.get_avatar_content_type(), Some(&png())); | ||
| 1308 | - assert_eq!(after.get_avatar_size(), Some(42)); | ||
| 1309 | - } | ||
| 1310 | - | ||
| 1311 | - /// The blob cleanup is built entirely on `RETURN BEFORE`: without the old | ||
| 1312 | - /// `avatar_file` coming back, every replace strands a file on disk that no | ||
| 1313 | - /// route ever collects. | ||
| 1314 | - #[tokio::test] | ||
| 1315 | - async fn the_avatar_writers_return_the_replaced_blob() { | ||
| 1316 | - let db = init_mem().await.unwrap(); | ||
| 1317 | - let user = a_user("ceyda", &db).await; | ||
| 1318 | - | ||
| 1319 | - let before = User::set_avatar(user.get_id(), "blob-1", &png(), 10, &db) | ||
| 1320 | - .await | ||
| 1321 | - .unwrap() | ||
| 1322 | - .expect("the row exists"); | ||
| 1323 | - assert_eq!(before.get_avatar_file(), None, "no blob to collect yet"); | ||
| 1324 | - | ||
| 1325 | - let before = User::set_avatar(user.get_id(), "blob-2", &png(), 20, &db) | ||
| 1326 | - .await | ||
| 1327 | - .unwrap() | ||
| 1328 | - .expect("the row exists"); | ||
| 1329 | - assert_eq!( | ||
| 1330 | - before.get_avatar_file(), | ||
| 1331 | - Some("blob-1"), | ||
| 1332 | - "the replaced blob is what the caller must delete" | ||
| 1333 | - ); | ||
| 1334 | - | ||
| 1335 | - let before = User::clear_avatar(user.get_id(), &db) | ||
| 1336 | - .await | ||
| 1337 | - .unwrap() | ||
| 1338 | - .expect("the row exists"); | ||
| 1339 | - assert_eq!(before.get_avatar_file(), Some("blob-2")); | ||
| 1340 | - | ||
| 1341 | - let after = User::read(user.get_id(), &db).await.unwrap().unwrap(); | ||
| 1342 | - assert_eq!(after.get_avatar_file(), None); | ||
| 1343 | - assert_eq!(after.get_avatar_content_type(), None); | ||
| 1344 | - assert_eq!(after.get_avatar_size(), None); | ||
| 1345 | - | ||
| 1346 | - assert!( | ||
| 1347 | - User::clear_avatar(&UserId::from_key("yok"), &db) | ||
| 1348 | - .await | ||
| 1349 | - .unwrap() | ||
| 1350 | - .is_none(), | ||
| 1351 | - "a missing row is None, not an error" | ||
| 1352 | - ); | ||
| 1353 | - } | ||
| 1354 | 334 | ||
| 1355 | #[tokio::test] | 335 | #[tokio::test] |
| 1356 | async fn username_newtype_validates() { | 336 | async fn username_newtype_validates() { |
src/service/course.rsmodified+2 -2
| @@ -13,7 +13,7 @@ use crate::domain::homework_file::HomeworkFile; | |||
| 13 | use crate::domain::question_image::QuestionImage; | 13 | use crate::domain::question_image::QuestionImage; |
| 14 | use crate::domain::role::Role; | 14 | use crate::domain::role::Role; |
| 15 | use crate::domain::term::{self, TermId}; | 15 | use crate::domain::term::{self, TermId}; |
| 16 | -use crate::domain::user::{User, UserId}; | 16 | +use crate::domain::user::UserId; |
| 17 | use crate::error::{AppError, ValidationError}; | 17 | use crate::error::{AppError, ValidationError}; |
| 18 | 18 | ||
| 19 | /// Refuse the write when this course's term is archived — a pre-flight guard, | 19 | /// Refuse the write when this course's term is archived — a pre-flight guard, |
| @@ -90,7 +90,7 @@ pub async fn assign_teacher( | |||
| 90 | target: &UserId, | 90 | target: &UserId, |
| 91 | ) -> Result<Course, AppError> { | 91 | ) -> Result<Course, AppError> { |
| 92 | require_open(db, course).await?; | 92 | require_open(db, course).await?; |
| 93 | - let Some(target_user) = User::read(target, db).await? else { | 93 | + let Some(target_user) = crate::db::user::read(db, target).await? else { |
| 94 | return Err(AppError::Validation(ValidationError::Invalid { | 94 | return Err(AppError::Validation(ValidationError::Invalid { |
| 95 | field: "user_id", | 95 | field: "user_id", |
| 96 | reason: "target user does not exist", | 96 | reason: "target user does not exist", |
src/service/exam_attempt.rsmodified+3 -3
| @@ -85,7 +85,7 @@ pub fn ensure_student(user: &User) -> Result<(), AppError> { | |||
| 85 | /// save — the room's door check is not the last word for a socket that | 85 | /// save — the room's door check is not the last word for a socket that |
| 86 | /// outlives the role. | 86 | /// outlives the role. |
| 87 | pub async fn ensure_student_now(user: &UserId, db: &Database) -> Result<(), AppError> { | 87 | pub async fn ensure_student_now(user: &UserId, db: &Database) -> Result<(), AppError> { |
| 88 | - let user = crate::domain::user::User::read(user, db) | 88 | + let user = crate::db::user::read(db, user) |
| 89 | .await? | 89 | .await? |
| 90 | .ok_or(AppError::Unauthorized)?; | 90 | .ok_or(AppError::Unauthorized)?; |
| 91 | ensure_student(&user) | 91 | ensure_student(&user) |
| @@ -552,10 +552,10 @@ mod tests { | |||
| 552 | .hash_async() | 552 | .hash_async() |
| 553 | .await | 553 | .await |
| 554 | .unwrap(); | 554 | .unwrap(); |
| 555 | - crate::domain::user::User::create( | 555 | + crate::db::user::create( |
| 556 | + db, | ||
| 556 | crate::domain::user::Username::try_new("ogrenci").unwrap(), | 557 | crate::domain::user::Username::try_new("ogrenci").unwrap(), |
| 557 | hash, | 558 | hash, |
| 558 | - db, | ||
| 559 | ) | 559 | ) |
| 560 | .await | 560 | .await |
| 561 | .unwrap() | 561 | .unwrap() |
src/service/mod.rsmodified+1 -0
| @@ -15,3 +15,4 @@ pub mod note; | |||
| 15 | pub mod payment_ledger; | 15 | pub mod payment_ledger; |
| 16 | pub mod session; | 16 | pub mod session; |
| 17 | pub mod settings; | 17 | pub mod settings; |
| 18 | +pub mod user; | ||
src/service/user.rsadded+477 -0
| @@ -0,0 +1,477 @@ | |||
| 1 | +//! User workflows: the boot-time admin seed, and the role change — the | ||
| 2 | +//! admin floor ([`ADMIN_FLOOR_LOCK`]) held across the count that checks it | ||
| 3 | +//! and the transaction that commits it, sweeps included. Reads, listings, | ||
| 4 | +//! the row mint, and the field-scoped writers live in [`crate::db::user`]. | ||
| 5 | + | ||
| 6 | +use crate::database::Database; | ||
| 7 | +use crate::db::user; | ||
| 8 | +use crate::domain::board::Board; | ||
| 9 | +use crate::domain::note_file::FileContentType; | ||
| 10 | +use crate::domain::preferences::{Language, PaletteColor, Theme}; | ||
| 11 | +use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; | ||
| 12 | +use crate::domain::role::Role; | ||
| 13 | +use crate::domain::user::{Password, PasswordHash, User, UserId, Username}; | ||
| 14 | +use crate::error::AppError; | ||
| 15 | + | ||
| 16 | +/// One role demotion at a time, school-wide. | ||
| 17 | +/// | ||
| 18 | +/// The invariant it protects is "the school always keeps an admin", and that | ||
| 19 | +/// guard is a count-then-write: read whether another admin exists, then lower | ||
| 20 | +/// this row. SurrealDB conflict-checks neither side of that pair — a | ||
| 21 | +/// `BEGIN…COMMIT` does not serialize a cross-record count against a concurrent | ||
| 22 | +/// update (write-skew, see [`crate::db::cap`]) and a statement that only | ||
| 23 | +/// *reads* the rival's row never collides with it. So two admins demoting each | ||
| 24 | +/// other both counted the other and both committed, leaving **zero** admins and | ||
| 25 | +/// a school nobody can administer: `ensure_admin` refuses to promote an | ||
| 26 | +/// existing non-admin row on every later boot, so the only way back was hand-run | ||
| 27 | +/// SurrealQL against the volume. | ||
| 28 | +/// | ||
| 29 | +/// Serializing the pair is what closes it, the same argument | ||
| 30 | +/// [`crate::service::settings::SETTINGS_LOCK`] makes one level up: the deployment | ||
| 31 | +/// runs one process by contract (stop-the-world upgrades), so process-wide is | ||
| 32 | +/// deployment-wide. A per-row counter (the [`crate::db::cap`] shape) does | ||
| 33 | +/// not fit — the count being capped is over *every* user row, with no parent | ||
| 34 | +/// record to hold it and no place to seed one without a backfill. | ||
| 35 | +/// | ||
| 36 | +/// **Lock order:** taken alone. Nothing is locked while it is held. | ||
| 37 | +static ADMIN_FLOOR_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); | ||
| 38 | + | ||
| 39 | +/// Idempotent startup seed: guarantee an admin account with this username. | ||
| 40 | +/// Missing → created directly with [`Role::Admin`]. Already an admin → | ||
| 41 | +/// nothing to do (the stored password stays whatever it is — the seed never | ||
| 42 | +/// rewrites credentials). Taken by a non-admin → refuse to touch it and log | ||
| 43 | +/// a warning: silently promoting an account someone else registered would | ||
| 44 | +/// be a privilege escalation, so that conflict is resolved out-of-band. | ||
| 45 | +pub async fn ensure_admin( | ||
| 46 | + db: &Database, | ||
| 47 | + username: Username, | ||
| 48 | + password: Password, | ||
| 49 | +) -> Result<(), AppError> { | ||
| 50 | + match user::find_by_username(db, username.as_str()).await? { | ||
| 51 | + Some(user) if user.role == Role::Admin => Ok(()), | ||
| 52 | + Some(_) => { | ||
| 53 | + tracing::warn!( | ||
| 54 | + "ADMIN_USERNAME names an existing non-admin account; refusing to promote it. \ | ||
| 55 | + Grant the role through an existing admin or the manual SurrealQL path." | ||
| 56 | + ); | ||
| 57 | + Ok(()) | ||
| 58 | + } | ||
| 59 | + None => { | ||
| 60 | + // One statement, admin from birth. Never create-then-promote: | ||
| 61 | + // an interruption between those two writes leaves a student row | ||
| 62 | + // holding ADMIN_USERNAME, which the `Some(_)` arm above then | ||
| 63 | + // refuses to promote — forever, on every subsequent boot. There | ||
| 64 | + // is no marker that could tell such a row apart from a stranger | ||
| 65 | + // who registered the name first, so the hole cannot be healed | ||
| 66 | + // later; it has to be impossible to open. | ||
| 67 | + user::create_with_role(db, username, password.hash_async().await?, Role::Admin) | ||
| 68 | + .await?; | ||
| 69 | + // No `username` field: with OTLP on every event is exported as a | ||
| 70 | + // log record, so an account name here leaves the process. | ||
| 71 | + tracing::info!("seeded the admin account named by ADMIN_USERNAME"); | ||
| 72 | + Ok(()) | ||
| 73 | + } | ||
| 74 | + } | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +/// Overwrite this user's role **and** shed every grant the new role may not | ||
| 78 | +/// hold, in one transaction. The caller is responsible for authorizing it. | ||
| 79 | +/// | ||
| 80 | +/// Refuses (`Conflict`) to lower the school's last admin, however the | ||
| 81 | +/// request is spelled and however many demotions are in flight at once — | ||
| 82 | +/// see [`ADMIN_FLOOR_LOCK`] for why that guard cannot live in the | ||
| 83 | +/// transaction below. | ||
| 84 | +/// | ||
| 85 | +/// The sweep itself — what each role change owes, arm by arm, and why the | ||
| 86 | +/// conditions differ — is [`user::set_role_cascade`]'s statement list, | ||
| 87 | +/// documented there. | ||
| 88 | +pub async fn set_role( | ||
| 89 | + db: &Database, | ||
| 90 | + target: &UserId, | ||
| 91 | + role: Role, | ||
| 92 | +) -> Result<(User, Vec<Board>), AppError> { | ||
| 93 | + // A missing account is a 404, answered before the floor is asked. | ||
| 94 | + user::read(db, target).await?.ok_or(AppError::NotFound)?; | ||
| 95 | + // The admin floor, held from the count to the commit ([`ADMIN_FLOOR_LOCK`] | ||
| 96 | + // for why a transaction cannot do this). Asked on the *live* rows rather | ||
| 97 | + // than a caller's snapshot, so a snapshot that predates a promotion cannot | ||
| 98 | + // skip the check, and cheap enough to ask on every demotion: one round | ||
| 99 | + // trip on an admin-only route. | ||
| 100 | + let _floor = if role == Role::Admin { | ||
| 101 | + None | ||
| 102 | + } else { | ||
| 103 | + let guard = ADMIN_FLOOR_LOCK.lock().await; | ||
| 104 | + if user::would_orphan_admins(db, target).await? { | ||
| 105 | + return Err(AppError::Conflict( | ||
| 106 | + "the school must keep at least one admin — promote another account first", | ||
| 107 | + )); | ||
| 108 | + } | ||
| 109 | + Some(guard) | ||
| 110 | + }; | ||
| 111 | + user::set_role_cascade(db, target, role).await | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +/// Register a new account — the web layer's row mint. New users always start | ||
| 115 | +/// as [`Role::Student`]; elevation is a separate, admin-only action | ||
| 116 | +/// (see [`set_role`]). | ||
| 117 | +pub async fn create( | ||
| 118 | + db: &Database, | ||
| 119 | + username: Username, | ||
| 120 | + password_hash: PasswordHash, | ||
| 121 | +) -> Result<User, AppError> { | ||
| 122 | + user::create(db, username, password_hash).await | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +/// Mint a row holding `role` outright — the school-creation path, whose | ||
| 126 | +/// first account must be an admin from birth. | ||
| 127 | +pub async fn create_with_role( | ||
| 128 | + db: &Database, | ||
| 129 | + username: Username, | ||
| 130 | + password_hash: PasswordHash, | ||
| 131 | + role: Role, | ||
| 132 | +) -> Result<User, AppError> { | ||
| 133 | + user::create_with_role(db, username, password_hash, role).await | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +/// One user row, for callers that only inspect it — the web layer's reads go | ||
| 137 | +/// through here. | ||
| 138 | +pub async fn read(db: &Database, id: &UserId) -> Result<Option<User>, AppError> { | ||
| 139 | + user::read(db, id).await | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +/// Every account, newest first — the web layer's paging read. | ||
| 143 | +pub async fn list_all( | ||
| 144 | + db: &Database, | ||
| 145 | + limit: Option<i64>, | ||
| 146 | + offset: i64, | ||
| 147 | +) -> Result<(Vec<User>, i64), AppError> { | ||
| 148 | + user::list_all(db, limit, offset).await | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +/// The users behind `ids` in one query; missing ids simply absent. | ||
| 152 | +pub async fn list_by_ids(db: &Database, ids: &[UserId]) -> Result<Vec<User>, AppError> { | ||
| 153 | + user::list_by_ids(db, ids).await | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +/// Username/name/surname fragment search — the pickers' backing read. | ||
| 157 | +pub async fn search( | ||
| 158 | + db: &Database, | ||
| 159 | + query: &str, | ||
| 160 | + role: Option<Role>, | ||
| 161 | + allowed_roles: Option<&[Role]>, | ||
| 162 | + limit: Option<i64>, | ||
| 163 | + offset: i64, | ||
| 164 | +) -> Result<(Vec<User>, i64), AppError> { | ||
| 165 | + user::search(db, query, role, allowed_roles, limit, offset).await | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +/// The login lookup. Usernames are stored trimmed; callers trim the same way | ||
| 169 | +/// so a padded attempt matches the canonical name. | ||
| 170 | +pub async fn find_by_username(db: &Database, username: &str) -> Result<Option<User>, AppError> { | ||
| 171 | + user::find_by_username(db, username).await | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +/// Persist the personal-info/profile fields a PATCH carried. | ||
| 175 | +pub async fn set_profile( | ||
| 176 | + db: &Database, | ||
| 177 | + id: &UserId, | ||
| 178 | + name: Option<Option<PersonName>>, | ||
| 179 | + surname: Option<Option<PersonName>>, | ||
| 180 | + email: Option<Option<Email>>, | ||
| 181 | + phone: Option<Option<Phone>>, | ||
| 182 | + birth_date: Option<Option<BirthDate>>, | ||
| 183 | + display_name: Option<Option<DisplayName>>, | ||
| 184 | + bio: Option<Option<Bio>>, | ||
| 185 | +) -> Result<User, AppError> { | ||
| 186 | + user::set_profile(db, id, name, surname, email, phone, birth_date, display_name, bio).await | ||
| 187 | +} | ||
| 188 | + | ||
| 189 | +/// Persist an avatar upload, handing back the replaced blob's name. | ||
| 190 | +pub async fn set_avatar( | ||
| 191 | + db: &Database, | ||
| 192 | + id: &UserId, | ||
| 193 | + file: &str, | ||
| 194 | + content_type: &FileContentType, | ||
| 195 | + size: i64, | ||
| 196 | +) -> Result<Option<User>, AppError> { | ||
| 197 | + user::set_avatar(db, id, file, content_type, size).await | ||
| 198 | +} | ||
| 199 | + | ||
| 200 | +/// Clear the avatar, handing back the blob's name for deletion. | ||
| 201 | +pub async fn clear_avatar(db: &Database, id: &UserId) -> Result<Option<User>, AppError> { | ||
| 202 | + user::clear_avatar(db, id).await | ||
| 203 | +} | ||
| 204 | + | ||
| 205 | +/// Rewrite the credential — the admin-password reset's store half. | ||
| 206 | +pub async fn set_password_hash( | ||
| 207 | + db: &Database, | ||
| 208 | + id: &UserId, | ||
| 209 | + password_hash: PasswordHash, | ||
| 210 | +) -> Result<Option<User>, AppError> { | ||
| 211 | + user::set_password_hash(db, id, password_hash).await | ||
| 212 | +} | ||
| 213 | + | ||
| 214 | +/// Persist the UI-preference fields a PATCH carried. | ||
| 215 | +pub async fn set_preferences( | ||
| 216 | + db: &Database, | ||
| 217 | + id: &UserId, | ||
| 218 | + theme: Option<Option<Theme>>, | ||
| 219 | + language: Option<Option<Language>>, | ||
| 220 | + palette_color: Option<Option<PaletteColor>>, | ||
| 221 | +) -> Result<User, AppError> { | ||
| 222 | + user::set_preferences(db, id, theme, language, palette_color).await | ||
| 223 | +} | ||
| 224 | + | ||
| 225 | +#[cfg(test)] | ||
| 226 | +mod tests { | ||
| 227 | + use super::*; | ||
| 228 | + use crate::database::{Database, init_mem}; | ||
| 229 | + use crate::domain::user::Password; | ||
| 230 | + | ||
| 231 | + async fn a_user(username: &str, db: &Database) -> User { | ||
| 232 | + user::create( | ||
| 233 | + db, | ||
| 234 | + Username::try_new(username).unwrap(), | ||
| 235 | + Password::try_new("secret1") | ||
| 236 | + .unwrap() | ||
| 237 | + .hash_async() | ||
| 238 | + .await | ||
| 239 | + .unwrap(), | ||
| 240 | + ) | ||
| 241 | + .await | ||
| 242 | + .unwrap() | ||
| 243 | + } | ||
| 244 | + | ||
| 245 | + /// The board result slot is an *index* into a batch whose length depends on | ||
| 246 | + /// which arms the role selected, so it is the one number in the cascade a | ||
| 247 | + /// silent mistake would not show up in the store: pointed at the wrong | ||
| 248 | + /// statement it yields an empty list, and every whiteboard room whose roster | ||
| 249 | + /// just changed is simply never told. Assert the rows come back. | ||
| 250 | + #[tokio::test] | ||
| 251 | + async fn the_cascade_returns_the_boards_it_stripped() { | ||
| 252 | + use crate::domain::board::{Board, BoardTitle}; | ||
| 253 | + | ||
| 254 | + let db = init_mem().await.unwrap(); | ||
| 255 | + let creator = a_user("ogretmen", &db).await; | ||
| 256 | + let guest = a_user("ogrenci", &db).await; | ||
| 257 | + let board = Board::create( | ||
| 258 | + creator.get_id(), | ||
| 259 | + BoardTitle::try_new("Geometri").unwrap(), | ||
| 260 | + vec![guest.get_id().clone()], | ||
| 261 | + &db, | ||
| 262 | + ) | ||
| 263 | + .await | ||
| 264 | + .unwrap(); | ||
| 265 | + | ||
| 266 | + // A promotion touches no roster and must report none. | ||
| 267 | + let (guest, boards) = set_role(&db, guest.get_id(), Role::Teacher) | ||
| 268 | + .await | ||
| 269 | + .unwrap(); | ||
| 270 | + assert!( | ||
| 271 | + boards.is_empty(), | ||
| 272 | + "only a demotion to parent strips rosters" | ||
| 273 | + ); | ||
| 274 | + | ||
| 275 | + let (_, boards) = set_role(&db, guest.get_id(), Role::Parent) | ||
| 276 | + .await | ||
| 277 | + .unwrap(); | ||
| 278 | + assert_eq!(boards.len(), 1, "the stripped room must be reported back"); | ||
| 279 | + assert_eq!(boards[0].get_id(), board.get_id()); | ||
| 280 | + assert!( | ||
| 281 | + boards[0].get_participants().is_empty(), | ||
| 282 | + "and carry the roster the room is about to be told about" | ||
| 283 | + ); | ||
| 284 | + } | ||
| 285 | + | ||
| 286 | + /// The half the roster strip cannot reach: the board's **creator**. Demoted, | ||
| 287 | + /// they are 404'd off their own room, every command on it is creator-only | ||
| 288 | + /// for everyone else, and nothing in the crate lists a board a caller is not | ||
| 289 | + /// on — so the room could be cleared, locked, closed and deleted by nobody | ||
| 290 | + /// while its participants kept drawing on it. The demotion closes it, and | ||
| 291 | + /// closing is *all* it does: the roster, the row and every mark stay | ||
| 292 | + /// readable. | ||
| 293 | + #[tokio::test] | ||
| 294 | + async fn a_demoted_creator_s_board_is_closed_and_still_readable() { | ||
| 295 | + use crate::domain::board::{Board, BoardTitle}; | ||
| 296 | + use crate::domain::board_stroke::{BOARD_CLOSED, BoardStroke}; | ||
| 297 | + | ||
| 298 | + let db = init_mem().await.unwrap(); | ||
| 299 | + let creator = a_user("ogretmen", &db).await; | ||
| 300 | + let guest = a_user("ogrenci", &db).await; | ||
| 301 | + let board = Board::create( | ||
| 302 | + creator.get_id(), | ||
| 303 | + BoardTitle::try_new("Geometri").unwrap(), | ||
| 304 | + vec![guest.get_id().clone()], | ||
| 305 | + &db, | ||
| 306 | + ) | ||
| 307 | + .await | ||
| 308 | + .unwrap(); | ||
| 309 | + let mark = |epoch| { | ||
| 310 | + let (id, author, db) = (board.get_id().clone(), guest.get_id().clone(), db.clone()); | ||
| 311 | + async move { BoardStroke::append(&id, &author, "{\"p\":[1]}", epoch, &db).await } | ||
| 312 | + }; | ||
| 313 | + mark(0).await.unwrap(); | ||
| 314 | + | ||
| 315 | + let (creator, boards) = set_role(&db, creator.get_id(), Role::Parent) | ||
| 316 | + .await | ||
| 317 | + .unwrap(); | ||
| 318 | + assert_eq!(boards.len(), 1, "the room must be reported back"); | ||
| 319 | + let stamp = boards[0] | ||
| 320 | + .get_closed_at() | ||
| 321 | + .expect("and carry the closing stamp the room is told about"); | ||
| 322 | + | ||
| 323 | + // Stored, not merely reported — and nothing else moved. | ||
| 324 | + let stored = Board::read(board.get_id(), &db).await.unwrap().unwrap(); | ||
| 325 | + assert_eq!(stored.get_closed_at(), Some(stamp)); | ||
| 326 | + assert_eq!( | ||
| 327 | + stored.get_participants(), | ||
| 328 | + [guest.get_id().clone()], | ||
| 329 | + "closing must not empty the roster it did not touch" | ||
| 330 | + ); | ||
| 331 | + assert_eq!( | ||
| 332 | + BoardStroke::history(board.get_id(), None, false, None, 0, &db) | ||
| 333 | + .await | ||
| 334 | + .unwrap() | ||
| 335 | + .1, | ||
| 336 | + 1, | ||
| 337 | + "the marks the participants drew stay on disk" | ||
| 338 | + ); | ||
| 339 | + | ||
| 340 | + // Read-only for the participants who are still on it. | ||
| 341 | + assert!( | ||
| 342 | + matches!(mark(0).await, Err(AppError::Conflict(BOARD_CLOSED))), | ||
| 343 | + "a closed board must refuse every write with the terminal answer" | ||
| 344 | + ); | ||
| 345 | + | ||
| 346 | + // The stamp is the record: a re-run of the sweep must not move it. | ||
| 347 | + tokio::time::sleep(std::time::Duration::from_millis(2)).await; | ||
| 348 | + set_role(&db, creator.get_id(), Role::Parent) | ||
| 349 | + .await | ||
| 350 | + .unwrap(); | ||
| 351 | + assert_eq!( | ||
| 352 | + Board::read(board.get_id(), &db) | ||
| 353 | + .await | ||
| 354 | + .unwrap() | ||
| 355 | + .unwrap() | ||
| 356 | + .get_closed_at(), | ||
| 357 | + Some(stamp), | ||
| 358 | + "the close is a compare-and-set, not a re-stamp" | ||
| 359 | + ); | ||
| 360 | + } | ||
| 361 | + | ||
| 362 | + /// A demotion below `teacher` must take the published calendar with it and | ||
| 363 | + /// settle the bookings on it. Nothing else can: a slot is listed only on its | ||
| 364 | + /// own teacher's calendar (and hidden from every other reader once its owner | ||
| 365 | + /// is demoted), deleted only by a teacher+, and a booking on one can be | ||
| 366 | + /// decided only by a teacher+ and cancelled only by its requester — who is | ||
| 367 | + /// refused the moment the window opens. So a slot left behind here is a row | ||
| 368 | + /// no route can reach and a seat nothing can ever free. | ||
| 369 | + #[tokio::test] | ||
| 370 | + async fn a_demotion_withdraws_the_calendar_and_settles_its_bookings() { | ||
| 371 | + use crate::domain::appointment_slot::AppointmentSlot; | ||
| 372 | + use crate::domain::appointment::{AppointmentReason, AppointmentStatus}; | ||
| 373 | + use crate::service::appointment; | ||
| 374 | + use crate::domain::timestamp::Timestamp; | ||
| 375 | + | ||
| 376 | + let db = init_mem().await.unwrap(); | ||
| 377 | + let staff = |name: &'static str, db: Database| async move { | ||
| 378 | + let teacher = a_user(name, &db).await; | ||
| 379 | + set_role(&db, teacher.get_id(), Role::Teacher) | ||
| 380 | + .await | ||
| 381 | + .unwrap() | ||
| 382 | + .0 | ||
| 383 | + }; | ||
| 384 | + let teacher = staff("ogretmen", db.clone()).await; | ||
| 385 | + let other = staff("digerogretmen", db.clone()).await; | ||
| 386 | + let student = a_user("ogrenci", &db).await; | ||
| 387 | + let soon = |offset| Timestamp::from_millis(Timestamp::now().as_millis() + offset); | ||
| 388 | + let reason = || AppointmentReason::try_new("görüşme").unwrap(); | ||
| 389 | + let slot = |owner: &User, offset: i64, db: Database| { | ||
| 390 | + let owner = owner.get_id().clone(); | ||
| 391 | + async move { | ||
| 392 | + AppointmentSlot::create(&owner, soon(offset), soon(offset + 60_000), None, &db) | ||
| 393 | + .await | ||
| 394 | + .unwrap() | ||
| 395 | + } | ||
| 396 | + }; | ||
| 397 | + | ||
| 398 | + let free = slot(&teacher, 60_000, db.clone()).await; | ||
| 399 | + let asked = slot(&teacher, 180_000, db.clone()).await; | ||
| 400 | + let agreed = slot(&teacher, 300_000, db.clone()).await; | ||
| 401 | + let kept = slot(&other, 60_000, db.clone()).await; | ||
| 402 | + | ||
| 403 | + let pending = appointment::book(&db, asked.get_id(), student.get_id(), reason()) | ||
| 404 | + .await | ||
| 405 | + .unwrap(); | ||
| 406 | + let approved = appointment::book(&db, agreed.get_id(), student.get_id(), reason()) | ||
| 407 | + .await | ||
| 408 | + .unwrap(); | ||
| 409 | + appointment::approve(&db, approved.get_id(), teacher.get_id()) | ||
| 410 | + .await | ||
| 411 | + .unwrap(); | ||
| 412 | + let elsewhere = appointment::book(&db, kept.get_id(), student.get_id(), reason()) | ||
| 413 | + .await | ||
| 414 | + .unwrap(); | ||
| 415 | + | ||
| 416 | + set_role(&db, teacher.get_id(), Role::Student) | ||
| 417 | + .await | ||
| 418 | + .unwrap(); | ||
| 419 | + | ||
| 420 | + // The calendar is gone, the booked weeks included. | ||
| 421 | + assert!( | ||
| 422 | + AppointmentSlot::list_for_teacher(teacher.get_id(), &db) | ||
| 423 | + .await | ||
| 424 | + .unwrap() | ||
| 425 | + .is_empty() | ||
| 426 | + ); | ||
| 427 | + for slot in [&free, &asked, &agreed] { | ||
| 428 | + assert!( | ||
| 429 | + AppointmentSlot::read(slot.get_id(), &db) | ||
| 430 | + .await | ||
| 431 | + .unwrap() | ||
| 432 | + .is_none(), | ||
| 433 | + "a slot only a teacher+ could reach outlived the role" | ||
| 434 | + ); | ||
| 435 | + } | ||
| 436 | + // Both bookings — the pending request and the confirmed meeting — ended | ||
| 437 | + // in a state their requester can still read, saying who dropped it. | ||
| 438 | + for booking in [&pending, &approved] { | ||
| 439 | + let after = appointment::read(&db, booking.get_id()) | ||
| 440 | + .await | ||
| 441 | + .unwrap() | ||
| 442 | + .expect("the requester keeps the row"); | ||
| 443 | + assert_eq!(after.get_status(), AppointmentStatus::Cancelled); | ||
| 444 | + assert_eq!(after.get_cancelled_by(), Some(teacher.get_id())); | ||
| 445 | + assert!(after.get_cancel_reason().is_some(), "and why"); | ||
| 446 | + } | ||
| 447 | + // The seat each held died with its slot row, so nothing is pinned: no | ||
| 448 | + // live booking is left pointing at a slot that no longer exists. | ||
| 449 | + let mut result = db | ||
| 450 | + .query( | ||
| 451 | + "SELECT VALUE id FROM appointment \ | ||
| 452 | + WHERE status IN ['pending', 'approved'] AND slot.starts_at = NONE", | ||
| 453 | + ) | ||
| 454 | + .await | ||
| 455 | + .unwrap() | ||
| 456 | + .check() | ||
| 457 | + .unwrap(); | ||
| 458 | + assert!(result.take::<Vec<surrealdb::types::RecordId>>(0).unwrap().is_empty()); | ||
| 459 | + | ||
| 460 | + // Another teacher's calendar is nobody else's business. | ||
| 461 | + assert_eq!( | ||
| 462 | + AppointmentSlot::list_for_teacher(other.get_id(), &db) | ||
| 463 | + .await | ||
| 464 | + .unwrap() | ||
| 465 | + .len(), | ||
| 466 | + 1 | ||
| 467 | + ); | ||
| 468 | + assert_eq!( | ||
| 469 | + appointment::read(&db, elsewhere.get_id()) | ||
| 470 | + .await | ||
| 471 | + .unwrap() | ||
| 472 | + .unwrap() | ||
| 473 | + .get_status(), | ||
| 474 | + AppointmentStatus::Pending | ||
| 475 | + ); | ||
| 476 | + } | ||
| 477 | +} | ||
src/web/appointments.rsmodified+6 -5
| @@ -424,7 +424,7 @@ async fn list_slots( | |||
| 424 | .filter(|teacher| seen.insert(teacher.key().to_string())) | 424 | .filter(|teacher| seen.insert(teacher.key().to_string())) |
| 425 | .cloned() | 425 | .cloned() |
| 426 | .collect(); | 426 | .collect(); |
| 427 | - let people: HashMap<String, PersonRef> = User::list_by_ids(&teachers, &st.db) | 427 | + let people: HashMap<String, PersonRef> = crate::service::user::list_by_ids(&st.db, &teachers) |
| 428 | .await? | 428 | .await? |
| 429 | .iter() | 429 | .iter() |
| 430 | .filter(|teacher| teacher.get_role().at_least(Role::Teacher)) | 430 | .filter(|teacher| teacher.get_role().at_least(Role::Teacher)) |
| @@ -558,7 +558,7 @@ async fn book( | |||
| 558 | .ok_or(AppError::NotFound)?; | 558 | .ok_or(AppError::NotFound)?; |
| 559 | // The slot row is not the grant: a teacher demoted since publishing keeps | 559 | // The slot row is not the grant: a teacher demoted since publishing keeps |
| 560 | // their rows, and those rows must be inert. Their live role decides. | 560 | // their rows, and those rows must be inert. Their live role decides. |
| 561 | - if !User::read(slot.get_teacher(), &st.db) | 561 | + if !crate::service::user::read(&st.db, slot.get_teacher()) |
| 562 | .await? | 562 | .await? |
| 563 | .is_some_and(|teacher| teacher.get_role().at_least(Role::Teacher)) | 563 | .is_some_and(|teacher| teacher.get_role().at_least(Role::Teacher)) |
| 564 | { | 564 | { |
| @@ -902,10 +902,10 @@ mod tests { | |||
| 902 | .hash_async() | 902 | .hash_async() |
| 903 | .await | 903 | .await |
| 904 | .unwrap(); | 904 | .unwrap(); |
| 905 | - let user = User::create(Username::try_new(username).unwrap(), hash, db) | 905 | + let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) |
| 906 | .await | 906 | .await |
| 907 | .unwrap(); | 907 | .unwrap(); |
| 908 | - user.set_role(role, db).await.unwrap().0 | 908 | + crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0 |
| 909 | } | 909 | } |
| 910 | 910 | ||
| 911 | /// All five `can_manage` sites are `RequireTeacher` today, so this is | 911 | /// All five `can_manage` sites are `RequireTeacher` today, so this is |
| @@ -927,7 +927,8 @@ mod tests { | |||
| 927 | assert!(can_manage(&slot, &owner)); | 927 | assert!(can_manage(&slot, &owner)); |
| 928 | 928 | ||
| 929 | for role in [Role::Student, Role::Parent] { | 929 | for role in [Role::Student, Role::Parent] { |
| 930 | - let demoted = owner.clone().set_role(role, &db).await.unwrap().0; | 930 | + let demoted = |
| 931 | + crate::service::user::set_role(&db, owner.get_id(), role).await.unwrap().0; | ||
| 931 | assert!( | 932 | assert!( |
| 932 | !can_manage(&slot, &demoted), | 933 | !can_manage(&slot, &demoted), |
| 933 | "{role:?} slot owner still decides its bookings" | 934 | "{role:?} slot owner still decides its bookings" |
src/web/attendance.rsmodified+1 -1
| @@ -200,7 +200,7 @@ async fn user_report( | |||
| 200 | let target = UserId::from_key(&user); | 200 | let target = UserId::from_key(&user); |
| 201 | ensure_can_observe(&caller, &target, &st.db).await?; | 201 | ensure_can_observe(&caller, &target, &st.db).await?; |
| 202 | // User must exist — a missing user is a 404, not an empty report. | 202 | // User must exist — a missing user is a 404, not an empty report. |
| 203 | - User::read(&target, &st.db) | 203 | + crate::service::user::read(&st.db, &target) |
| 204 | .await? | 204 | .await? |
| 205 | .ok_or(AppError::NotFound)?; | 205 | .ok_or(AppError::NotFound)?; |
| 206 | // Only an exactly-teacher caller is narrowed to their managed courses; | 206 | // Only an exactly-teacher caller is narrowed to their managed courses; |
src/web/auth.rsmodified+6 -5
| @@ -12,7 +12,7 @@ use utoipa_axum::routes; | |||
| 12 | use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS}; | 12 | use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS}; |
| 13 | use crate::domain::builder::BuilderSession; | 13 | use crate::domain::builder::BuilderSession; |
| 14 | use crate::domain::role::Role as DomainRole; | 14 | use crate::domain::role::Role as DomainRole; |
| 15 | -use crate::domain::user::{Password, PasswordHash, User, Username}; | 15 | +use crate::domain::user::{Password, PasswordHash, Username}; |
| 16 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 16 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 17 | use crate::rate_limit::{RateLimitConfig, RateLimiter}; | 17 | use crate::rate_limit::{RateLimitConfig, RateLimiter}; |
| 18 | use crate::service; | 18 | use crate::service; |
| @@ -118,7 +118,8 @@ async fn register( | |||
| 118 | } | 118 | } |
| 119 | .into()); | 119 | .into()); |
| 120 | } | 120 | } |
| 121 | - // Hash BEFORE the availability check inside `User::create`, never after: the | 121 | + // Hash BEFORE the availability check inside the user-create path, never |
| 122 | + // after: the | ||
| 122 | // ~33ms of argon2 is what makes both outcomes cost the same, so a taken | 123 | // ~33ms of argon2 is what makes both outcomes cost the same, so a taken |
| 123 | // username can't be spotted by a fast reply. The only work the taken path | 124 | // username can't be spotted by a fast reply. The only work the taken path |
| 124 | // skips is the insert itself, orders of magnitude below hashing. | 125 | // skips is the insert itself, orders of magnitude below hashing. |
| @@ -126,12 +127,12 @@ async fn register( | |||
| 126 | // Built once, before the branch: the created and the taken path answer with | 127 | // Built once, before the branch: the created and the taken path answer with |
| 127 | // the very same value, so they cannot be told apart by construction rather | 128 | // the very same value, so they cannot be told apart by construction rather |
| 128 | // than by keeping two field lists in sync. Every fresh account starts as a | 129 | // than by keeping two field lists in sync. Every fresh account starts as a |
| 129 | - // student (`User::create`), so this holds whichever way the insert goes. | 130 | + // student (`service::user::create`), so this holds whichever way the insert goes. |
| 130 | let body = RegisterResponse { | 131 | let body = RegisterResponse { |
| 131 | username: username.as_str().to_string(), | 132 | username: username.as_str().to_string(), |
| 132 | role: DomainRole::Student.into(), | 133 | role: DomainRole::Student.into(), |
| 133 | }; | 134 | }; |
| 134 | - match User::create(username, password_hash, &db).await { | 135 | + match crate::service::user::create(&db, username, password_hash).await { |
| 135 | Ok(_) => {} | 136 | Ok(_) => {} |
| 136 | // Taken. Log the real reason server-side; the caller gets the same 201 | 137 | // Taken. Log the real reason server-side; the caller gets the same 201 |
| 137 | // and the same body, because telling the two apart is the whole thing | 138 | // and the same body, because telling the two apart is the whole thing |
| @@ -174,7 +175,7 @@ async fn login( | |||
| 174 | let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?; | 175 | let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?; |
| 175 | // Usernames are stored trimmed (see `Username::try_new`); trim the lookup | 176 | // Usernames are stored trimmed (see `Username::try_new`); trim the lookup |
| 176 | // the same way so a padded login attempt matches the canonical name. | 177 | // the same way so a padded login attempt matches the canonical name. |
| 177 | - let user = match User::find_by_username(req.username.trim(), &db).await? { | 178 | + let user = match crate::service::user::find_by_username(&db, req.username.trim()).await? { |
| 178 | // Verification is `.await`ed so argon2 runs on the blocking pool instead | 179 | // Verification is `.await`ed so argon2 runs on the blocking pool instead |
| 179 | // of stalling an async worker; that rules out a match guard, which | 180 | // of stalling an async worker; that rules out a match guard, which |
| 180 | // cannot await. | 181 | // cannot await. |
src/web/bank_questions.rsmodified+6 -3
| @@ -948,10 +948,10 @@ mod tests { | |||
| 948 | .hash_async() | 948 | .hash_async() |
| 949 | .await | 949 | .await |
| 950 | .unwrap(); | 950 | .unwrap(); |
| 951 | - let user = User::create(Username::try_new(username).unwrap(), hash, db) | 951 | + let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) |
| 952 | .await | 952 | .await |
| 953 | .unwrap(); | 953 | .unwrap(); |
| 954 | - user.set_role(role, db).await.unwrap().0 | 954 | + crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0 |
| 955 | } | 955 | } |
| 956 | 956 | ||
| 957 | /// Every bank route is `RequireTeacher` today, so this is pinned at the | 957 | /// Every bank route is `RequireTeacher` today, so this is pinned at the |
| @@ -977,7 +977,10 @@ mod tests { | |||
| 977 | assert!(ensure_owner(&question, &owner).is_ok()); | 977 | assert!(ensure_owner(&question, &owner).is_ok()); |
| 978 | 978 | ||
| 979 | for role in [Role::Student, Role::Parent] { | 979 | for role in [Role::Student, Role::Parent] { |
| 980 | - let demoted = owner.clone().set_role(role, &db).await.unwrap().0; | 980 | + let demoted = crate::service::user::set_role(&db, owner.get_id(), role) |
| 981 | + .await | ||
| 982 | + .unwrap() | ||
| 983 | + .0; | ||
| 981 | assert!( | 984 | assert!( |
| 982 | !can_see(&question, &demoted), | 985 | !can_see(&question, &demoted), |
| 983 | "{role:?} owner still reads their template" | 986 | "{role:?} owner still reads their template" |
src/web/board_ws.rsmodified+9 -7
| @@ -72,7 +72,7 @@ use crate::domain::board::{Board, BoardId}; | |||
| 72 | use crate::domain::board_stroke::{self, BoardStroke}; | 72 | use crate::domain::board_stroke::{self, BoardStroke}; |
| 73 | use crate::domain::role::Role; | 73 | use crate::domain::role::Role; |
| 74 | use crate::domain::timestamp::Timestamp; | 74 | use crate::domain::timestamp::Timestamp; |
| 75 | -use crate::domain::user::{User, UserId}; | 75 | +use crate::domain::user::UserId; |
| 76 | use crate::error::AppError; | 76 | use crate::error::AppError; |
| 77 | use crate::state::AppState; | 77 | use crate::state::AppState; |
| 78 | use crate::tenant::Slug; | 78 | use crate::tenant::Slug; |
| @@ -207,7 +207,7 @@ type Step = Result<(), RoomClosed>; | |||
| 207 | /// role barred from the whiteboard outright — must not leave an open socket | 207 | /// role barred from the whiteboard outright — must not leave an open socket |
| 208 | /// still committing strokes. | 208 | /// still committing strokes. |
| 209 | async fn live_board(board: &BoardId, user: &UserId, db: &Database) -> Result<Board, AppError> { | 209 | async fn live_board(board: &BoardId, user: &UserId, db: &Database) -> Result<Board, AppError> { |
| 210 | - let barred = User::read(user, db) | 210 | + let barred = crate::service::user::read(db, user) |
| 211 | .await? | 211 | .await? |
| 212 | .is_none_or(|caller| !caller.get_role().at_least(Role::Student)); | 212 | .is_none_or(|caller| !caller.get_role().at_least(Role::Student)); |
| 213 | if barred { | 213 | if barred { |
| @@ -681,17 +681,17 @@ mod tests { | |||
| 681 | 681 | ||
| 682 | let db = crate::database::init_mem().await.unwrap(); | 682 | let db = crate::database::init_mem().await.unwrap(); |
| 683 | let password = Password::try_new("secret1").unwrap(); | 683 | let password = Password::try_new("secret1").unwrap(); |
| 684 | - let creator = User::create( | 684 | + let creator = crate::service::user::create( |
| 685 | + &db, | ||
| 685 | Username::try_new("ogretmen").unwrap(), | 686 | Username::try_new("ogretmen").unwrap(), |
| 686 | password.hash_async().await.unwrap(), | 687 | password.hash_async().await.unwrap(), |
| 687 | - &db, | ||
| 688 | ) | 688 | ) |
| 689 | .await | 689 | .await |
| 690 | .unwrap(); | 690 | .unwrap(); |
| 691 | - let mate = User::create( | 691 | + let mate = crate::service::user::create( |
| 692 | + &db, | ||
| 692 | Username::try_new("ogrenci").unwrap(), | 693 | Username::try_new("ogrenci").unwrap(), |
| 693 | password.hash_async().await.unwrap(), | 694 | password.hash_async().await.unwrap(), |
| 694 | - &db, | ||
| 695 | ) | 695 | ) |
| 696 | .await | 696 | .await |
| 697 | .unwrap(); | 697 | .unwrap(); |
| @@ -713,7 +713,9 @@ mod tests { | |||
| 713 | 713 | ||
| 714 | // Demoted while the socket is open: refused from here on, and with the | 714 | // Demoted while the socket is open: refused from here on, and with the |
| 715 | // frame a denied write already uses — no new frame type. | 715 | // frame a denied write already uses — no new frame type. |
| 716 | - mate.set_role(Role::Parent, &db).await.unwrap(); | 716 | + crate::service::user::set_role(&db, mate.get_id(), Role::Parent) |
| 717 | + .await | ||
| 718 | + .unwrap(); | ||
| 717 | let err = live_board(board.get_id(), &mate_id, &db).await.unwrap_err(); | 719 | let err = live_board(board.get_id(), &mate_id, &db).await.unwrap_err(); |
| 718 | assert!( | 720 | assert!( |
| 719 | matches!(err, AppError::Forbidden(_)), | 721 | matches!(err, AppError::Forbidden(_)), |
src/web/boards.rsmodified+3 -3
| @@ -137,7 +137,7 @@ async fn resolve_participants( | |||
| 137 | // Absent from this list means "no such user, or below `student`" — the two | 137 | // Absent from this list means "no such user, or below `student`" — the two |
| 138 | // are one case here, and telling them apart is what the caller must not be | 138 | // are one case here, and telling them apart is what the caller must not be |
| 139 | // able to do anyway. | 139 | // able to do anyway. |
| 140 | - let eligible: Vec<UserId> = User::list_by_ids(&wanted, db) | 140 | + let eligible: Vec<UserId> = crate::service::user::list_by_ids(db, &wanted) |
| 141 | .await? | 141 | .await? |
| 142 | .iter() | 142 | .iter() |
| 143 | .filter(|found| found.get_role().at_least(Role::Student)) | 143 | .filter(|found| found.get_role().at_least(Role::Student)) |
| @@ -838,7 +838,7 @@ async fn invite_board( | |||
| 838 | // a source is a whole group, and one member who has left or was never | 838 | // a source is a whole group, and one member who has left or was never |
| 839 | // eligible must not fail the invite for the other twenty-nine. | 839 | // eligible must not fail the invite for the other twenty-nine. |
| 840 | let mut roster = board.get_participants().to_vec(); | 840 | let mut roster = board.get_participants().to_vec(); |
| 841 | - for candidate in User::list_by_ids(&invited, &st.db).await? { | 841 | + for candidate in crate::service::user::list_by_ids(&st.db, &invited).await? { |
| 842 | if !candidate.get_role().at_least(Role::Student) { | 842 | if !candidate.get_role().at_least(Role::Student) { |
| 843 | continue; | 843 | continue; |
| 844 | } | 844 | } |
| @@ -920,7 +920,7 @@ mod tests { | |||
| 920 | .check() | 920 | .check() |
| 921 | .unwrap(); | 921 | .unwrap(); |
| 922 | let who = async |key: &str| { | 922 | let who = async |key: &str| { |
| 923 | - User::read(&UserId::from_key(key), &db) | 923 | + crate::service::user::read(&db, &UserId::from_key(key)) |
| 924 | .await | 924 | .await |
| 925 | .unwrap() | 925 | .unwrap() |
| 926 | .unwrap() | 926 | .unwrap() |
src/web/builder.rsmodified+5 -3
| @@ -225,7 +225,7 @@ fn path_slug(raw: &str) -> Result<Slug, AppError> { | |||
| 225 | /// below admin → `409`, the repo's verdict for "the row exists, its state | 225 | /// below admin → `409`, the repo's verdict for "the row exists, its state |
| 226 | /// refuses this". | 226 | /// refuses this". |
| 227 | async fn school_admin(username: &str, db: &crate::database::Database) -> Result<User, AppError> { | 227 | async fn school_admin(username: &str, db: &crate::database::Database) -> Result<User, AppError> { |
| 228 | - let user = User::find_by_username(username.trim(), db) | 228 | + let user = crate::service::user::find_by_username(db, username.trim()) |
| 229 | .await? | 229 | .await? |
| 230 | .ok_or(AppError::NotFound)?; | 230 | .ok_or(AppError::NotFound)?; |
| 231 | if user.get_role() != Role::Admin { | 231 | if user.get_role() != Role::Admin { |
| @@ -356,7 +356,9 @@ async fn create_school( | |||
| 356 | modules.validate()?; | 356 | modules.validate()?; |
| 357 | 357 | ||
| 358 | let db = st.tenants.create(&slug, &name, modules).await?; | 358 | let db = st.tenants.create(&slug, &name, modules).await?; |
| 359 | - if let Err(err) = User::create_with_role(username, password_hash, Role::Admin, &db).await { | 359 | + if let Err(err) = |
| 360 | + crate::service::user::create_with_role(&db, username, password_hash, Role::Admin).await | ||
| 361 | + { | ||
| 360 | // A school nobody can log into is worse than no school: take the | 362 | // A school nobody can log into is worse than no school: take the |
| 361 | // database back so the very same request can simply be retried. | 363 | // database back so the very same request can simply be retried. |
| 362 | if let Err(cleanup) = st.tenants.drop(&slug).await { | 364 | if let Err(cleanup) = st.tenants.drop(&slug).await { |
| @@ -754,7 +756,7 @@ async fn reset_admin_password( | |||
| 754 | let user = school_admin(&req.username, &db).await?; | 756 | let user = school_admin(&req.username, &db).await?; |
| 755 | let password_hash = Password::try_new(&req.password)?.hash_async().await?; | 757 | let password_hash = Password::try_new(&req.password)?.hash_async().await?; |
| 756 | 758 | ||
| 757 | - User::set_password_hash(user.get_id(), password_hash, &db) | 759 | + crate::service::user::set_password_hash(&db, user.get_id(), password_hash) |
| 758 | .await? | 760 | .await? |
| 759 | .ok_or(AppError::NotFound)?; | 761 | .ok_or(AppError::NotFound)?; |
| 760 | // The other half: the new password means nothing while a cookie minted | 762 | // The other half: the new password means nothing while a cookie minted |
src/web/classes.rsmodified+10 -7
| @@ -268,7 +268,7 @@ async fn teacher_or_none(text: Option<&str>, db: &Database) -> Result<Option<Use | |||
| 268 | 268 | ||
| 269 | /// The teacher-or-higher account `key` names, or the 400 both write paths give. | 269 | /// The teacher-or-higher account `key` names, or the 400 both write paths give. |
| 270 | async fn resolve_teacher(key: &str, db: &Database) -> Result<User, AppError> { | 270 | async fn resolve_teacher(key: &str, db: &Database) -> Result<User, AppError> { |
| 271 | - let Some(teacher) = User::read(&UserId::from_key(key), db).await? else { | 271 | + let Some(teacher) = crate::service::user::read(db, &UserId::from_key(key)).await? else { |
| 272 | return Err(AppError::Validation(ValidationError::Invalid { | 272 | return Err(AppError::Validation(ValidationError::Invalid { |
| 273 | field: "teacher_id", | 273 | field: "teacher_id", |
| 274 | reason: "target user does not exist", | 274 | reason: "target user does not exist", |
| @@ -657,7 +657,7 @@ async fn user_classes( | |||
| 657 | let target = UserId::from_key(&user); | 657 | let target = UserId::from_key(&user); |
| 658 | ensure_can_observe(&caller, &target, &st.db).await?; | 658 | ensure_can_observe(&caller, &target, &st.db).await?; |
| 659 | // User must exist — a missing user is a 404, not an empty page. | 659 | // User must exist — a missing user is a 404, not an empty page. |
| 660 | - User::read(&target, &st.db) | 660 | + crate::service::user::read(&st.db, &target) |
| 661 | .await? | 661 | .await? |
| 662 | .ok_or(AppError::NotFound)?; | 662 | .ok_or(AppError::NotFound)?; |
| 663 | // A linked parent reads this too, and is no more entitled to the office's | 663 | // A linked parent reads this too, and is no more entitled to the office's |
| @@ -748,7 +748,7 @@ async fn add_member( | |||
| 748 | class.require_open(&st.db).await?; | 748 | class.require_open(&st.db).await?; |
| 749 | 749 | ||
| 750 | let target = UserId::from_key(&req.user_id); | 750 | let target = UserId::from_key(&req.user_id); |
| 751 | - let Some(target_user) = User::read(&target, &st.db).await? else { | 751 | + let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { |
| 752 | return Err(AppError::Validation(ValidationError::Invalid { | 752 | return Err(AppError::Validation(ValidationError::Invalid { |
| 753 | field: "user_id", | 753 | field: "user_id", |
| 754 | reason: "target user does not exist", | 754 | reason: "target user does not exist", |
| @@ -1493,25 +1493,28 @@ mod tests { | |||
| 1493 | #[tokio::test] | 1493 | #[tokio::test] |
| 1494 | async fn an_empty_teacher_is_no_teacher_and_a_student_is_never_one() { | 1494 | async fn an_empty_teacher_is_no_teacher_and_a_student_is_never_one() { |
| 1495 | use crate::domain::role::Role; | 1495 | use crate::domain::role::Role; |
| 1496 | - use crate::domain::user::{Password, User, Username}; | 1496 | + use crate::domain::user::{Password, Username}; |
| 1497 | 1497 | ||
| 1498 | let db = crate::database::init_mem().await.unwrap(); | 1498 | let db = crate::database::init_mem().await.unwrap(); |
| 1499 | assert!(teacher_or_none(None, &db).await.unwrap().is_none()); | 1499 | assert!(teacher_or_none(None, &db).await.unwrap().is_none()); |
| 1500 | assert!(teacher_or_none(Some(""), &db).await.unwrap().is_none()); | 1500 | assert!(teacher_or_none(Some(""), &db).await.unwrap().is_none()); |
| 1501 | 1501 | ||
| 1502 | let make = async |name: &str, role: Role| { | 1502 | let make = async |name: &str, role: Role| { |
| 1503 | - let user = User::create( | 1503 | + let user = crate::service::user::create( |
| 1504 | + &db, | ||
| 1504 | Username::try_new(name).unwrap(), | 1505 | Username::try_new(name).unwrap(), |
| 1505 | Password::try_new("secret1") | 1506 | Password::try_new("secret1") |
| 1506 | .unwrap() | 1507 | .unwrap() |
| 1507 | .hash_async() | 1508 | .hash_async() |
| 1508 | .await | 1509 | .await |
| 1509 | .unwrap(), | 1510 | .unwrap(), |
| 1510 | - &db, | ||
| 1511 | ) | 1511 | ) |
| 1512 | .await | 1512 | .await |
| 1513 | .unwrap(); | 1513 | .unwrap(); |
| 1514 | - user.set_role(role, &db).await.unwrap().0 | 1514 | + crate::service::user::set_role(&db, user.get_id(), role) |
| 1515 | + .await | ||
| 1516 | + .unwrap() | ||
| 1517 | + .0 | ||
| 1515 | }; | 1518 | }; |
| 1516 | let student = make("ali", Role::Student).await; | 1519 | let student = make("ali", Role::Student).await; |
| 1517 | let teacher = make("ada", Role::Teacher).await; | 1520 | let teacher = make("ada", Role::Teacher).await; |
src/web/dto.rsmodified+1 -1
| @@ -136,7 +136,7 @@ pub async fn person_map( | |||
| 136 | .into_iter() | 136 | .into_iter() |
| 137 | .filter(|id| seen.insert(id.key().to_string())) | 137 | .filter(|id| seen.insert(id.key().to_string())) |
| 138 | .collect(); | 138 | .collect(); |
| 139 | - let users = User::list_by_ids(&unique, db).await?; | 139 | + let users = crate::service::user::list_by_ids(db, &unique).await?; |
| 140 | Ok(users | 140 | Ok(users |
| 141 | .iter() | 141 | .iter() |
| 142 | .map(|user| (user.get_id().key().to_string(), PersonRef::new(user))) | 142 | .map(|user| (user.get_id().key().to_string(), PersonRef::new(user))) |
src/web/events.rsmodified+9 -6
| @@ -517,7 +517,7 @@ async fn mark( | |||
| 517 | }; | 517 | }; |
| 518 | 518 | ||
| 519 | // Target user must exist. | 519 | // Target user must exist. |
| 520 | - let Some(target_user) = User::read(&target, &st.db).await? else { | 520 | + let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { |
| 521 | return Err(AppError::Validation(ValidationError::Invalid { | 521 | return Err(AppError::Validation(ValidationError::Invalid { |
| 522 | field: "user_id", | 522 | field: "user_id", |
| 523 | reason: "target user does not exist", | 523 | reason: "target user does not exist", |
| @@ -759,7 +759,7 @@ async fn register( | |||
| 759 | Some(ref key) => UserId::from_key(key), | 759 | Some(ref key) => UserId::from_key(key), |
| 760 | None => user.get_id().clone(), | 760 | None => user.get_id().clone(), |
| 761 | }; | 761 | }; |
| 762 | - let Some(target_user) = User::read(&target, &st.db).await? else { | 762 | + let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { |
| 763 | return Err(AppError::Validation(ValidationError::Invalid { | 763 | return Err(AppError::Validation(ValidationError::Invalid { |
| 764 | field: "user_id", | 764 | field: "user_id", |
| 765 | reason: "target user does not exist", | 765 | reason: "target user does not exist", |
| @@ -835,7 +835,7 @@ async fn unregister( | |||
| 835 | // stranded, and a volume written before `Registration::register` claimed | 835 | // stranded, and a volume written before `Registration::register` claimed |
| 836 | // the holder's row already carries some. | 836 | // the holder's row already carries some. |
| 837 | if &target != user.get_id() | 837 | if &target != user.get_id() |
| 838 | - && let Some(target_user) = User::read(&target, &st.db).await? | 838 | + && let Some(target_user) = crate::service::user::read(&st.db, &target).await? |
| 839 | && target_user.get_role().at_least(Role::Teacher) | 839 | && target_user.get_role().at_least(Role::Teacher) |
| 840 | { | 840 | { |
| 841 | return Err(AppError::Forbidden( | 841 | return Err(AppError::Forbidden( |
| @@ -865,10 +865,10 @@ mod tests { | |||
| 865 | .hash_async() | 865 | .hash_async() |
| 866 | .await | 866 | .await |
| 867 | .unwrap(); | 867 | .unwrap(); |
| 868 | - let user = User::create(Username::try_new(username).unwrap(), hash, db) | 868 | + let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) |
| 869 | .await | 869 | .await |
| 870 | .unwrap(); | 870 | .unwrap(); |
| 871 | - user.set_role(role, db).await.unwrap().0 | 871 | + crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0 |
| 872 | } | 872 | } |
| 873 | 873 | ||
| 874 | /// `can_manage` is only reached behind `RequireTeacher` today, so this is | 874 | /// `can_manage` is only reached behind `RequireTeacher` today, so this is |
| @@ -892,7 +892,10 @@ mod tests { | |||
| 892 | assert!(can_manage(&event, &creator)); | 892 | assert!(can_manage(&event, &creator)); |
| 893 | 893 | ||
| 894 | for role in [Role::Student, Role::Parent] { | 894 | for role in [Role::Student, Role::Parent] { |
| 895 | - let demoted = creator.clone().set_role(role, &db).await.unwrap().0; | 895 | + let demoted = crate::service::user::set_role(&db, creator.get_id(), role) |
| 896 | + .await | ||
| 897 | + .unwrap() | ||
| 898 | + .0; | ||
| 896 | assert!( | 899 | assert!( |
| 897 | !can_manage(&event, &demoted), | 900 | !can_manage(&event, &demoted), |
| 898 | "{role:?} creator still manages the event" | 901 | "{role:?} creator still manages the event" |
src/web/exams/mod.rsmodified+1 -1
| @@ -574,7 +574,7 @@ async fn grade( | |||
| 574 | } | 574 | } |
| 575 | 575 | ||
| 576 | // Target user must exist. | 576 | // Target user must exist. |
| 577 | - let Some(target_user) = User::read(&target, &st.db).await? else { | 577 | + let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { |
| 578 | return Err(AppError::Validation(ValidationError::Invalid { | 578 | return Err(AppError::Validation(ValidationError::Invalid { |
| 579 | field: "user_id", | 579 | field: "user_id", |
| 580 | reason: "target user does not exist", | 580 | reason: "target user does not exist", |
src/web/extractor.rsmodified+1 -1
| @@ -50,7 +50,7 @@ where | |||
| 50 | return Err(AppError::Unauthorized); | 50 | return Err(AppError::Unauthorized); |
| 51 | } | 51 | } |
| 52 | 52 | ||
| 53 | - User::read(session.user(), &db) | 53 | + service::user::read(&db, session.user()) |
| 54 | .await? | 54 | .await? |
| 55 | .ok_or(AppError::Unauthorized) | 55 | .ok_or(AppError::Unauthorized) |
| 56 | } | 56 | } |
src/web/homework.rsmodified+2 -2
| @@ -1163,7 +1163,7 @@ async fn grade_homework( | |||
| 1163 | } | 1163 | } |
| 1164 | 1164 | ||
| 1165 | // Target user must exist. | 1165 | // Target user must exist. |
| 1166 | - let Some(target_user) = User::read(&target, &st.db).await? else { | 1166 | + let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { |
| 1167 | return Err(AppError::Validation(ValidationError::Invalid { | 1167 | return Err(AppError::Validation(ValidationError::Invalid { |
| 1168 | field: "user", | 1168 | field: "user", |
| 1169 | reason: "target user does not exist", | 1169 | reason: "target user does not exist", |
| @@ -1480,7 +1480,7 @@ async fn homework_report( | |||
| 1480 | let target = UserId::from_key(&user); | 1480 | let target = UserId::from_key(&user); |
| 1481 | ensure_can_observe(&caller, &target, &st.db).await?; | 1481 | ensure_can_observe(&caller, &target, &st.db).await?; |
| 1482 | // User must exist — a missing user is a 404, not an empty report. | 1482 | // User must exist — a missing user is a 404, not an empty report. |
| 1483 | - User::read(&target, &st.db) | 1483 | + crate::service::user::read(&st.db, &target) |
| 1484 | .await? | 1484 | .await? |
| 1485 | .ok_or(AppError::NotFound)?; | 1485 | .ok_or(AppError::NotFound)?; |
| 1486 | // Only an exactly-teacher caller is narrowed to their managed courses; | 1486 | // Only an exactly-teacher caller is narrowed to their managed courses; |
src/web/marks.rsmodified+1 -1
| @@ -203,7 +203,7 @@ async fn user_marks( | |||
| 203 | let target = UserId::from_key(&user); | 203 | let target = UserId::from_key(&user); |
| 204 | ensure_can_observe(&caller, &target, &st.db).await?; | 204 | ensure_can_observe(&caller, &target, &st.db).await?; |
| 205 | // User must exist — a missing user is a 404, not an empty report. | 205 | // User must exist — a missing user is a 404, not an empty report. |
| 206 | - User::read(&target, &st.db) | 206 | + crate::service::user::read(&st.db, &target) |
| 207 | .await? | 207 | .await? |
| 208 | .ok_or(AppError::NotFound)?; | 208 | .ok_or(AppError::NotFound)?; |
| 209 | // Only an exactly-teacher caller is narrowed to their managed courses; | 209 | // Only an exactly-teacher caller is narrowed to their managed courses; |
src/web/meals.rsmodified+5 -6
| @@ -676,7 +676,7 @@ async fn update_profile( | |||
| 676 | let target = UserId::from_key(&user); | 676 | let target = UserId::from_key(&user); |
| 677 | // Only a student eats off the school's menus; a profile on anyone else is | 677 | // Only a student eats off the school's menus; a profile on anyone else is |
| 678 | // a typo, and a typo here is an allergy filed against the wrong person. | 678 | // a typo, and a typo here is an allergy filed against the wrong person. |
| 679 | - if User::read(&target, &st.db) | 679 | + if crate::service::user::read(&st.db, &target) |
| 680 | .await? | 680 | .await? |
| 681 | .ok_or(AppError::NotFound)? | 681 | .ok_or(AppError::NotFound)? |
| 682 | .get_role() | 682 | .get_role() |
| @@ -803,7 +803,7 @@ async fn booking_target( | |||
| 803 | }, | 803 | }, |
| 804 | ))?); | 804 | ))?); |
| 805 | if ParentLink::exists(caller.get_id(), &target, db).await? | 805 | if ParentLink::exists(caller.get_id(), &target, db).await? |
| 806 | - && User::read(&target, db) | 806 | + && crate::service::user::read(db, &target) |
| 807 | .await? | 807 | .await? |
| 808 | .is_some_and(|target| target.get_role() == Role::Student) | 808 | .is_some_and(|target| target.get_role() == Role::Student) |
| 809 | { | 809 | { |
| @@ -1146,7 +1146,7 @@ async fn mark_attendance( | |||
| 1146 | let student = UserId::from_key(&req.student_id); | 1146 | let student = UserId::from_key(&req.student_id); |
| 1147 | // The target must exist; no booking is required, since a walk-in was still | 1147 | // The target must exist; no booking is required, since a walk-in was still |
| 1148 | // served and the record is operationally true. | 1148 | // served and the record is operationally true. |
| 1149 | - if User::read(&student, &st.db).await?.is_none() { | 1149 | + if crate::service::user::read(&st.db, &student).await?.is_none() { |
| 1150 | return Err(AppError::Validation(ValidationError::Invalid { | 1150 | return Err(AppError::Validation(ValidationError::Invalid { |
| 1151 | field: "student_id", | 1151 | field: "student_id", |
| 1152 | reason: "target user does not exist", | 1152 | reason: "target user does not exist", |
| @@ -1350,10 +1350,9 @@ async fn ensure_can_read_money( | |||
| 1350 | // The link row alone is not the grant: a link whose student side changed | 1350 | // The link row alone is not the grant: a link whose student side changed |
| 1351 | // role must be inert, so the target's live role is re-read. A missing or | 1351 | // role must be inert, so the target's live role is re-read. A missing or |
| 1352 | // non-student target falls through to the same 403 — a parent never gets an | 1352 | // non-student target falls through to the same 403 — a parent never gets an |
| 1353 | - // existence oracle. | ||
| 1354 | if caller.get_role() == Role::Parent | 1353 | if caller.get_role() == Role::Parent |
| 1355 | && ParentLink::exists(caller.get_id(), target, db).await? | 1354 | && ParentLink::exists(caller.get_id(), target, db).await? |
| 1356 | - && User::read(target, db) | 1355 | + && crate::service::user::read(db, target) |
| 1357 | .await? | 1356 | .await? |
| 1358 | .is_some_and(|target| target.get_role() == Role::Student) | 1357 | .is_some_and(|target| target.get_role() == Role::Student) |
| 1359 | { | 1358 | { |
| @@ -1500,7 +1499,7 @@ async fn record_credit( | |||
| 1500 | // promoted to staff keeps what they owed), and the student rule alone made | 1499 | // promoted to staff keeps what they owed), and the student rule alone made |
| 1501 | // that debt permanently unsettleable — there is no other route that | 1500 | // that debt permanently unsettleable — there is no other route that |
| 1502 | // appends a credit. A typo'd staff id has no lines, so it still 400s. | 1501 | // appends a credit. A typo'd staff id has no lines, so it still 400s. |
| 1503 | - if User::read(&student, &st.db) | 1502 | + if crate::service::user::read(&st.db, &student) |
| 1504 | .await? | 1503 | .await? |
| 1505 | .ok_or(AppError::NotFound)? | 1504 | .ok_or(AppError::NotFound)? |
| 1506 | .get_role() | 1505 | .get_role() |
src/web/messages.rsmodified+2 -2
| @@ -120,7 +120,7 @@ async fn load_people(messages: &[Message], db: &Database) -> Result<People, AppE | |||
| 120 | }) | 120 | }) |
| 121 | .filter(|id| seen.insert(id.key().to_string())) | 121 | .filter(|id| seen.insert(id.key().to_string())) |
| 122 | .collect(); | 122 | .collect(); |
| 123 | - let users = User::list_by_ids(&ids, db).await?; | 123 | + let users = crate::service::user::list_by_ids(db, &ids).await?; |
| 124 | Ok(people_of(&users)) | 124 | Ok(people_of(&users)) |
| 125 | } | 125 | } |
| 126 | 126 | ||
| @@ -197,7 +197,7 @@ async fn send_message( | |||
| 197 | reason: "cannot message yourself", | 197 | reason: "cannot message yourself", |
| 198 | })); | 198 | })); |
| 199 | } | 199 | } |
| 200 | - let recipient = User::read(&UserId::from_key(&req.recipient_id), &st.db) | 200 | + let recipient = crate::service::user::read(&st.db, &UserId::from_key(&req.recipient_id)) |
| 201 | .await? | 201 | .await? |
| 202 | .ok_or(AppError::NotFound)?; | 202 | .ok_or(AppError::NotFound)?; |
| 203 | if !user.get_role().may_message(recipient.get_role()) { | 203 | if !user.get_role().may_message(recipient.get_role()) { |
src/web/mod.rsmodified+9 -10
| @@ -98,7 +98,7 @@ pub(crate) async fn ensure_can_observe( | |||
| 98 | // an existence oracle. | 98 | // an existence oracle. |
| 99 | if caller.get_role() == Role::Parent | 99 | if caller.get_role() == Role::Parent |
| 100 | && ParentLink::exists(caller.get_id(), target, db).await? | 100 | && ParentLink::exists(caller.get_id(), target, db).await? |
| 101 | - && User::read(target, db) | 101 | + && crate::service::user::read(db, target) |
| 102 | .await? | 102 | .await? |
| 103 | .is_some_and(|target| target.get_role() == Role::Student) | 103 | .is_some_and(|target| target.get_role() == Role::Student) |
| 104 | { | 104 | { |
| @@ -131,7 +131,7 @@ pub(crate) async fn ensure_can_observe( | |||
| 131 | /// A missing user counts as demoted. The ordinary path is one extra read and no | 131 | /// A missing user counts as demoted. The ordinary path is one extra read and no |
| 132 | /// write at all. | 132 | /// write at all. |
| 133 | pub(crate) async fn undo_if_demoted(target: &UserId, db: &Database) -> Result<(), AppError> { | 133 | pub(crate) async fn undo_if_demoted(target: &UserId, db: &Database) -> Result<(), AppError> { |
| 134 | - if User::read(target, db) | 134 | + if crate::service::user::read(db, target) |
| 135 | .await? | 135 | .await? |
| 136 | .is_some_and(|user| user.get_role().at_least(Role::Teacher)) | 136 | .is_some_and(|user| user.get_role().at_least(Role::Teacher)) |
| 137 | { | 137 | { |
| @@ -414,22 +414,21 @@ mod tests { | |||
| 414 | 414 | ||
| 415 | let db = crate::database::init_mem().await.unwrap(); | 415 | let db = crate::database::init_mem().await.unwrap(); |
| 416 | let office = UserId::from_key("office"); | 416 | let office = UserId::from_key("office"); |
| 417 | - let teacher = User::create( | 417 | + let teacher = crate::service::user::create( |
| 418 | + &db, | ||
| 418 | Username::try_new("ada").unwrap(), | 419 | Username::try_new("ada").unwrap(), |
| 419 | Password::try_new("secret1") | 420 | Password::try_new("secret1") |
| 420 | .unwrap() | 421 | .unwrap() |
| 421 | .hash_async() | 422 | .hash_async() |
| 422 | .await | 423 | .await |
| 423 | .unwrap(), | 424 | .unwrap(), |
| 424 | - &db, | ||
| 425 | ) | 425 | ) |
| 426 | .await | 426 | .await |
| 427 | - .unwrap() | 427 | + .unwrap(); |
| 428 | - .set_role(Role::Teacher, &db) | 428 | + crate::service::user::set_role(&db, teacher.get_id(), Role::Teacher) |
| 429 | - .await | 429 | + .await |
| 430 | - .unwrap() | 430 | + .unwrap() |
| 431 | - .0; | 431 | + .0; |
| 432 | - | ||
| 433 | let assigned = async |db: &Database| { | 432 | let assigned = async |db: &Database| { |
| 434 | let class = ClassGroup::create( | 433 | let class = ClassGroup::create( |
| 435 | &office, | 434 | &office, |
src/web/payments.rsmodified+2 -2
| @@ -434,7 +434,7 @@ async fn assign_plan( | |||
| 434 | let student = UserId::from_key(&student_id); | 434 | let student = UserId::from_key(&student_id); |
| 435 | // A fee record belongs to a student; billing anyone else is a typo, and | 435 | // A fee record belongs to a student; billing anyone else is a typo, and |
| 436 | // a typo here is money against the wrong person. | 436 | // a typo here is money against the wrong person. |
| 437 | - let is_student = User::read(&student, &st.db) | 437 | + let is_student = crate::service::user::read(&st.db, &student) |
| 438 | .await? | 438 | .await? |
| 439 | .is_some_and(|user| user.get_role() == Role::Student); | 439 | .is_some_and(|user| user.get_role() == Role::Student); |
| 440 | let (status, reason) = if is_student { | 440 | let (status, reason) = if is_student { |
| @@ -791,7 +791,7 @@ async fn ensure_can_read_payments( | |||
| 791 | // existence oracle. | 791 | // existence oracle. |
| 792 | if caller.get_role() == Role::Parent | 792 | if caller.get_role() == Role::Parent |
| 793 | && ParentLink::exists(caller.get_id(), target, db).await? | 793 | && ParentLink::exists(caller.get_id(), target, db).await? |
| 794 | - && User::read(target, db) | 794 | + && crate::service::user::read(db, target) |
| 795 | .await? | 795 | .await? |
| 796 | .is_some_and(|target| target.get_role() == Role::Student) | 796 | .is_some_and(|target| target.get_role() == Role::Student) |
| 797 | { | 797 | { |
src/web/pomodoro.rsmodified+1 -1
| @@ -225,7 +225,7 @@ async fn user_pomodoro( | |||
| 225 | let target = UserId::from_key(&user); | 225 | let target = UserId::from_key(&user); |
| 226 | ensure_can_observe(&caller, &target, &st.db).await?; | 226 | ensure_can_observe(&caller, &target, &st.db).await?; |
| 227 | // User must exist — a missing user is a 404, not an empty log. | 227 | // User must exist — a missing user is a 404, not an empty log. |
| 228 | - User::read(&target, &st.db) | 228 | + crate::service::user::read(&st.db, &target) |
| 229 | .await? | 229 | .await? |
| 230 | .ok_or(AppError::NotFound)?; | 230 | .ok_or(AppError::NotFound)?; |
| 231 | let sessions = PomodoroSession::list_for_user(&target, &st.db).await?; | 231 | let sessions = PomodoroSession::list_for_user(&target, &st.db).await?; |
src/web/tenant_state.rsmodified+3 -3
| @@ -183,7 +183,7 @@ mod tests { | |||
| 183 | use crate::database::init_mem_tenants; | 183 | use crate::database::init_mem_tenants; |
| 184 | use crate::db::session; | 184 | use crate::db::session; |
| 185 | use crate::domain::builder::{Builder, BuilderSession}; | 185 | use crate::domain::builder::{Builder, BuilderSession}; |
| 186 | - use crate::domain::user::{Password, User, Username}; | 186 | + use crate::domain::user::{Password, Username}; |
| 187 | use crate::tenant::DEMO_SLUG; | 187 | use crate::tenant::DEMO_SLUG; |
| 188 | use crate::web::{CurrentUser, RequireBuilder}; | 188 | use crate::web::{CurrentUser, RequireBuilder}; |
| 189 | 189 | ||
| @@ -204,14 +204,14 @@ mod tests { | |||
| 204 | .await | 204 | .await |
| 205 | .expect("the demo school"); | 205 | .expect("the demo school"); |
| 206 | 206 | ||
| 207 | - let user = User::create( | 207 | + let user = crate::service::user::create( |
| 208 | + &school, | ||
| 208 | Username::try_new("ada").unwrap(), | 209 | Username::try_new("ada").unwrap(), |
| 209 | Password::try_new("secret1") | 210 | Password::try_new("secret1") |
| 210 | .unwrap() | 211 | .unwrap() |
| 211 | .hash_async() | 212 | .hash_async() |
| 212 | .await | 213 | .await |
| 213 | .unwrap(), | 214 | .unwrap(), |
| 214 | - &school, | ||
| 215 | ) | 215 | ) |
| 216 | .await | 216 | .await |
| 217 | .unwrap(); | 217 | .unwrap(); |
src/web/users.rsmodified+42 -37
| @@ -147,18 +147,18 @@ async fn apply_profile( | |||
| 147 | let birth_date = merge_field(req.birth_date.as_deref(), BirthDate::try_new)?; | 147 | let birth_date = merge_field(req.birth_date.as_deref(), BirthDate::try_new)?; |
| 148 | let display_name = merge_field(req.display_name.as_deref(), DisplayName::try_new)?; | 148 | let display_name = merge_field(req.display_name.as_deref(), DisplayName::try_new)?; |
| 149 | let bio = merge_field(req.bio.as_deref(), Bio::try_new)?; | 149 | let bio = merge_field(req.bio.as_deref(), Bio::try_new)?; |
| 150 | - let updated = user | 150 | + let updated = crate::service::user::set_profile( |
| 151 | - .set_profile( | 151 | + db, |
| 152 | - name, | 152 | + user.get_id(), |
| 153 | - surname, | 153 | + name, |
| 154 | - email, | 154 | + surname, |
| 155 | - phone, | 155 | + email, |
| 156 | - birth_date, | 156 | + phone, |
| 157 | - display_name, | 157 | + birth_date, |
| 158 | - bio, | 158 | + display_name, |
| 159 | - db, | 159 | + bio, |
| 160 | - ) | 160 | + ) |
| 161 | - .await?; | 161 | + .await?; |
| 162 | Ok(UserResponse::new(&updated)) | 162 | Ok(UserResponse::new(&updated)) |
| 163 | } | 163 | } |
| 164 | 164 | ||
| @@ -174,9 +174,14 @@ async fn apply_preferences( | |||
| 174 | let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?; | 174 | let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?; |
| 175 | let language = merge_field(req.language.as_deref(), Language::try_from_str)?; | 175 | let language = merge_field(req.language.as_deref(), Language::try_from_str)?; |
| 176 | let palette_color = merge_field(req.palette_color.as_deref(), PaletteColor::try_from_str)?; | 176 | let palette_color = merge_field(req.palette_color.as_deref(), PaletteColor::try_from_str)?; |
| 177 | - let updated = user | 177 | + let updated = crate::service::user::set_preferences( |
| 178 | - .set_preferences(theme, language, palette_color, db) | 178 | + db, |
| 179 | - .await?; | 179 | + user.get_id(), |
| 180 | + theme, | ||
| 181 | + language, | ||
| 182 | + palette_color, | ||
| 183 | + ) | ||
| 184 | + .await?; | ||
| 180 | Ok(UserResponse::new(&updated)) | 185 | Ok(UserResponse::new(&updated)) |
| 181 | } | 186 | } |
| 182 | 187 | ||
| @@ -246,7 +251,8 @@ async fn search_users( | |||
| 246 | "students and parents may only search staff (teacher or higher)", | 251 | "students and parents may only search staff (teacher or higher)", |
| 247 | )); | 252 | )); |
| 248 | } | 253 | } |
| 249 | - let (users, total) = User::search(&req.q, role, allowed, limit, offset, &st.db).await?; | 254 | + let (users, total) = |
| 255 | + crate::service::user::search(&st.db, &req.q, role, allowed, limit, offset).await?; | ||
| 250 | let items = users.iter().map(PersonRef::new).collect(); | 256 | let items = users.iter().map(PersonRef::new).collect(); |
| 251 | Ok(Json(Page::new(items, total, limit, offset))) | 257 | Ok(Json(Page::new(items, total, limit, offset))) |
| 252 | } | 258 | } |
| @@ -274,7 +280,7 @@ async fn list_users( | |||
| 274 | Query(page): Query<PageParams>, | 280 | Query(page): Query<PageParams>, |
| 275 | ) -> Result<Json<Page<UserResponse>>, AppError> { | 281 | ) -> Result<Json<Page<UserResponse>>, AppError> { |
| 276 | let (limit, offset) = page.resolve()?; | 282 | let (limit, offset) = page.resolve()?; |
| 277 | - let (users, total) = User::list_all(limit, offset, &st.db).await?; | 283 | + let (users, total) = crate::service::user::list_all(&st.db, limit, offset).await?; |
| 278 | let items = users.iter().map(UserResponse::new).collect(); | 284 | let items = users.iter().map(UserResponse::new).collect(); |
| 279 | Ok(Json(Page::new(items, total, limit, offset))) | 285 | Ok(Json(Page::new(items, total, limit, offset))) |
| 280 | } | 286 | } |
| @@ -351,7 +357,7 @@ async fn get_user( | |||
| 351 | _admin: RequireAdmin, | 357 | _admin: RequireAdmin, |
| 352 | Path(id): Path<String>, | 358 | Path(id): Path<String>, |
| 353 | ) -> Result<Json<UserResponse>, AppError> { | 359 | ) -> Result<Json<UserResponse>, AppError> { |
| 354 | - let user = User::read(&UserId::from_key(&id), &st.db) | 360 | + let user = crate::service::user::read(&st.db, &UserId::from_key(&id)) |
| 355 | .await? | 361 | .await? |
| 356 | .ok_or(AppError::NotFound)?; | 362 | .ok_or(AppError::NotFound)?; |
| 357 | Ok(Json(UserResponse::new(&user))) | 363 | Ok(Json(UserResponse::new(&user))) |
| @@ -382,7 +388,7 @@ async fn update_user_profile( | |||
| 382 | Path(id): Path<String>, | 388 | Path(id): Path<String>, |
| 383 | Json(req): Json<UpdateProfile>, | 389 | Json(req): Json<UpdateProfile>, |
| 384 | ) -> Result<Json<UserResponse>, AppError> { | 390 | ) -> Result<Json<UserResponse>, AppError> { |
| 385 | - let user = User::read(&UserId::from_key(&id), &st.db) | 391 | + let user = crate::service::user::read(&st.db, &UserId::from_key(&id)) |
| 386 | .await? | 392 | .await? |
| 387 | .ok_or(AppError::NotFound)?; | 393 | .ok_or(AppError::NotFound)?; |
| 388 | Ok(Json(apply_profile(user, &req, &st.db).await?)) | 394 | Ok(Json(apply_profile(user, &req, &st.db).await?)) |
| @@ -413,7 +419,7 @@ async fn update_user_preferences( | |||
| 413 | Path(id): Path<String>, | 419 | Path(id): Path<String>, |
| 414 | Json(req): Json<UpdatePreferences>, | 420 | Json(req): Json<UpdatePreferences>, |
| 415 | ) -> Result<Json<UserResponse>, AppError> { | 421 | ) -> Result<Json<UserResponse>, AppError> { |
| 416 | - let user = User::read(&UserId::from_key(&id), &st.db) | 422 | + let user = crate::service::user::read(&st.db, &UserId::from_key(&id)) |
| 417 | .await? | 423 | .await? |
| 418 | .ok_or(AppError::NotFound)?; | 424 | .ok_or(AppError::NotFound)?; |
| 419 | Ok(Json(apply_preferences(user, &req, &st.db).await?)) | 425 | Ok(Json(apply_preferences(user, &req, &st.db).await?)) |
| @@ -473,16 +479,13 @@ async fn set_role( | |||
| 473 | if &target == admin.get_id() { | 479 | if &target == admin.get_id() { |
| 474 | return Err(AppError::Forbidden("cannot change your own role")); | 480 | return Err(AppError::Forbidden("cannot change your own role")); |
| 475 | } | 481 | } |
| 476 | - let user = User::read(&target, &st.db) | 482 | + // The role write and every sweep it owes commit together |
| 477 | - .await? | 483 | + // ([`crate::service::user::set_role`] carries the whole list and the |
| 478 | - .ok_or(AppError::NotFound)?; | 484 | + // reasoning behind each arm). The write ordering *within* a request is |
| 479 | - // The role write and every sweep it owes commit together ([`User::set_role`] | 485 | + // closed from the other end: a handler that assigns a teacher-only role |
| 480 | - // carries the whole list and the reasoning behind each arm). The write | 486 | + // re-reads the live role after its write ([`super::undo_if_demoted`]), so |
| 481 | - // ordering *within* a request is closed from the other end: a handler that | 487 | + // a demotion racing an assignment is caught by whichever side is second. |
| 482 | - // assigns a teacher-only role re-reads the live role after its write | 488 | + let (updated, boards) = crate::service::user::set_role(&st.db, &target, role).await?; |
| 483 | - // ([`super::undo_if_demoted`]), so a demotion racing an assignment is caught | ||
| 484 | - // by whichever side is second. | ||
| 485 | - let (updated, boards) = user.set_role(role, &st.db).await?; | ||
| 486 | // Whiteboard rooms the commit above changed, prompted with the same frames | 489 | // Whiteboard rooms the commit above changed, prompted with the same frames |
| 487 | // their own routes publish — after the commit, because the room re-reads the | 490 | // their own routes publish — after the commit, because the room re-reads the |
| 488 | // database before it acts on a frame. A room whose creator was demoted is | 491 | // database before it acts on a frame. A room whose creator was demoted is |
| @@ -543,7 +546,7 @@ async fn students_page( | |||
| 543 | .iter() | 546 | .iter() |
| 544 | .map(|link| link.get_student().clone()) | 547 | .map(|link| link.get_student().clone()) |
| 545 | .collect(); | 548 | .collect(); |
| 546 | - let mut students = User::list_by_ids(&ids, db).await?; | 549 | + let mut students = crate::service::user::list_by_ids(db, &ids).await?; |
| 547 | // The link row alone is not the grant, exactly as [`ensure_can_observe`] | 550 | // The link row alone is not the grant, exactly as [`ensure_can_observe`] |
| 548 | // says: a link whose student side changed role (a sweep lost a race with | 551 | // says: a link whose student side changed role (a sweep lost a race with |
| 549 | // `link_student`) is inert everywhere else, so it must not name a person | 552 | // `link_student`) is inert everywhere else, so it must not name a person |
| @@ -590,7 +593,7 @@ async fn link_student( | |||
| 590 | Path(id): Path<String>, | 593 | Path(id): Path<String>, |
| 591 | Json(req): Json<LinkStudent>, | 594 | Json(req): Json<LinkStudent>, |
| 592 | ) -> Result<Json<ParentLinkResponse>, AppError> { | 595 | ) -> Result<Json<ParentLinkResponse>, AppError> { |
| 593 | - let parent = User::read(&UserId::from_key(&id), &st.db) | 596 | + let parent = crate::service::user::read(&st.db, &UserId::from_key(&id)) |
| 594 | .await? | 597 | .await? |
| 595 | .ok_or(AppError::NotFound)?; | 598 | .ok_or(AppError::NotFound)?; |
| 596 | if parent.get_role() != Role::Parent { | 599 | if parent.get_role() != Role::Parent { |
| @@ -599,7 +602,9 @@ async fn link_student( | |||
| 599 | reason: "students can only be tied to a parent account", | 602 | reason: "students can only be tied to a parent account", |
| 600 | })); | 603 | })); |
| 601 | } | 604 | } |
| 602 | - let Some(student) = User::read(&UserId::from_key(&req.user_id), &st.db).await? else { | 605 | + let Some(student) = |
| 606 | + crate::service::user::read(&st.db, &UserId::from_key(&req.user_id)).await? | ||
| 607 | + else { | ||
| 603 | return Err(AppError::Validation(ValidationError::Invalid { | 608 | return Err(AppError::Validation(ValidationError::Invalid { |
| 604 | field: "user_id", | 609 | field: "user_id", |
| 605 | reason: "target user does not exist", | 610 | reason: "target user does not exist", |
| @@ -644,7 +649,7 @@ async fn list_parent_students( | |||
| 644 | Query(page): Query<PageParams>, | 649 | Query(page): Query<PageParams>, |
| 645 | ) -> Result<Json<Page<PersonRef>>, AppError> { | 650 | ) -> Result<Json<Page<PersonRef>>, AppError> { |
| 646 | let parent = UserId::from_key(&id); | 651 | let parent = UserId::from_key(&id); |
| 647 | - User::read(&parent, &st.db) | 652 | + crate::service::user::read(&st.db, &parent) |
| 648 | .await? | 653 | .await? |
| 649 | .ok_or(AppError::NotFound)?; | 654 | .ok_or(AppError::NotFound)?; |
| 650 | Ok(Json(students_page(&parent, page, &st.db).await?)) | 655 | Ok(Json(students_page(&parent, page, &st.db).await?)) |
| @@ -1065,7 +1070,7 @@ async fn ensure_may_read_profile( | |||
| 1065 | async fn readable_profile_user(st: &AppState, caller: &User, id: &str) -> Result<User, AppError> { | 1070 | async fn readable_profile_user(st: &AppState, caller: &User, id: &str) -> Result<User, AppError> { |
| 1066 | let target = UserId::from_key(id); | 1071 | let target = UserId::from_key(id); |
| 1067 | ensure_may_read_profile(caller, &target, &st.db).await?; | 1072 | ensure_may_read_profile(caller, &target, &st.db).await?; |
| 1068 | - User::read(&target, &st.db).await?.ok_or(AppError::NotFound) | 1073 | + crate::service::user::read(&st.db, &target).await?.ok_or(AppError::NotFound) |
| 1069 | } | 1074 | } |
| 1070 | 1075 | ||
| 1071 | /// The caller's own public profile — what everyone else sees of them. | 1076 | /// The caller's own public profile — what everyone else sees of them. |
| @@ -1160,7 +1165,7 @@ async fn upload_my_avatar( | |||
| 1160 | 1165 | ||
| 1161 | let file = ulid::Ulid::new().to_string(); | 1166 | let file = ulid::Ulid::new().to_string(); |
| 1162 | store_blob(&st, &file, &upload.data, || async { | 1167 | store_blob(&st, &file, &upload.data, || async { |
| 1163 | - match User::set_avatar(user.get_id(), &file, &upload.content_type, size, &st.db).await? { | 1168 | + match crate::service::user::set_avatar(&st.db, user.get_id(), &file, &upload.content_type, size).await? { |
| 1164 | // Row written; the picture this one replaced comes off disk. | 1169 | // Row written; the picture this one replaced comes off disk. |
| 1165 | Some(before) => Ok(((), before.get_avatar_file().map(str::to_string))), | 1170 | Some(before) => Ok(((), before.get_avatar_file().map(str::to_string))), |
| 1166 | // The account went away mid-upload — the fresh blob is an orphan. | 1171 | // The account went away mid-upload — the fresh blob is an orphan. |
| @@ -1281,7 +1286,7 @@ async fn delete_avatar( | |||
| 1281 | /// Clear the row's avatar and take its blob off disk — the shared tail of the | 1286 | /// Clear the row's avatar and take its blob off disk — the shared tail of the |
| 1282 | /// self and moderation deletes. A row without one (or no row at all) is a 404. | 1287 | /// self and moderation deletes. A row without one (or no row at all) is a 404. |
| 1283 | async fn drop_avatar(st: &AppState, user: &UserId) -> Result<StatusCode, AppError> { | 1288 | async fn drop_avatar(st: &AppState, user: &UserId) -> Result<StatusCode, AppError> { |
| 1284 | - let before = User::clear_avatar(user, &st.db) | 1289 | + let before = crate::service::user::clear_avatar(&st.db, user) |
| 1285 | .await? | 1290 | .await? |
| 1286 | .ok_or(AppError::NotFound)?; | 1291 | .ok_or(AppError::NotFound)?; |
| 1287 | let Some(file) = before.get_avatar_file() else { | 1292 | let Some(file) = before.get_avatar_file() else { |
src/web/work.rsmodified+2 -2
| @@ -8,7 +8,7 @@ use utoipa_axum::router::OpenApiRouter; | |||
| 8 | use utoipa_axum::routes; | 8 | use utoipa_axum::routes; |
| 9 | 9 | ||
| 10 | use crate::domain::timestamp::Timestamp; | 10 | use crate::domain::timestamp::Timestamp; |
| 11 | -use crate::domain::user::{User, UserId}; | 11 | +use crate::domain::user::UserId; |
| 12 | use crate::domain::work_entry::{WorkEntry, WorkEntryId, out_before_in_error}; | 12 | use crate::domain::work_entry::{WorkEntry, WorkEntryId, out_before_in_error}; |
| 13 | use crate::error::{AppError, ErrorResponse}; | 13 | use crate::error::{AppError, ErrorResponse}; |
| 14 | use crate::state::AppState; | 14 | use crate::state::AppState; |
| @@ -159,7 +159,7 @@ async fn user_work( | |||
| 159 | let (limit, offset) = page.resolve()?; | 159 | let (limit, offset) = page.resolve()?; |
| 160 | let target = UserId::from_key(&user); | 160 | let target = UserId::from_key(&user); |
| 161 | // User must exist — a missing user is a 404, not an empty log. | 161 | // User must exist — a missing user is a 404, not an empty log. |
| 162 | - User::read(&target, &st.db) | 162 | + crate::service::user::read(&st.db, &target) |
| 163 | .await? | 163 | .await? |
| 164 | .ok_or(AppError::NotFound)?; | 164 | .ok_or(AppError::NotFound)?; |
| 165 | let (entries, total) = WorkEntry::list_for_user(&target, limit, offset, &st.db).await?; | 165 | let (entries, total) = WorkEntry::list_for_user(&target, limit, offset, &st.db).await?; |
tests/builder_api.rsmodified+2 -2
| @@ -387,14 +387,14 @@ async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions | |||
| 387 | .get(&hezarfen_backend::tenant::Slug::try_new("gamma").unwrap()) | 387 | .get(&hezarfen_backend::tenant::Slug::try_new("gamma").unwrap()) |
| 388 | .await | 388 | .await |
| 389 | .unwrap(); | 389 | .unwrap(); |
| 390 | - hezarfen_backend::domain::user::User::create( | 390 | + hezarfen_backend::db::user::create( |
| 391 | + &gamma_db, | ||
| 391 | Username::try_new("veli").unwrap(), | 392 | Username::try_new("veli").unwrap(), |
| 392 | Password::try_new("secret1") | 393 | Password::try_new("secret1") |
| 393 | .unwrap() | 394 | .unwrap() |
| 394 | .hash_async() | 395 | .hash_async() |
| 395 | .await | 396 | .await |
| 396 | .unwrap(), | 397 | .unwrap(), |
| 397 | - &gamma_db, | ||
| 398 | ) | 398 | ) |
| 399 | .await | 399 | .await |
| 400 | .unwrap(); | 400 | .unwrap(); |
tests/integration.rsmodified+11 -5
| @@ -5234,7 +5234,7 @@ async fn admin_manages_roles_with_guards() { | |||
| 5234 | /// * `src/web/users.rs:453` — `PATCH /users/{id}/role`, the *only* path that | 5234 | /// * `src/web/users.rs:453` — `PATCH /users/{id}/role`, the *only* path that |
| 5235 | /// writes `user.role` from a caller's string (`Role::try_from_str`). | 5235 | /// writes `user.role` from a caller's string (`Role::try_from_str`). |
| 5236 | /// * `src/web/auth.rs:114` — `POST /auth/register`, hardcoded `Role::Student` | 5236 | /// * `src/web/auth.rs:114` — `POST /auth/register`, hardcoded `Role::Student` |
| 5237 | -/// (`User::create` → `create_with_role`, `src/domain/user.rs:334`). | 5237 | +/// (`service::user::create` → `create_with_role`, `src/db/user.rs`). |
| 5238 | /// * `src/web/users.rs:231` — the user-search `?role=` filter (a read). | 5238 | /// * `src/web/users.rs:231` — the user-search `?role=` filter (a read). |
| 5239 | /// * `src/web/events.rs:89` — a role-audience event stores a role string of | 5239 | /// * `src/web/events.rs:89` — a role-audience event stores a role string of |
| 5240 | /// its own on the event row. | 5240 | /// its own on the event row. |
| @@ -6367,7 +6367,7 @@ async fn promotion_via_role_endpoint_sweeps_enrollments() { | |||
| 6367 | assert!(rows.is_empty(), "enrollment rows deleted from the DB"); | 6367 | assert!(rows.is_empty(), "enrollment rows deleted from the DB"); |
| 6368 | } | 6368 | } |
| 6369 | 6369 | ||
| 6370 | -/// Regression: `User::create` pre-checks the username and then inserts, so two | 6370 | +/// Regression: `db::user::create` pre-checks the username and then inserts, so two |
| 6371 | /// concurrent registrations of the same name could both pass the check; the | 6371 | /// concurrent registrations of the same name could both pass the check; the |
| 6372 | /// loser then hit the unique index and surfaced as a raw 500. A lost race must | 6372 | /// loser then hit the unique index and surfaced as a raw 500. A lost race must |
| 6373 | /// answer the same uniform 201 as the winner (the "taken" reply is deliberately | 6373 | /// answer the same uniform 201 as the winner (the "taken" reply is deliberately |
| @@ -6865,7 +6865,9 @@ async fn admin_seed_creates_working_admin() { | |||
| 6865 | let (app, db) = app_and_db().await; | 6865 | let (app, db) = app_and_db().await; |
| 6866 | let username = Username::try_new("root").unwrap(); | 6866 | let username = Username::try_new("root").unwrap(); |
| 6867 | let password = Password::try_new("secret1").unwrap(); | 6867 | let password = Password::try_new("secret1").unwrap(); |
| 6868 | - User::ensure_admin(username, password, &db).await.unwrap(); | 6868 | + hezarfen_backend::service::user::ensure_admin(&db, username, password) |
| 6869 | + .await | ||
| 6870 | + .unwrap(); | ||
| 6869 | 6871 | ||
| 6870 | let creds = json!({ "school": "demo", "username": "root", "password": "secret1" }); | 6872 | let creds = json!({ "school": "demo", "username": "root", "password": "secret1" }); |
| 6871 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; | 6873 | let res = send(&app, "POST", "/auth/login", None, Some(creds)).await; |
| @@ -6885,7 +6887,9 @@ async fn admin_seed_is_idempotent() { | |||
| 6885 | for _ in 0..2 { | 6887 | for _ in 0..2 { |
| 6886 | let username = Username::try_new("root").unwrap(); | 6888 | let username = Username::try_new("root").unwrap(); |
| 6887 | let password = Password::try_new("secret1").unwrap(); | 6889 | let password = Password::try_new("secret1").unwrap(); |
| 6888 | - User::ensure_admin(username, password, &db).await.unwrap(); | 6890 | + hezarfen_backend::service::user::ensure_admin(&db, username, password) |
| 6891 | + .await | ||
| 6892 | + .unwrap(); | ||
| 6889 | } | 6893 | } |
| 6890 | 6894 | ||
| 6891 | let cookie = { | 6895 | let cookie = { |
| @@ -6909,7 +6913,9 @@ async fn admin_seed_refuses_existing_non_admin() { | |||
| 6909 | 6913 | ||
| 6910 | let username = Username::try_new("squatter").unwrap(); | 6914 | let username = Username::try_new("squatter").unwrap(); |
| 6911 | let password = Password::try_new("attacker-pw").unwrap(); | 6915 | let password = Password::try_new("attacker-pw").unwrap(); |
| 6912 | - User::ensure_admin(username, password, &db).await.unwrap(); | 6916 | + hezarfen_backend::service::user::ensure_admin(&db, username, password) |
| 6917 | + .await | ||
| 6918 | + .unwrap(); | ||
| 6913 | 6919 | ||
| 6914 | // Still a student: the admin-only listing stays closed... | 6920 | // Still a student: the admin-only listing stays closed... |
| 6915 | let res = send(&app, "GET", "/users", Some(&cookie), None).await; | 6921 | let res = send(&app, "GET", "/users", Some(&cookie), None).await; |
tests/regress_admin_floor.rsmodified+9 -5
| @@ -13,7 +13,7 @@ use axum::http::StatusCode; | |||
| 13 | use common::{app_and_db, login_as, me_id, send}; | 13 | use common::{app_and_db, login_as, me_id, send}; |
| 14 | use hezarfen_backend::database::Database; | 14 | use hezarfen_backend::database::Database; |
| 15 | use hezarfen_backend::domain::role::Role; | 15 | use hezarfen_backend::domain::role::Role; |
| 16 | -use hezarfen_backend::domain::user::{User, UserId}; | 16 | +use hezarfen_backend::domain::user::UserId; |
| 17 | use serde_json::json; | 17 | use serde_json::json; |
| 18 | use surrealdb::types::RecordId; | 18 | use surrealdb::types::RecordId; |
| 19 | 19 | ||
| @@ -79,8 +79,8 @@ async fn set_role_refuses_the_last_admin() { | |||
| 79 | let ada = login_as(&app, &db, "ada", "admin").await; | 79 | let ada = login_as(&app, &db, "ada", "admin").await; |
| 80 | let ada_id = UserId::from_key(&me_id(&app, &ada).await); | 80 | let ada_id = UserId::from_key(&me_id(&app, &ada).await); |
| 81 | 81 | ||
| 82 | - let user = User::read(&ada_id, &db).await.unwrap().unwrap(); | 82 | + hezarfen_backend::db::user::read(&db, &ada_id).await.unwrap().unwrap(); |
| 83 | - let refused = user.set_role(Role::Student, &db).await; | 83 | + let refused = hezarfen_backend::service::user::set_role(&db, &ada_id, Role::Student).await; |
| 84 | assert!(refused.is_err(), "the sole admin was demoted"); | 84 | assert!(refused.is_err(), "the sole admin was demoted"); |
| 85 | assert_eq!(admin_count(&db).await, 1, "the admin row was still lowered"); | 85 | assert_eq!(admin_count(&db).await, 1, "the admin row was still lowered"); |
| 86 | 86 | ||
| @@ -97,8 +97,12 @@ async fn set_role_refuses_the_last_admin() { | |||
| 97 | ) | 97 | ) |
| 98 | .await; | 98 | .await; |
| 99 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); | 99 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 100 | - let ada_row = User::read(&ada_id, &db).await.unwrap().unwrap(); | 100 | + hezarfen_backend::db::user::read(&db, &ada_id).await.unwrap().unwrap(); |
| 101 | - assert!(ada_row.set_role(Role::Student, &db).await.is_ok()); | 101 | + assert!( |
| 102 | + hezarfen_backend::service::user::set_role(&db, &ada_id, Role::Student) | ||
| 103 | + .await | ||
| 104 | + .is_ok() | ||
| 105 | + ); | ||
| 102 | assert_eq!(admin_count(&db).await, 1); | 106 | assert_eq!(admin_count(&db).await, 1); |
| 103 | } | 107 | } |
| 104 | 108 | ||
tests/regress_role_sweep.rsmodified+4 -4
| @@ -29,7 +29,7 @@ use hezarfen_backend::domain::event::EventId; | |||
| 29 | use hezarfen_backend::domain::registration::Registration; | 29 | use hezarfen_backend::domain::registration::Registration; |
| 30 | use hezarfen_backend::domain::role::Role; | 30 | use hezarfen_backend::domain::role::Role; |
| 31 | use hezarfen_backend::domain::timestamp::Timestamp; | 31 | use hezarfen_backend::domain::timestamp::Timestamp; |
| 32 | -use hezarfen_backend::domain::user::{User, UserId}; | 32 | +use hezarfen_backend::domain::user::UserId; |
| 33 | use serde_json::json; | 33 | use serde_json::json; |
| 34 | 34 | ||
| 35 | /// How many rows `sql` selects ids for. | 35 | /// How many rows `sql` selects ids for. |
| @@ -51,11 +51,11 @@ async fn counter(sql: &str, db: &Database) -> i64 { | |||
| 51 | 51 | ||
| 52 | /// Demote through the real path — the sweeps ride the role write. | 52 | /// Demote through the real path — the sweeps ride the role write. |
| 53 | async fn demote(user: &UserId, to: Role, db: &Database) { | 53 | async fn demote(user: &UserId, to: Role, db: &Database) { |
| 54 | - User::read(user, db) | 54 | + hezarfen_backend::db::user::read(db, user) |
| 55 | .await | 55 | .await |
| 56 | .unwrap() | 56 | .unwrap() |
| 57 | - .expect("the account is there") | 57 | + .expect("the account is there"); |
| 58 | - .set_role(to, db) | 58 | + hezarfen_backend::service::user::set_role(db, user, to) |
| 59 | .await | 59 | .await |
| 60 | .unwrap(); | 60 | .unwrap(); |
| 61 | } | 61 | } |