forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

user.rs488 lines, 19.5 KiBHistoryRawDownload
1//! User workflows: the boot-time admin seed, and the role change — the
2//! admin floor carried by the role write's own guard, and every sweep the
3//! change owes committed in the same transaction. Reads, listings,
4//! the row mint, and the field-scoped writers live in [`crate::db::user`].
5
6use crate::database::Database;
7use crate::db::user;
8use crate::domain::board::Board;
9use crate::domain::note_file::FileContentType;
10use crate::domain::person::PersonId;
11use crate::domain::preferences::{Language, PaletteColor, Theme};
12use crate::domain::profile::{
13 Address, Bio, BirthDate, DisplayName, Email, Gender, PersonName, Phone,
14};
15use crate::domain::role::Role;
16use crate::domain::user::{Password, StudentNumber, User, UserId, Username};
17use crate::error::AppError;
18use crate::tenant::{SchoolId, Tenants};
19
20/// Idempotent startup seed: guarantee an admin account with this username.
21/// Missing → created directly with [`Role::Admin`]. Already an admin →
22/// nothing to do (the stored password stays whatever it is — the seed never
23/// rewrites credentials). Taken by a non-admin → refuse to touch it and log
24/// a warning: silently promoting an account someone else registered would
25/// be a privilege escalation, so that conflict is resolved out-of-band.
26pub async fn ensure_admin(
27 tenants: &Tenants,
28 id: &SchoolId,
29 username: Username,
30 password: Password,
31) -> Result<(), AppError> {
32 let db = tenants.get(id).await?;
33 // The person half runs first, so the school row can carry the person id
34 // it is the join key to. Login reads the control-plane credential, so the
35 // seeded admin needs their `person` row and the membership too. Both
36 // writes are idempotent (create-or-load never re-keys an existing
37 // person's password; the membership insert is `ON CONFLICT DO NOTHING`),
38 // so every boot re-runs them — and a school whose seed predates the
39 // person half heals on the next boot instead of stranding an admin who
40 // cannot log in.
41 let password_hash = password.hash_async().await?;
42 let person =
43 crate::service::person::create_or_load(tenants.control(), username.clone(), password_hash)
44 .await?;
45 crate::service::person::link_school(tenants.control(), person.get_id(), id).await?;
46 match user::find_by_username(&db, username.as_str()).await? {
47 Some(user) if user.role == Role::Admin => {}
48 Some(_) => {
49 tracing::warn!(
50 "ADMIN_USERNAME names an existing non-admin account; refusing to promote it. \
51 Grant the role through an existing admin or a hand-run SQL session."
52 );
53 return Ok(());
54 }
55 // One statement, admin from birth. Never create-then-promote:
56 // an interruption between those two writes leaves a student row
57 // holding ADMIN_USERNAME, which the `Some(_)` arm above then
58 // refuses to promote — forever, on every subsequent boot. There
59 // is no marker that could tell such a row apart from a stranger
60 // who registered the name first, so the hole cannot be healed
61 // later; it has to be impossible to open.
62 None => {
63 user::create_with_role(&db, username, Some(*person.get_id()), Role::Admin, None)
64 .await?;
65 // No `username` field: with OTLP on every event is exported as a
66 // log record, so an account name here leaves the process.
67 tracing::info!("seeded the admin account named by ADMIN_USERNAME");
68 }
69 }
70 Ok(())
71}
72
73/// Overwrite this user's role **and** shed every grant the new role may not
74/// hold, in one transaction. The caller is responsible for authorizing it.
75///
76/// Refuses (`Conflict`) to lower the school's last admin, however the
77/// request is spelled and however many demotions are in flight at once.
78/// The floor is not a lock here — it is a predicate on the role write
79/// itself ([`user::set_role_cascade`]): the `UPDATE` that lowers the row
80/// carries `AND NOT (demoting the admin whom no other admin remains)`, so
81/// the count it reads and the write it guards are one statement, contended
82/// on row locks like any other write. Two admins demoting each other both
83/// used to count the other and both commit — the old store could not
84/// serialize a cross-record count against a concurrent update, which is
85/// what the process-wide lock used to stand in for. The database does that
86/// serialization now; zero rows out of the guarded write is the same 409
87/// the lock's check used to answer.
88///
89/// The sweep itself — what each role change owes, arm by arm, and why the
90/// conditions differ — is [`user::set_role_cascade`]'s statement list,
91/// documented there.
92pub async fn set_role(
93 db: &Database,
94 target: &UserId,
95 role: Role,
96) -> Result<(User, Vec<Board>), AppError> {
97 // A missing account is a 404, answered before the cascade opens a
98 // transaction. (No route deletes a user row, so the row cannot vanish
99 // between this read and the write.)
100 user::read(db, target).await?.ok_or(AppError::NotFound)?;
101 user::set_role_cascade(db, target, role).await
102}
103
104/// Register a new school account for `person` — the web layer's row mint.
105/// New users always start as [`Role::Student`]; elevation is a separate,
106/// admin-only action (see [`set_role`]).
107pub async fn create(
108 db: &Database,
109 username: Username,
110 person: Option<PersonId>,
111) -> Result<User, AppError> {
112 user::create(db, username, person).await
113}
114
115/// Mint a row holding `role` outright — the school-creation path, whose
116/// first account must be an admin from birth — optionally numbered
117/// (`student_number`; only a `student` row may carry one, the caller's check).
118pub async fn create_with_role(
119 db: &Database,
120 username: Username,
121 person: Option<PersonId>,
122 role: Role,
123 student_number: Option<StudentNumber>,
124) -> Result<User, AppError> {
125 user::create_with_role(db, username, person, role, student_number).await
126}
127
128/// One user row, for callers that only inspect it — the web layer's reads go
129/// through here.
130pub async fn read(db: &Database, id: &UserId) -> Result<Option<User>, AppError> {
131 user::read(db, id).await
132}
133
134/// Every account, newest first — or only the roles `roles` names, when the
135/// set is `Some` (the admin directory's tabs). The narrowing is the query's
136/// `WHERE`, so `total` counts the filtered set and paging stays inside it.
137pub async fn list_all(
138 db: &Database,
139 roles: Option<&[Role]>,
140 limit: Option<i64>,
141 offset: i64,
142) -> Result<(Vec<User>, i64), AppError> {
143 user::list_all(db, roles, limit, offset).await
144}
145
146/// The users behind `ids` in one query; missing ids simply absent.
147pub async fn list_by_ids(db: &Database, ids: &[UserId]) -> Result<Vec<User>, AppError> {
148 user::list_by_ids(db, ids).await
149}
150
151/// Username/name/surname fragment search — the pickers' backing read.
152pub async fn search(
153 db: &Database,
154 query: &str,
155 role: Option<Role>,
156 allowed_roles: Option<&[Role]>,
157 limit: Option<i64>,
158 offset: i64,
159) -> Result<(Vec<User>, i64), AppError> {
160 user::search(db, query, role, allowed_roles, limit, offset).await
161}
162
163/// The login lookup. Usernames are stored trimmed; callers trim the same way
164/// so a padded attempt matches the canonical name.
165pub async fn find_by_username(db: &Database, username: &str) -> Result<Option<User>, AppError> {
166 user::find_by_username(db, username).await
167}
168
169/// Persist the personal-info/profile fields a PATCH carried.
170// One argument per nullable column is the point: folding them into a struct
171// would just re-spell the HTTP DTO here and cost the compiler's check that
172// every column was considered at the call site.
173#[allow(clippy::too_many_arguments)]
174pub async fn set_profile(
175 db: &Database,
176 id: &UserId,
177 name: Option<Option<PersonName>>,
178 surname: Option<Option<PersonName>>,
179 email: Option<Option<Email>>,
180 phone: Option<Option<Phone>>,
181 birth_date: Option<Option<BirthDate>>,
182 display_name: Option<Option<DisplayName>>,
183 bio: Option<Option<Bio>>,
184 gender: Option<Option<Gender>>,
185 address: Option<Option<Address>>,
186 emergency_contact_name: Option<Option<PersonName>>,
187 emergency_contact_phone: Option<Option<Phone>>,
188 // The subject specialisation, clearable like `bio`; membership in the
189 // school's `Settings::get_branches()` list is the caller's check, not this
190 // one's.
191 branch: Option<Option<String>>,
192 // The school-issued student number, clearable like `bio`; *being a
193 // student* is the caller's check (it holds the row), and uniqueness is
194 // the partial index's, mapped to a 409 in [`crate::db::user`].
195 student_number: Option<Option<StudentNumber>>,
196) -> Result<User, AppError> {
197 user::set_profile(
198 db,
199 id,
200 name,
201 surname,
202 email,
203 phone,
204 birth_date,
205 display_name,
206 bio,
207 gender,
208 address,
209 emergency_contact_name,
210 emergency_contact_phone,
211 branch,
212 student_number,
213 )
214 .await
215}
216
217/// Persist an avatar upload, handing back the replaced blob's name.
218pub async fn set_avatar(
219 db: &Database,
220 id: &UserId,
221 file: &str,
222 content_type: &FileContentType,
223 size: i64,
224) -> Result<Option<User>, AppError> {
225 user::set_avatar(db, id, file, content_type, size).await
226}
227
228/// Clear the avatar, handing back the blob's name for deletion.
229pub async fn clear_avatar(db: &Database, id: &UserId) -> Result<Option<User>, AppError> {
230 user::clear_avatar(db, id).await
231}
232
233/// Persist the UI-preference fields a PATCH carried.
234pub async fn set_preferences(
235 db: &Database,
236 id: &UserId,
237 theme: Option<Option<Theme>>,
238 language: Option<Option<Language>>,
239 palette_color: Option<Option<PaletteColor>>,
240) -> Result<User, AppError> {
241 user::set_preferences(db, id, theme, language, palette_color).await
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247 use crate::database::{Database, init_test_db};
248
249 async fn a_user(username: &str, db: &Database) -> User {
250 user::create(db, Username::try_new(username).unwrap(), None)
251 .await
252 .unwrap()
253 }
254
255 /// The board result slot is an *index* into a batch whose length depends on
256 /// which arms the role selected, so it is the one number in the cascade a
257 /// silent mistake would not show up in the store: pointed at the wrong
258 /// statement it yields an empty list, and every whiteboard room whose roster
259 /// just changed is simply never told. Assert the rows come back.
260 #[tokio::test]
261 async fn the_cascade_returns_the_boards_it_stripped() {
262 use crate::domain::board::BoardTitle;
263
264 let (db, _leases) = init_test_db().await;
265 let creator = a_user("ogretmen", &db).await;
266 let guest = a_user("ogrenci", &db).await;
267 let board = crate::db::board::create(
268 &db,
269 creator.get_id(),
270 BoardTitle::try_new("Geometri").unwrap(),
271 vec![*guest.get_id()],
272 )
273 .await
274 .unwrap();
275
276 // A promotion touches no roster and must report none.
277 let (guest, boards) = set_role(&db, guest.get_id(), Role::Teacher).await.unwrap();
278 assert!(
279 boards.is_empty(),
280 "only a demotion to parent strips rosters"
281 );
282
283 let (_, boards) = set_role(&db, guest.get_id(), Role::Parent).await.unwrap();
284 assert_eq!(boards.len(), 1, "the stripped room must be reported back");
285 assert_eq!(boards[0].get_id(), board.get_id());
286 assert!(
287 boards[0].get_participants().is_empty(),
288 "and carry the roster the room is about to be told about"
289 );
290 }
291
292 /// The half the roster strip cannot reach: the board's **creator**. Demoted,
293 /// they are 404'd off their own room, every command on it is creator-only
294 /// for everyone else, and nothing in the crate lists a board a caller is not
295 /// on — so the room could be cleared, locked, closed and deleted by nobody
296 /// while its participants kept drawing on it. The demotion closes it, and
297 /// closing is *all* it does: the roster, the row and every mark stay
298 /// readable.
299 #[tokio::test]
300 async fn a_demoted_creator_s_board_is_closed_and_still_readable() {
301 use crate::domain::board::BoardTitle;
302 use crate::domain::board_stroke::BOARD_CLOSED;
303
304 let (db, _leases) = init_test_db().await;
305 let creator = a_user("ogretmen", &db).await;
306 let guest = a_user("ogrenci", &db).await;
307 let board = crate::db::board::create(
308 &db,
309 creator.get_id(),
310 BoardTitle::try_new("Geometri").unwrap(),
311 vec![*guest.get_id()],
312 )
313 .await
314 .unwrap();
315 let mark = |epoch| {
316 let (id, author, db) = (board.get_id().clone(), *guest.get_id(), db.clone());
317 async move { crate::db::board_stroke::append(&db, &id, &author, "{\"p\":[1]}", epoch).await }
318 };
319 mark(0).await.unwrap();
320
321 let (creator, boards) = set_role(&db, creator.get_id(), Role::Parent).await.unwrap();
322 assert_eq!(boards.len(), 1, "the room must be reported back");
323 let stamp = boards[0]
324 .get_closed_at()
325 .expect("and carry the closing stamp the room is told about");
326
327 // Stored, not merely reported — and nothing else moved.
328 let stored = crate::db::board::read(&db, board.get_id())
329 .await
330 .unwrap()
331 .unwrap();
332 assert_eq!(stored.get_closed_at(), Some(stamp));
333 assert_eq!(
334 stored.get_participants(),
335 [*guest.get_id()],
336 "closing must not empty the roster it did not touch"
337 );
338 assert_eq!(
339 crate::db::board_stroke::history(&db, board.get_id(), None, false, None, 0)
340 .await
341 .unwrap()
342 .1,
343 1,
344 "the marks the participants drew stay on disk"
345 );
346
347 // Read-only for the participants who are still on it.
348 assert!(
349 matches!(mark(0).await, Err(AppError::Conflict(BOARD_CLOSED))),
350 "a closed board must refuse every write with the terminal answer"
351 );
352
353 // The stamp is the record: a re-run of the sweep must not move it.
354 tokio::time::sleep(std::time::Duration::from_millis(2)).await;
355 set_role(&db, creator.get_id(), Role::Parent).await.unwrap();
356 assert_eq!(
357 crate::db::board::read(&db, board.get_id())
358 .await
359 .unwrap()
360 .unwrap()
361 .get_closed_at(),
362 Some(stamp),
363 "the close is a compare-and-set, not a re-stamp"
364 );
365 }
366
367 /// A demotion below `teacher` must take the published calendar with it and
368 /// settle the bookings on it. Nothing else can: a slot is listed only on its
369 /// own teacher's calendar (and hidden from every other reader once its owner
370 /// is demoted), deleted only by a teacher+, and a booking on one can be
371 /// decided only by a teacher+ and cancelled only by its requester — who is
372 /// refused the moment the window opens. So a slot left behind here is a row
373 /// no route can reach and a seat nothing can ever free.
374 #[tokio::test]
375 async fn a_demotion_withdraws_the_calendar_and_settles_its_bookings() {
376 use crate::domain::appointment::{AppointmentReason, AppointmentStatus};
377 use crate::domain::timestamp::Timestamp;
378 use crate::service::appointment;
379
380 let (db, _leases) = init_test_db().await;
381 let staff = |name: &'static str, db: Database| async move {
382 let teacher = a_user(name, &db).await;
383 set_role(&db, teacher.get_id(), Role::Teacher)
384 .await
385 .unwrap()
386 .0
387 };
388 let teacher = staff("ogretmen", db.clone()).await;
389 let other = staff("digerogretmen", db.clone()).await;
390 let student = a_user("ogrenci", &db).await;
391 let soon = |offset| Timestamp::from_millis(Timestamp::now().as_millis() + offset);
392 let reason = || AppointmentReason::try_new("görüşme").unwrap();
393 let slot = |owner: &User, offset: i64, db: Database| {
394 let owner = *owner.get_id();
395 async move {
396 crate::service::appointment_slot::create(
397 &db,
398 &owner,
399 soon(offset),
400 soon(offset + 60_000),
401 None,
402 )
403 .await
404 .unwrap()
405 }
406 };
407
408 let free = slot(&teacher, 60_000, db.clone()).await;
409 let asked = slot(&teacher, 180_000, db.clone()).await;
410 let agreed = slot(&teacher, 300_000, db.clone()).await;
411 let kept = slot(&other, 60_000, db.clone()).await;
412
413 let pending = appointment::book(&db, asked.get_id(), student.get_id(), reason())
414 .await
415 .unwrap();
416 let approved = appointment::book(&db, agreed.get_id(), student.get_id(), reason())
417 .await
418 .unwrap();
419 appointment::approve(&db, approved.get_id(), teacher.get_id())
420 .await
421 .unwrap();
422 let elsewhere = appointment::book(&db, kept.get_id(), student.get_id(), reason())
423 .await
424 .unwrap();
425
426 set_role(&db, teacher.get_id(), Role::Student)
427 .await
428 .unwrap();
429
430 // The calendar is gone, the booked weeks included.
431 assert!(
432 crate::service::appointment_slot::list_for_teacher(&db, teacher.get_id())
433 .await
434 .unwrap()
435 .is_empty()
436 );
437 for slot in [&free, &asked, &agreed] {
438 assert!(
439 crate::service::appointment_slot::read(&db, slot.get_id())
440 .await
441 .unwrap()
442 .is_none(),
443 "a slot only a teacher+ could reach outlived the role"
444 );
445 }
446 // Both bookings — the pending request and the confirmed meeting — ended
447 // in a state their requester can still read, saying who dropped it.
448 for booking in [&pending, &approved] {
449 let after = appointment::read(&db, booking.get_id())
450 .await
451 .unwrap()
452 .expect("the requester keeps the row");
453 assert_eq!(after.get_status(), AppointmentStatus::Cancelled);
454 assert_eq!(after.get_cancelled_by(), Some(teacher.get_id()));
455 assert!(after.get_cancel_reason().is_some(), "and why");
456 }
457 // The seat each held died with its slot row, so nothing is pinned: no
458 // live booking is left pointing at a slot that no longer exists.
459 // The slot is a foreign key now, so this reads as a structural fact:
460 // no live booking may point at a slot row that is gone.
461 let orphans: i64 = sqlx::query_scalar(
462 "SELECT count(*) FROM appointment a \
463 WHERE a.status IN ('pending', 'approved') \
464 AND NOT EXISTS (SELECT 1 FROM appointment_slot s WHERE s.id = a.slot)",
465 )
466 .fetch_one(&db)
467 .await
468 .unwrap();
469 assert_eq!(orphans, 0);
470
471 // Another teacher's calendar is nobody else's business.
472 assert_eq!(
473 crate::service::appointment_slot::list_for_teacher(&db, other.get_id())
474 .await
475 .unwrap()
476 .len(),
477 1
478 );
479 assert_eq!(
480 appointment::read(&db, elsewhere.get_id())
481 .await
482 .unwrap()
483 .unwrap()
484 .get_status(),
485 AppointmentStatus::Pending
486 );
487 }
488}