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

users.rs1691 lines, 75.0 KiBHistoryRawDownload
1use crate::web::tenant_state::{SchoolIdCookie, State};
2use axum::Json;
3use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
4use axum::http::StatusCode;
5use axum::response::Response;
6use serde::{Deserialize, Serialize};
7use serde_json::json;
8use utoipa::{IntoParams, ToSchema};
9use utoipa_axum::router::OpenApiRouter;
10use utoipa_axum::routes;
11
12use crate::constant::{
13 MAX_MAX_FILE_BYTES, MAX_PROFILE_CLASSES, MAX_PROFILE_COURSES, RESERVED_USERNAMES,
14 UPLOAD_BODY_OVERHEAD_BYTES,
15};
16use crate::database::Database;
17use crate::domain::badge::{self, BadgeAward};
18use crate::domain::class_group::ClassGroupId;
19
20use crate::domain::preferences::{Language, PaletteColor, Theme};
21use crate::domain::profile::{
22 Address, Bio, BirthDate, DisplayName, Email, Gender, PersonName, Phone, ProfileStats,
23};
24use crate::domain::role::Role;
25use crate::domain::user::{Password, StudentNumber, User, UserId, Username};
26use crate::error::{AppError, ErrorResponse, ValidationError};
27use crate::service::parent_link::ensure_can_observe;
28use crate::state::AppState;
29
30use super::courses::visible_courses;
31use super::dto::AssignableRole;
32use super::dto::Role as RoleSchema;
33use super::{
34 CurrentUser, Page, PageParams, PersonRef, RequireAdmin, UploadFileForm, UserResponse, paginate,
35 read_image_upload, remove_blob, serve_inline_blob, store_blob,
36};
37
38pub fn routes() -> OpenApiRouter<AppState> {
39 OpenApiRouter::new()
40 .routes(routes!(list_users, create_user))
41 .routes(routes!(update_my_profile))
42 .routes(routes!(update_my_preferences))
43 .routes(routes!(my_students))
44 .routes(routes!(my_profile))
45 .routes(routes!(search_users))
46 .routes(routes!(get_user))
47 .routes(routes!(set_role))
48 .routes(routes!(update_user_profile, get_user_profile))
49 .routes(routes!(update_user_preferences))
50 .routes(routes!(link_student, list_parent_students))
51 .routes(routes!(unlink_student))
52 // The avatar routes get their own HTTP body cap, like the note-file and
53 // question-image ones: the server-wide hard ceiling plus multipart
54 // framing headroom. It must stay on this sub-router — on the whole
55 // `/users` router every JSON endpoint would start accepting 25 MB.
56 .merge(
57 OpenApiRouter::new()
58 .routes(routes!(upload_my_avatar, get_my_avatar, delete_my_avatar))
59 .routes(routes!(get_avatar, delete_avatar))
60 .layer(DefaultBodyLimit::max(
61 MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES,
62 )),
63 )
64}
65
66#[derive(Deserialize, ToSchema)]
67struct SetRole {
68 /// The role to assign. Deserialized as a string so an unknown value returns a
69 /// uniform `400`; documented as the `AssignableRole` enum so the docs list
70 /// exactly the choices the server accepts (the response-side `Role` also
71 /// names the `ai` service principal, which this endpoint has always refused).
72 #[schema(value_type = AssignableRole, example = "teacher")]
73 role: String,
74}
75
76/// Partial personal-info update. Per field: omitted (or `null`) keeps the
77/// current value, an empty string clears it, anything else is validated and set.
78#[derive(Deserialize, ToSchema)]
79struct UpdateProfile {
80 #[schema(example = "Ada", max_length = 100)]
81 name: Option<String>,
82 #[schema(example = "Lovelace", max_length = 100)]
83 surname: Option<String>,
84 #[schema(example = "ada@example.com", max_length = 254)]
85 email: Option<String>,
86 /// Any punctuation and spacing; it is the digit count that must land in
87 /// `7`–`15`, so no character-length bound applies.
88 #[schema(example = "+90 555 123 45 67")]
89 phone: Option<String>,
90 /// Birth date in `YYYY-MM-DD` form.
91 #[schema(example = "1990-01-02")]
92 birth_date: Option<String>,
93 /// The name the public profile is shown under, instead of the legal one.
94 #[schema(example = "Ada", max_length = 50)]
95 display_name: Option<String>,
96 /// Free text under the profile's name.
97 #[schema(example = "Sınıfın en hızlı pomodorocusu.", max_length = 500)]
98 bio: Option<String>,
99 /// Self-declared gender: `female`, `male`, `other`, or `undisclosed`.
100 /// A closed vocabulary — anything else is a `400`.
101 #[schema(example = "female")]
102 gender: Option<String>,
103 /// Postal address, at most `max_address_len` characters (from `GET /limits`).
104 #[schema(example = "Çamlık Mah. 2. Sk. No: 7, Bornova / İzmir", max_length = 500)]
105 address: Option<String>,
106 /// Who to call when the person is unreachable. Same rules as `name`.
107 #[schema(example = "Mehmet Yılmaz", max_length = 100)]
108 emergency_contact_name: Option<String>,
109 /// The emergency contact's phone, same shape as `phone`.
110 #[schema(example = "+90 555 987 65 43")]
111 emergency_contact_phone: Option<String>,
112 /// The teacher's subject specialisation: one of the school's `branches` from
113 /// `GET /settings`, by name. Omit to keep the current value; send `""` to
114 /// clear it (a school that lists no subjects stores none).
115 #[schema(example = "Matematik", max_length = 50)]
116 branch: Option<String>,
117 /// The school-issued student number of the account being patched, unique
118 /// inside the school. Only a `student` account may hold one — naming one
119 /// for any other role, or naming a number another student already holds,
120 /// is refused. Omit to keep the current value; send `""` (or whitespace)
121 /// to clear it.
122 #[schema(example = "1234", max_length = 32)]
123 student_number: Option<String>,
124}
125
126/// Partial UI-preference update. Same field semantics as [`UpdateProfile`]:
127/// omitted (or `null`) keeps the current value, an empty string clears it back
128/// to "never chose" (the client then follows the device preference), anything
129/// else is validated and set.
130#[derive(Deserialize, ToSchema)]
131struct UpdatePreferences {
132 /// `light` or `dark`.
133 #[schema(example = "dark")]
134 theme: Option<String>,
135 /// `tr` or `en` (ISO 639-1).
136 #[schema(example = "tr")]
137 language: Option<String>,
138 /// Accent color as a 6-digit hex with a leading `#`; stored lowercase. Any
139 /// valid hex, not a fixed palette.
140 #[schema(example = "#fefae0")]
141 palette_color: Option<String>,
142}
143
144/// Resolve one patched field into what the save should write: absent (or
145/// `null`) is `None` — the column is not written at all, so a concurrent PATCH
146/// of it survives; `""` is `Some(None)`, an explicit clear; anything else must
147/// parse into the domain newtype, exactly as a create would.
148fn merge_field<T>(
149 patch: Option<&str>,
150 parse: impl Fn(&str) -> Result<T, ValidationError>,
151) -> Result<Option<Option<T>>, ValidationError> {
152 match patch {
153 None => Ok(None),
154 Some("") => Ok(Some(None)),
155 Some(value) => Ok(Some(Some(parse(value)?))),
156 }
157}
158
159/// Resolve the `branch` a request names. Same shape as [`merge_field`] — absent
160/// is "keep", `""` is an explicit clear — with the one check a free string
161/// cannot make: the value must be one the *school* lists (`GET /settings`).
162/// The vocabulary is the school's, so nothing else can decide it, and a school
163/// with no list can only ever have its `branch` cleared.
164fn merge_branch(
165 patch: Option<&str>,
166 allowed: &[String],
167) -> Result<Option<Option<String>>, ValidationError> {
168 match patch {
169 None => Ok(None),
170 Some("") => Ok(Some(None)),
171 Some(value) => {
172 if !allowed.iter().any(|name| name == value) {
173 return Err(ValidationError::Invalid {
174 field: "branch",
175 reason: "branch must be one of the school's configured branş list",
176 });
177 }
178 Ok(Some(Some(value.to_string())))
179 }
180 }
181}
182
183/// Resolve the `student_number` a request names. Same merge shape as
184/// [`merge_field`] — absent (or `null`) is "keep", blank is an explicit
185/// clear — plus the two checks a plain field does not carry:
186///
187/// * **The role gate.** A number names a student of this school, so only a
188/// `student` row may receive one; naming one for any other role is a 400,
189/// not a silent write the next role change would clear.
190/// * **The shape**, through [`StudentNumber`]: non-blank after trimming and
191/// within the published bound. Blank is a *clear* rather than a parse
192/// failure, so whitespace can never become a stored number — the same
193/// reading every other patchable field has.
194///
195/// `""` on a non-student stays a clear (a no-op: such a row never holds one),
196/// and a value that collides with another student's is the unique index's
197/// refusal — a 409 from the writer, never a pre-check that could race.
198fn merge_student_number(
199 patch: Option<&str>,
200 role: Role,
201) -> Result<Option<Option<StudentNumber>>, ValidationError> {
202 match patch {
203 None => Ok(None),
204 Some(raw) if raw.trim().is_empty() => Ok(Some(None)),
205 Some(raw) => {
206 if role != Role::Student {
207 return Err(StudentNumber::non_student_refusal());
208 }
209 Ok(Some(Some(StudentNumber::try_new(raw)?)))
210 }
211 }
212}
213
214/// Validate and persist exactly the info fields `req` carried — nothing is
215/// merged from `user`'s snapshot, so a concurrent PATCH of another field is not
216/// reverted. Shared by the self-service and admin profile endpoints — they
217/// differ only in whose row they load and who may call them.
218///
219/// `student_number` is resolved against the target's *live* role, read with the
220/// row we hold — so the role gate cannot be raced by a role change landing in
221/// between (a promotion that lands first makes this a 400; this write landing
222/// first leaves nothing behind, because the role write clears the number in the
223/// same statement).
224async fn apply_profile(
225 user: User,
226 req: &UpdateProfile,
227 db: &Database,
228) -> Result<UserResponse, AppError> {
229 let name = merge_field(req.name.as_deref(), |v| PersonName::try_new("name", v))?;
230 let surname = merge_field(req.surname.as_deref(), |v| {
231 PersonName::try_new("surname", v)
232 })?;
233 let email = merge_field(req.email.as_deref(), Email::try_new)?;
234 let phone = merge_field(req.phone.as_deref(), Phone::try_new)?;
235 let birth_date = merge_field(req.birth_date.as_deref(), BirthDate::try_new)?;
236 let display_name = merge_field(req.display_name.as_deref(), DisplayName::try_new)?;
237 let bio = merge_field(req.bio.as_deref(), Bio::try_new)?;
238 let gender = merge_field(req.gender.as_deref(), Gender::try_from_str)?;
239 let address = merge_field(req.address.as_deref(), Address::try_new)?;
240 let emergency_contact_name = merge_field(req.emergency_contact_name.as_deref(), |v| {
241 PersonName::try_new("emergency_contact_name", v)
242 })?;
243 let emergency_contact_phone =
244 merge_field(req.emergency_contact_phone.as_deref(), Phone::try_new)?;
245 let student_number = merge_student_number(req.student_number.as_deref(), user.get_role())?;
246 // Only a request that actually names a branch pays the settings read.
247 let branch = match req.branch {
248 Some(_) => {
249 let school = crate::service::settings::load(db).await?;
250 merge_branch(req.branch.as_deref(), &school.get_branches())?
251 }
252 None => None,
253 };
254 let updated = crate::service::user::set_profile(
255 db,
256 user.get_id(),
257 name,
258 surname,
259 email,
260 phone,
261 birth_date,
262 display_name,
263 bio,
264 gender,
265 address,
266 emergency_contact_name,
267 emergency_contact_phone,
268 branch,
269 student_number,
270 )
271 .await?;
272 Ok(UserResponse::new(&updated))
273}
274
275/// Validate and persist exactly the preference fields `req` carried — same
276/// no-merge reasoning as [`apply_profile`]. Shared by the
277/// self-service and admin preference endpoints — they differ only in whose row
278/// they load and who may call them.
279async fn apply_preferences(
280 user: User,
281 req: &UpdatePreferences,
282 db: &Database,
283) -> Result<UserResponse, AppError> {
284 let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?;
285 let language = merge_field(req.language.as_deref(), Language::try_from_str)?;
286 let palette_color = merge_field(req.palette_color.as_deref(), PaletteColor::try_from_str)?;
287 let updated =
288 crate::service::user::set_preferences(db, user.get_id(), theme, language, palette_color)
289 .await?;
290 Ok(UserResponse::new(&updated))
291}
292
293#[derive(Deserialize, IntoParams)]
294struct SearchUsers {
295 /// Case-insensitive fragment of a username, name, or surname. Omit it —
296 /// or leave it blank — to list everyone the caller may see, optionally
297 /// narrowed by `role`.
298 q: Option<String>,
299 /// Restrict matches to one role: `parent`, `student`, `teacher`,
300 /// `manager`, or `admin`. Omit to search every role.
301 role: Option<String>,
302 /// Max matches to return. Omit for every match; when given, `1`–`500`.
303 #[param(minimum = 1, maximum = 500, example = 100)]
304 limit: Option<i64>,
305 /// Matches to skip from the start. Defaults to `0`.
306 #[param(minimum = 0, example = 0)]
307 offset: Option<i64>,
308}
309
310/// Find users by username or name — backs the pickers (enroll, grade, mark
311/// attendance) and, for a student or parent, the one way to find the staff
312/// member they are allowed to message. Any authenticated user may ask; a
313/// caller below teacher only ever sees the roles they may message (teacher,
314/// manager, admin), in the items *and* in `total`. A blank or omitted `q`
315/// lists everyone the caller may see — what the pickers open with; `role`
316/// narrows to one role (e.g. `role=student` for an enroll picker), and a
317/// student or parent naming a role they may not message is refused. Paged
318/// via `?limit=&offset=` like the other lists (omit `limit` for every
319/// match); returns a `{items, total, limit, offset}` envelope carrying only
320/// id/username/display name and the student number — no contact details.
321#[utoipa::path(
322 get,
323 path = "/search",
324 tag = "users",
325 security(("session_cookie" = [])),
326 params(SearchUsers),
327 responses(
328 (status = 200, description = "A page of matching users (all matches when unpaged)", body = Page<PersonRef>),
329 (status = 400, description = "Unknown role, or invalid limit/offset", body = ErrorResponse),
330 (status = 401, description = "Not authenticated", body = ErrorResponse),
331 (status = 403, description = "A student or parent asked for a role they may not message", body = ErrorResponse),
332 ),
333)]
334async fn search_users(
335 State(st): State<AppState>,
336 CurrentUser(user): CurrentUser,
337 Query(req): Query<SearchUsers>,
338) -> Result<Json<Page<PersonRef>>, AppError> {
339 let (limit, offset) = PageParams {
340 limit: req.limit,
341 offset: req.offset,
342 }
343 .resolve()?;
344 let role = req.role.as_deref().map(Role::try_from_str).transpose()?;
345 // Below staff the caller may only see whom they may write to. Asking for a
346 // role outside that set is a refusal, not a silently empty page.
347 let allowed = user.get_role().messageable_roles();
348 if let (Some(allowed), Some(role)) = (allowed, role)
349 && !allowed.contains(&role)
350 {
351 return Err(AppError::Forbidden(
352 "students and parents may only search staff (teacher or higher)",
353 ));
354 }
355 let (users, total) = crate::service::user::search(
356 &st.db,
357 req.q.as_deref().unwrap_or(""),
358 role,
359 allowed,
360 limit,
361 offset,
362 )
363 .await?;
364 let items = users.iter().map(PersonRef::new).collect();
365 Ok(Json(Page::new(items, total, limit, offset)))
366}
367
368/// The admin directory's optional `roles` narrowing: a comma-separated list
369/// of role names, e.g. `roles=manager,admin` for the two staff tabs in one
370/// read. Absent (`None`) is every user — today's response, unchanged.
371#[derive(Debug, Deserialize, IntoParams)]
372struct ListUsersFilter {
373 /// Keep only users whose role is in this comma-separated set: `student`,
374 /// `parent`, `teacher`, `manager`, or `admin` (an OR, not an AND). Omit
375 /// to list every role.
376 roles: Option<String>,
377}
378
379impl ListUsersFilter {
380 /// Resolve `roles` into the filter set. Each token is trimmed, then
381 /// parsed with [`Role::try_from_str`] — the same vocabulary
382 /// `GET /users/search` parses `role` with. An empty value (`?roles=`), a
383 /// blank token (`roles=manager,`), or an unknown name is a `400` naming
384 /// `roles` — the same refusal shape every other closed set answers with,
385 /// never a silently empty page.
386 fn resolve(&self) -> Result<Option<Vec<Role>>, ValidationError> {
387 let Some(raw) = self.roles.as_deref() else {
388 return Ok(None);
389 };
390 raw.split(',')
391 .map(|token| {
392 Role::try_from_str(token.trim()).map_err(|err| match err {
393 // The parser names its field `role`; this param is the
394 // plural `roles`, so the refusal must name what the
395 // request actually carried.
396 ValidationError::Invalid { reason, .. } => ValidationError::Invalid {
397 field: "roles",
398 reason,
399 },
400 err => err,
401 })
402 })
403 .collect::<Result<Vec<_>, _>>()
404 .map(Some)
405 }
406}
407
408/// List every user with their role, newest first. Admin only. Paged: pass
409/// `?limit=&offset=` to take a window (omit `limit` for the whole list); the
410/// response is a `{items, total, limit, offset}` envelope where `total` counts
411/// every user.
412///
413/// The optional `roles` parameter narrows the directory to a set of roles —
414/// a comma-separated list (`roles=manager,admin` is the two staff tabs in
415/// one read, an OR). Omitted, the response is the whole roster. The window
416/// and `total` are taken after the narrowing, so `total` counts the filtered
417/// set and paging stays inside it. Each name is the vocabulary
418/// `GET /users/search` parses; an unknown name, a blank value, or a blank
419/// token is a `400` naming `roles`.
420#[utoipa::path(
421 get,
422 path = "/",
423 tag = "users",
424 security(("session_cookie" = [])),
425 params(PageParams, ListUsersFilter),
426 responses(
427 (status = 200, description = "A page of users (the full list when unpaged)", body = Page<UserResponse>),
428 (status = 400, description = "Invalid limit or offset, or an unknown `roles` entry", body = ErrorResponse),
429 (status = 401, description = "Not authenticated", body = ErrorResponse),
430 (status = 403, description = "Requires admin role", body = ErrorResponse),
431 ),
432)]
433async fn list_users(
434 State(st): State<AppState>,
435 _admin: RequireAdmin,
436 Query(page): Query<PageParams>,
437 Query(filter): Query<ListUsersFilter>,
438) -> Result<Json<Page<UserResponse>>, AppError> {
439 let (limit, offset) = page.resolve()?;
440 let roles = filter.resolve()?;
441 let (users, total) =
442 crate::service::user::list_all(&st.db, roles.as_deref(), limit, offset).await?;
443 let items = users.iter().map(UserResponse::new).collect();
444 Ok(Json(Page::new(items, total, limit, offset)))
445}
446
447#[derive(Deserialize, ToSchema)]
448struct CreateUser {
449 /// The new account's username — a global credential, exactly as at
450 /// `POST /auth/register`.
451 #[schema(example = "ada", min_length = 3, max_length = 32)]
452 username: String,
453 #[schema(example = "correct horse battery", min_length = 6, max_length = 128)]
454 password: String,
455 /// The role the account is born with. Omitted → `student`.
456 #[schema(example = "teacher")]
457 role: Option<String>,
458 /// The school-issued student number, unique inside the school. Only a
459 /// `student` account may hold one — naming one while creating any other
460 /// role is a `400`, and a number another student already holds is a `409`.
461 /// Omit to create the account unnumbered; blank is the same as omitted.
462 #[schema(example = "1234", max_length = 32)]
463 student_number: Option<String>,
464}
465
466/// Create a school account directly — the school-office path for adding a
467/// student or a staff member with no self-registration and no invite. Admin
468/// only. `{username, password}` are required and `role` is optional (omitted →
469/// `student`); the row is born with its role rather than promoted into it, so
470/// a new teacher is never briefly a student. `student_number` numbers a new
471/// student at mint time — a `409` when another student in this school already
472/// holds it, a `400` on a non-student role. The username is a global
473/// **person** credential exactly as at `POST /auth/register`: a name new
474/// everywhere creates the person and this school's `app_user`, while a person
475/// who already exists is attached to this school only when the password
476/// matches the stored credential — a mismatch is a `409`. A username already
477/// taken in this school is a `409`, and the reserved staff-reading names
478/// (`admin`, `root`, …) are a `400`, the same policy registration holds.
479#[utoipa::path(
480 post,
481 path = "/",
482 tag = "users",
483 security(("session_cookie" = [])),
484 request_body = CreateUser,
485 responses(
486 (status = 201, description = "Account created, holding the requested role", body = UserResponse),
487 (status = 400, description = "Invalid username or password (a reserved username included), an unknown role, or a student number on a non-student role", body = ErrorResponse),
488 (status = 401, description = "Not authenticated", body = ErrorResponse),
489 (status = 403, description = "Requires admin role", body = ErrorResponse),
490 (status = 409, description = "The username is taken in this school, that person exists under a different password, or the student number is already taken (`code: student_number_taken`)", body = ErrorResponse),
491 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
492 ),
493)]
494async fn create_user(
495 State(st): State<AppState>,
496 SchoolIdCookie(school): SchoolIdCookie,
497 _admin: RequireAdmin,
498 Json(req): Json<CreateUser>,
499) -> Result<(StatusCode, Json<UserResponse>), AppError> {
500 let username = Username::try_new(&req.username)?;
501 // The same policy `POST /auth/register` enforces: these names read as
502 // staff and invite impersonation, so no minting route may claim them. The
503 // `ADMIN_USERNAME` bootstrap does not come through here.
504 if RESERVED_USERNAMES.contains(&username.as_str()) {
505 return Err(ValidationError::Invalid {
506 field: "username",
507 reason: "this username is reserved",
508 }
509 .into());
510 }
511 let role = match req.role.as_deref() {
512 Some(raw) => Role::try_from_str(raw)?,
513 None => Role::Student,
514 };
515 // The number is validated against the role the row is being born with
516 // (the same gate the profile writer applies), then bound into the mint —
517 // one statement, so a refused number leaves no half-created account.
518 let student_number = merge_student_number(req.student_number.as_deref(), role)?.flatten();
519 let password = Password::try_new(&req.password)?;
520 let password_hash = password.hash_async().await?;
521
522 // Person half (control database): create the global account, or meet the
523 // one already standing — the credential login verifies, exactly as the
524 // register and school-create paths treat it. The stored hash is never
525 // rewritten here; the caller must prove they know it below.
526 let control = st.tenants.control();
527 let person =
528 crate::service::person::create_or_load(control, username.clone(), password_hash).await?;
529 if !person.get_password_hash().verify_async(&password).await {
530 return Err(AppError::Conflict(
531 "an account with that username exists under a different password",
532 ));
533 }
534
535 // School half, born with its role: a fresh row holds no enrollments or
536 // teaching assignments for a later promotion to sweep. A username already
537 // taken in this school refuses here, before the membership is written, and
538 // so does a student number another student already holds.
539 let user = crate::service::user::create_with_role(
540 &st.db,
541 username,
542 Some(*person.get_id()),
543 role,
544 student_number,
545 )
546 .await?;
547 crate::service::person::link_school(control, person.get_id(), &school).await?;
548 Ok((StatusCode::CREATED, Json(UserResponse::new(&user))))
549}
550
551/// Update the caller's own personal info: name, surname, email, phone, birth
552/// date, plus the public-profile pair `display_name` and `bio` (both readable
553/// school-wide at `GET /users/{id}/profile`, unlike the contact fields). Any
554/// authenticated role. Omitted fields stay as they are; an empty string clears
555/// a field. `student_number` follows the same merge semantics, with two
556/// refusals of its own: naming one while the account is not a `student` is a
557/// `400`, and a number another student in this school already holds is a `409`
558/// (`code: student_number_taken`).
559#[utoipa::path(
560 patch,
561 path = "/me",
562 tag = "users",
563 security(("session_cookie" = [])),
564 request_body = UpdateProfile,
565 responses(
566 (status = 200, description = "Updated user", body = UserResponse),
567 (status = 400, description = "Invalid field, or a student number on a non-student account", body = ErrorResponse),
568 (status = 401, description = "Not authenticated", body = ErrorResponse),
569 (status = 409, description = "The student number is already taken (`code: student_number_taken`)", body = ErrorResponse),
570 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
571 ),
572)]
573async fn update_my_profile(
574 State(st): State<AppState>,
575 CurrentUser(user): CurrentUser,
576 Json(req): Json<UpdateProfile>,
577) -> Result<Json<UserResponse>, AppError> {
578 Ok(Json(apply_profile(user, &req, &st.db).await?))
579}
580
581/// Update the caller's own UI preferences: `theme` (`light`/`dark`),
582/// `language` (`tr`/`en`), and `palette_color` (accent color as `#rrggbb`).
583/// Any authenticated role. Omitted fields stay as they
584/// are; an empty string clears one back to "never chose" (the client then
585/// follows the device preference). Read them back on any user response, e.g.
586/// `GET /auth/me`.
587#[utoipa::path(
588 patch,
589 path = "/me/preferences",
590 tag = "users",
591 security(("session_cookie" = [])),
592 request_body = UpdatePreferences,
593 responses(
594 (status = 200, description = "Updated user", body = UserResponse),
595 (status = 400, description = "Invalid theme, language, or palette color", body = ErrorResponse),
596 (status = 401, description = "Not authenticated", body = ErrorResponse),
597 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
598 ),
599)]
600async fn update_my_preferences(
601 State(st): State<AppState>,
602 CurrentUser(user): CurrentUser,
603 Json(req): Json<UpdatePreferences>,
604) -> Result<Json<UserResponse>, AppError> {
605 Ok(Json(apply_preferences(user, &req, &st.db).await?))
606}
607
608/// Fetch one user with their role and personal info. Admin only.
609#[utoipa::path(
610 get,
611 path = "/{id}",
612 tag = "users",
613 security(("session_cookie" = [])),
614 params(("id" = String, Path, description = "User id")),
615 responses(
616 (status = 200, description = "The user", body = UserResponse),
617 (status = 401, description = "Not authenticated", body = ErrorResponse),
618 (status = 403, description = "Requires admin role", body = ErrorResponse),
619 (status = 404, description = "User not found", body = ErrorResponse),
620 ),
621)]
622async fn get_user(
623 State(st): State<AppState>,
624 _admin: RequireAdmin,
625 Path(id): Path<String>,
626) -> Result<Json<UserResponse>, AppError> {
627 let user = crate::service::user::read(&st.db, &UserId::from_key(&id))
628 .await?
629 .ok_or(AppError::NotFound)?;
630 Ok(Json(UserResponse::new(&user)))
631}
632
633/// Update any user's personal info. Admin only — the school-office path for
634/// maintaining records on behalf of students and staff. Same field semantics
635/// as `PATCH /users/me`, `student_number` included: the number belongs to the
636/// student identity the office maintains, so this is the door that issues it —
637/// a `400` when the target is not a `student`, a `409`
638/// (`code: student_number_taken`) when another student in this school already
639/// holds it. A role change away from `student` clears it on its own
640/// (`PATCH /users/{id}/role`), which is also the answer to "this account is no
641/// longer a student".
642#[utoipa::path(
643 patch,
644 path = "/{id}/profile",
645 tag = "users",
646 security(("session_cookie" = [])),
647 params(("id" = String, Path, description = "User id")),
648 request_body = UpdateProfile,
649 responses(
650 (status = 200, description = "Updated user", body = UserResponse),
651 (status = 400, description = "Invalid field, or a student number on a non-student account", body = ErrorResponse),
652 (status = 401, description = "Not authenticated", body = ErrorResponse),
653 (status = 403, description = "Requires admin role", body = ErrorResponse),
654 (status = 404, description = "User not found", body = ErrorResponse),
655 (status = 409, description = "The student number is already taken (`code: student_number_taken`)", body = ErrorResponse),
656 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
657 ),
658)]
659async fn update_user_profile(
660 State(st): State<AppState>,
661 _admin: RequireAdmin,
662 Path(id): Path<String>,
663 Json(req): Json<UpdateProfile>,
664) -> Result<Json<UserResponse>, AppError> {
665 let user = crate::service::user::read(&st.db, &UserId::from_key(&id))
666 .await?
667 .ok_or(AppError::NotFound)?;
668 Ok(Json(apply_profile(user, &req, &st.db).await?))
669}
670
671/// Update any user's UI preferences. Admin only — everyone else manages their
672/// own through `PATCH /users/me/preferences`, which this mirrors field for
673/// field.
674#[utoipa::path(
675 patch,
676 path = "/{id}/preferences",
677 tag = "users",
678 security(("session_cookie" = [])),
679 params(("id" = String, Path, description = "User id")),
680 request_body = UpdatePreferences,
681 responses(
682 (status = 200, description = "Updated user", body = UserResponse),
683 (status = 400, description = "Invalid theme, language, or palette color", body = ErrorResponse),
684 (status = 401, description = "Not authenticated", body = ErrorResponse),
685 (status = 403, description = "Requires admin role", body = ErrorResponse),
686 (status = 404, description = "User not found", body = ErrorResponse),
687 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
688 ),
689)]
690async fn update_user_preferences(
691 State(st): State<AppState>,
692 _admin: RequireAdmin,
693 Path(id): Path<String>,
694 Json(req): Json<UpdatePreferences>,
695) -> Result<Json<UserResponse>, AppError> {
696 let user = crate::service::user::read(&st.db, &UserId::from_key(&id))
697 .await?
698 .ok_or(AppError::NotFound)?;
699 Ok(Json(apply_preferences(user, &req, &st.db).await?))
700}
701
702/// Set a user's role. Admin only. An admin cannot change their own role, and
703/// the school's **last** admin cannot be demoted by anyone (`409`) — together
704/// those keep role management from locking everyone out, including when two
705/// admins demote each other at the same instant (the floor is a predicate on
706/// the role write itself, so the racing demotions serialize on row locks).
707/// A school that has already lost its admins is recovered by hand against the
708/// database, since the seed never promotes.
709/// Setting any non-`student` role also drops the user's course enrollments —
710/// only students enroll, so a promoted user leaves every roster — and clears
711/// the account's student number in the same transaction: the number names a
712/// student of this school, so no window exists where a promoted account still
713/// holds one. Demoting below
714/// `teacher` drops their course teaching assignments for the mirror reason, and
715/// withdraws their published appointment slots, cancelling the live bookings on
716/// them: nothing could reach either afterwards — a slot is listed only on its
717/// own teacher's calendar and deleted only by a teacher+, and a booking on one
718/// is decided only by a teacher+ and cancelled only by its requester, who is
719/// refused once the window opens. The requester keeps the booking as
720/// `cancelled`, naming the ex-teacher and the reason.
721/// Demoting to `parent` additionally gives back the seats they hold on
722/// still-open event signup lists: a parent can no longer free them, and nobody
723/// else may. Seats on lists that have already closed stay as they are — that
724/// roster is history. It also takes the account off every whiteboard roster and
725/// **closes every board it created** — permanently read-only, nothing deleted.
726/// A demoted creator is a `404` on their own board, the four commands that could
727/// end it are the creator's alone, and no route lists a board the caller is not
728/// on, so the room would otherwise be commandable by nobody while its
729/// participants kept drawing on it. Closed, they keep reading the board, its
730/// history and its epochs; only writes are refused.
731#[utoipa::path(
732 patch,
733 path = "/{id}/role",
734 tag = "users",
735 security(("session_cookie" = [])),
736 params(("id" = String, Path, description = "User id")),
737 request_body = SetRole,
738 responses(
739 (status = 200, description = "Updated user", body = UserResponse),
740 (status = 400, description = "Invalid role", body = ErrorResponse),
741 (status = 401, description = "Not authenticated", body = ErrorResponse),
742 (status = 403, description = "Requires admin, or attempted to change own role", body = ErrorResponse),
743 (status = 404, description = "User not found", body = ErrorResponse),
744 (status = 409, description = "That account is the school's last admin", body = ErrorResponse),
745 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
746 ),
747)]
748async fn set_role(
749 State(st): State<AppState>,
750 SchoolIdCookie(school): SchoolIdCookie,
751 RequireAdmin(admin): RequireAdmin,
752 Path(id): Path<String>,
753 Json(req): Json<SetRole>,
754) -> Result<Json<UserResponse>, AppError> {
755 let role = Role::try_from_str(&req.role)?;
756 let target = UserId::from_key(&id);
757 if &target == admin.get_id() {
758 return Err(AppError::Forbidden("cannot change your own role"));
759 }
760 // The role write and every sweep it owes commit together
761 // ([`crate::service::user::set_role`] carries the whole list and the
762 // reasoning behind each arm). The write ordering *within* a request is
763 // closed from the other end: a handler that assigns a teacher-only role
764 // re-reads the live role after its write ([`super::undo_if_demoted`]), so
765 // a demotion racing an assignment is caught by whichever side is second.
766 let (updated, boards) = crate::service::user::set_role(&st.db, &target, role).await?;
767 // Whiteboard rooms the commit above changed, prompted with the same frames
768 // their own routes publish — after the commit, because the room re-reads the
769 // database before it acts on a frame. A room whose creator was demoted is
770 // now closed, and its `closed` frame is what turns the open sockets
771 // read-only; told only about the roster, they would draw on until each
772 // stroke came back refused.
773 for board in boards {
774 st.board_hub.publish(
775 &school,
776 board.get_id().key().as_str(),
777 json!({
778 "type": "participants",
779 "creator": board.get_creator().key(),
780 "participants": board
781 .get_participants()
782 .iter()
783 .map(|user| user.key())
784 .collect::<Vec<_>>(),
785 })
786 .to_string(),
787 );
788 if let Some(closed_at) = board.get_closed_at() {
789 st.board_hub.publish(
790 &school,
791 board.get_id().key().as_str(),
792 json!({"type": "closed", "closed_at": closed_at.as_millis()}).to_string(),
793 );
794 }
795 }
796 Ok(Json(UserResponse::new(&updated)))
797}
798
799#[derive(Deserialize, ToSchema)]
800struct LinkStudent {
801 /// The student to tie to this parent.
802 user_id: String,
803}
804
805#[derive(Serialize, ToSchema)]
806struct ParentLinkResponse {
807 parent: PersonRef,
808 student: PersonRef,
809 /// The admin who created the tie.
810 linked_by: PersonRef,
811}
812
813/// One page of a parent's observed students, sorted by username. Shared by the
814/// admin listing and the parent's own `/me/students` — they differ only in
815/// whose links they read and who may call them.
816async fn students_page(
817 parent: &UserId,
818 page: PageParams,
819 db: &Database,
820) -> Result<Page<PersonRef>, AppError> {
821 let (limit, offset) = page.resolve()?;
822 let links = crate::service::parent_link::list_for_parent(db, parent).await?;
823 let ids: Vec<UserId> = links.iter().map(|link| *link.get_student()).collect();
824 let mut students = crate::service::user::list_by_ids(db, &ids).await?;
825 // The link row alone is not the grant, exactly as [`ensure_can_observe`]
826 // says: a link whose student side changed role (a sweep lost a race with
827 // `link_student`) is inert everywhere else, so it must not name a person
828 // here either. Filtered at read time rather than swept, which also makes
829 // any such row already on disk inert without a migration.
830 students.retain(|student| student.get_role() == Role::Student);
831 students.sort_by(|a, b| a.get_username().as_str().cmp(b.get_username().as_str()));
832 let total = students.len() as i64;
833 // Paged in the web layer: the rows come from a link table and are
834 // re-sorted by username in Rust.
835 let items = paginate(&students, limit, offset)
836 .iter()
837 .map(PersonRef::new)
838 .collect();
839 Ok(Page::new(items, total, limit, offset))
840}
841
842/// Tie a student to a parent account. Admin only — family ties are school-office
843/// records, like roles. `{id}` must hold the `parent` role and `user_id` the
844/// `student` role; a parent may observe any number of students. Idempotent:
845/// linking the same pair again keeps the one tie (the `linked_by` stamp moves
846/// to the latest linker, like re-enrolling). The tie grants the
847/// parent read access to the student's marks, attendance, and pomodoro reports
848/// — nothing else, and never any write.
849#[utoipa::path(
850 post,
851 path = "/{id}/students",
852 tag = "users",
853 security(("session_cookie" = [])),
854 params(("id" = String, Path, description = "Parent user id")),
855 request_body = LinkStudent,
856 responses(
857 (status = 200, description = "The tie (created or already present)", body = ParentLinkResponse),
858 (status = 400, description = "The target is not a parent, or user_id is unknown or not a student", body = ErrorResponse),
859 (status = 401, description = "Not authenticated", body = ErrorResponse),
860 (status = 403, description = "Requires admin role", body = ErrorResponse),
861 (status = 404, description = "Parent user not found", body = ErrorResponse),
862 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
863 ),
864)]
865async fn link_student(
866 State(st): State<AppState>,
867 RequireAdmin(admin): RequireAdmin,
868 Path(id): Path<String>,
869 Json(req): Json<LinkStudent>,
870) -> Result<Json<ParentLinkResponse>, AppError> {
871 let (link, parent, student) = crate::service::parent_link::link(
872 &st.db,
873 &UserId::from_key(&id),
874 &UserId::from_key(&req.user_id),
875 admin.get_id(),
876 )
877 .await?;
878 let people = PersonRef::map_of(&[&parent, &student, &admin]);
879 Ok(Json(ParentLinkResponse {
880 parent: PersonRef::resolve(&people, link.get_parent()),
881 student: PersonRef::resolve(&people, link.get_student()),
882 linked_by: PersonRef::resolve(&people, link.get_linked_by()),
883 }))
884}
885
886/// List the students tied to a parent account, sorted by username. Admin only
887/// — parents read their own list at `GET /users/me/students`. Paged via
888/// `?limit=&offset=` like the other lists.
889#[utoipa::path(
890 get,
891 path = "/{id}/students",
892 tag = "users",
893 security(("session_cookie" = [])),
894 params(("id" = String, Path, description = "Parent user id"), PageParams),
895 responses(
896 (status = 200, description = "A page of the parent's students", body = Page<PersonRef>),
897 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
898 (status = 401, description = "Not authenticated", body = ErrorResponse),
899 (status = 403, description = "Requires admin role", body = ErrorResponse),
900 (status = 404, description = "User not found", body = ErrorResponse),
901 ),
902)]
903async fn list_parent_students(
904 State(st): State<AppState>,
905 _admin: RequireAdmin,
906 Path(id): Path<String>,
907 Query(page): Query<PageParams>,
908) -> Result<Json<Page<PersonRef>>, AppError> {
909 let parent = UserId::from_key(&id);
910 crate::service::user::read(&st.db, &parent)
911 .await?
912 .ok_or(AppError::NotFound)?;
913 Ok(Json(students_page(&parent, page, &st.db).await?))
914}
915
916/// Untie a student from a parent account. Admin only. The student's data is
917/// untouched — only the parent's read grant goes away.
918#[utoipa::path(
919 delete,
920 path = "/{id}/students/{student}",
921 tag = "users",
922 security(("session_cookie" = [])),
923 params(
924 ("id" = String, Path, description = "Parent user id"),
925 ("student" = String, Path, description = "Student user id"),
926 ),
927 responses(
928 (status = 204, description = "Tie removed"),
929 (status = 401, description = "Not authenticated", body = ErrorResponse),
930 (status = 403, description = "Requires admin role", body = ErrorResponse),
931 (status = 404, description = "No such tie", body = ErrorResponse),
932 ),
933)]
934async fn unlink_student(
935 State(st): State<AppState>,
936 _admin: RequireAdmin,
937 Path((id, student)): Path<(String, String)>,
938) -> Result<StatusCode, AppError> {
939 if crate::service::parent_link::remove(
940 &st.db,
941 &UserId::from_key(&id),
942 &UserId::from_key(&student),
943 )
944 .await?
945 .is_none()
946 {
947 return Err(AppError::NotFound);
948 }
949 Ok(StatusCode::NO_CONTENT)
950}
951
952/// The students the calling parent observes, sorted by username. Requires the
953/// `parent` role. Each entry's reports live at `GET /marks/{user}`,
954/// `GET /attendance/{user}`, and `GET /pomodoro/{user}`. Paged via
955/// `?limit=&offset=`.
956#[utoipa::path(
957 get,
958 path = "/me/students",
959 tag = "users",
960 security(("session_cookie" = [])),
961 params(PageParams),
962 responses(
963 (status = 200, description = "A page of the caller's students", body = Page<PersonRef>),
964 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
965 (status = 401, description = "Not authenticated", body = ErrorResponse),
966 (status = 403, description = "Requires the parent role", body = ErrorResponse),
967 ),
968)]
969async fn my_students(
970 State(st): State<AppState>,
971 CurrentUser(user): CurrentUser,
972 Query(page): Query<PageParams>,
973) -> Result<Json<Page<PersonRef>>, AppError> {
974 if user.get_role() != Role::Parent {
975 return Err(AppError::Forbidden("requires the parent role"));
976 }
977 Ok(Json(students_page(user.get_id(), page, &st.db).await?))
978}
979
980// ---- the public profile -----------------------------------------------------
981// The school-wide read half of a user row: who they are, what they belong to,
982// and the counters that motivate. Deliberately *not* `UserResponse` — that one
983// carries email, phone, and birth date, which keep exactly the gate they have
984// today (self, teacher+, admin). Nothing here widens where they are reachable.
985//
986// The student number is deliberately on `UserResponse` (and `PersonRef`) and
987// *not* here: it is the school office's identifier for a student, readable
988// wherever the reader is already looking at student identity — the admin user
989// surfaces, the pickers, a parent's own children's roster — while this profile
990// is readable by every authenticated account school-wide. A number is not a
991// secret, but broadcasting one to the whole school is a widening nobody asked
992// for.
993
994/// A user's public profile. Contact details are not part of it, at any role.
995#[derive(Serialize, ToSchema)]
996struct ProfileResponse {
997 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
998 id: String,
999 #[schema(example = "ada")]
1000 username: String,
1001 /// The self-chosen `display_name`, falling back to `"Name Surname"`, then
1002 /// `null` when the row carries neither.
1003 #[schema(example = "Ada Lovelace")]
1004 display_name: Option<String>,
1005 role: RoleSchema,
1006 #[schema(example = "Sınıfın en hızlı pomodorocusu.")]
1007 bio: Option<String>,
1008 /// The teacher's subject specialisation, one of the school's `branches`
1009 /// (`GET /settings`); `null` when none is set — or when the school lists none.
1010 #[schema(example = "Matematik")]
1011 branch: Option<String>,
1012 /// Present only once a picture is uploaded; the bytes are at
1013 /// `GET /users/{id}/avatar`.
1014 avatar: Option<ProfileAvatar>,
1015 /// At most `max_profile_classes` sections — the full list is at
1016 /// `GET /classes/me`.
1017 classes: Vec<ProfileClassRef>,
1018 /// At most `max_profile_courses` **sections** the person is reached by —
1019 /// `GET /instances/me`'s set unioned with their own enrollment rows — each
1020 /// with its own resolved title, and only the ones the *reader* may already
1021 /// read the catalog course of at `GET /courses/{id}`, so a stranger sees an
1022 /// empty block while the owner and manager+ see it whole. The full list is
1023 /// at `GET /courses/me`.
1024 courses: Vec<ProfileCourseRef>,
1025 /// Every badge this account has earned, oldest first. Ids and stamps only —
1026 /// the label and the icon are the client's, keyed by id off the `badges`
1027 /// catalog at `GET /limits`.
1028 badges: Vec<ProfileBadge>,
1029 stats: ProfileStatsResponse,
1030}
1031
1032/// One earned badge. Permanent: once it appears here it never leaves, even if
1033/// the counter behind it falls back below the threshold that earned it.
1034#[derive(Serialize, ToSchema)]
1035struct ProfileBadge {
1036 /// A catalog id from `GET /limits` — `badges.catalog[].id`.
1037 #[schema(example = "pomodoro_finished_10")]
1038 id: String,
1039 /// When it was *first* earned, UTC unix-milliseconds. Later syncs never
1040 /// move it.
1041 #[schema(example = 1_759_000_000_000_i64)]
1042 earned_at: i64,
1043}
1044
1045/// What a stored avatar is, without its bytes.
1046#[derive(Serialize, ToSchema)]
1047struct ProfileAvatar {
1048 #[schema(example = "image/png")]
1049 content_type: String,
1050 /// Size in bytes.
1051 #[schema(example = 20_480)]
1052 size: i64,
1053}
1054
1055/// A class section as a profile shows it: the label, and nothing about who runs
1056/// it. The office-side view (creator, homeroom teacher) stays behind
1057/// `GET /classes/{id}`, which is teacher+.
1058#[derive(Serialize, ToSchema)]
1059struct ProfileClassRef {
1060 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
1061 id: String,
1062 #[schema(example = "9-A")]
1063 name: String,
1064 /// The class's rung on the grade ladder (`0` = anaokulu).
1065 #[schema(example = 9)]
1066 grade_level: i16,
1067}
1068
1069/// A course as a profile shows it — one row per **class section** the person
1070/// is reached by, never the catalog row: the 9-A and 12-A sections of one ders
1071/// carry their own resolved titles and hours, and the profile lists both. `id`
1072/// is the instance id (`GET /instances/{id}`); `kind` is the catalog row's,
1073/// which is the same for every section of one course.
1074///
1075/// The class identity rides the profile's **class gate**, not the course one:
1076/// `class`, `class_name` and `grade_level` name the section's şube, and a
1077/// class name and grade are exactly what `GET /classes/user/{id}` withholds
1078/// from a viewer below the [`crate::service::parent_link::ensure_can_observe`]
1079/// bar — so this block withholds them from exactly the same viewers (they
1080/// read `null`), the same all-or-nothing rule the `classes` block answers to.
1081/// A viewer who passes — self, teacher+, a linked parent — reads all three.
1082/// `id`, `course`, `title` and `kind` stay populated for everyone the course
1083/// gate lets through: the block's purpose is the section, not the class.
1084#[derive(Serialize, ToSchema)]
1085struct ProfileCourseRef {
1086 /// The instance id (`GET /instances/{id}`).
1087 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
1088 id: String,
1089 /// The catalog course this section teaches (`GET /courses/{id}`).
1090 #[schema(example = "019732e3-7b00-7000-8000-00000000beef")]
1091 course: String,
1092 /// The class this section belongs to (`GET /classes/{id}`) — `null` for a
1093 /// viewer below the class-observation bar.
1094 #[schema(example = "019732e3-7b00-7000-8000-00000000cafe")]
1095 class: Option<String>,
1096 /// The class's own name, e.g. `9-A` — `null` for a viewer below the
1097 /// class-observation bar.
1098 #[schema(example = "9-A")]
1099 class_name: Option<String>,
1100 /// The **resolved** display title of this section: its own override, else
1101 /// its offering's, else the catalog course's.
1102 #[schema(example = "Matematik")]
1103 title: String,
1104 /// The class's rung on the grade ladder (`0` = anaokulu) — `null` for a
1105 /// viewer below the class-observation bar.
1106 #[schema(example = 9)]
1107 grade_level: Option<i16>,
1108 /// `course`, `study` (supervised study), or `club`.
1109 #[schema(example = "course")]
1110 kind: String,
1111}
1112
1113/// The motivational counters. Derived, never settable, and never `null`: an
1114/// account with no rows behind a counter reads a true `0`.
1115///
1116/// Two kinds live here. The first four are **computed at read time** from the
1117/// rows that exist right now, so deleting the rows moves them down. Every
1118/// `*_total` one is a **stored lifetime counter**, incremented as the work
1119/// happens and never recomputed — they can therefore outlive the rows behind
1120/// them (an exam deleted by its teacher still counts as sat), which is exactly
1121/// why a badge earned off them stays earned. Each is named for a `stat` of the
1122/// badge catalog at `GET /limits`, plus `_total`, and that spelling is the join
1123/// a client makes between the two surfaces — so the suffix is on the key even
1124/// where the counter is not a running total (`study_streak_total` is a longest,
1125/// not a sum).
1126///
1127/// Some are staff counters and some student ones; a role that never does the
1128/// work simply reads zero, which is why no key is conditional.
1129///
1130/// Every number here is the **owner's** true total for every reader, never
1131/// narrowed per viewer — deliberately so even where the rows behind it sit
1132/// behind a gate this reader would fail (`GET /pomodoro/{id}`,
1133/// `GET /marks/user/{id}`, `GET /attendance/user/{id}`). A magnitude names no
1134/// course, class, lesson or exam, and a per-reader counter would make one
1135/// profile read differently to different people.
1136#[derive(Serialize, ToSchema)]
1137struct ProfileStatsResponse {
1138 /// Finished pomodoro stints; an open one counts for nothing.
1139 pomodoro_sessions: i64,
1140 /// Total focused milliseconds across those stints.
1141 pomodoro_focus_ms: i64,
1142 /// Every section behind the `courses` block, not just the embedded window.
1143 courses: i64,
1144 /// Every class behind the `classes` block, not just the embedded window.
1145 classes: i64,
1146 /// Lifetime homework hand-ins. Withdrawing a submission gives one back;
1147 /// editing one moves nothing.
1148 homework_submitted_total: i64,
1149 /// Lifetime hand-ins made before their deadline, judged at hand-in.
1150 homework_on_time_total: i64,
1151 /// Lifetime exams sat, counted at the first sitting of each exam — a retake
1152 /// moves nothing, and deleting the exam does not take one back.
1153 exam_sat_total: i64,
1154 /// Lifetime finished pomodoro stints.
1155 pomodoro_finished_total: i64,
1156 /// Lifetime focused milliseconds.
1157 pomodoro_focus_ms_total: i64,
1158 /// Lifetime grades this teacher recorded — exam sittings and homework
1159 /// submissions alike, once per pair: a regrade moves nothing, and deleting
1160 /// the grade gives it back.
1161 marks_given_total: i64,
1162 /// Lifetime lessons this teacher held, credited by the **first roll call
1163 /// taken at or after the lesson's own `starts_at`** — a lesson scheduled
1164 /// and cancelled counts for nothing, and neither does one marked before it
1165 /// has begun.
1166 lessons_held_total: i64,
1167 /// Lifetime pool questions this teacher approved.
1168 pool_approved_total: i64,
1169 /// Lifetime questions of this author that reached the school-wide pool,
1170 /// counted when the approval lands.
1171 pool_published_total: i64,
1172 /// Lifetime lesson roll calls that put this **student** `present` or
1173 /// `late`; a correction to any other status takes one back. Daily and event
1174 /// attendance moves it not at all.
1175 lessons_attended_total: i64,
1176 /// Lifetime exam marks at or above the high-mark cut published as
1177 /// `badges.high_mark_min` on `GET /limits`, one per graded sitting;
1178 /// deleting the mark gives it back, like the grader's own counter.
1179 /// Homework marks never count — they are optional and often status-only.
1180 high_mark_total: i64,
1181 /// Longest run of consecutive study days ever held — a high-water mark, so
1182 /// breaking the run never brings it down. Days end at midnight UTC.
1183 study_streak_total: i64,
1184}
1185
1186/// Build one profile as `viewer` may see it. The course block is chosen off the
1187/// owner's **live** role, not off the `creator`/`teachers` columns: those are
1188/// historical and no demotion sweeps them, so a demoted ex-teacher lists the
1189/// sections they are reached by, like any other student. It lists one row per
1190/// *section* and rides [`crate::web::courses::reached_instances`] — the class
1191/// roster / homeroom / taught set `GET /instances/me` serves, unioned with the
1192/// owner's own enrollment rows — so a section that is theirs to sit or run is
1193/// the only thing that appears.
1194///
1195/// A section carries a resolved title, and `GET /courses/{id}` hands that title
1196/// only to the enrolled, the staff who run it, and manager+ — so the block is
1197/// intersected with [`visible_courses`], the same catalog `GET /courses`
1198/// serves. Reading your own profile, or reading as manager+, needs no
1199/// intersection: both already see the whole list.
1200///
1201/// The class block answers to [`ensure_can_observe`], the gate
1202/// `GET /classes/user/{id}` holds — teacher+, or a parent linked to the target
1203/// — because every other `/classes` read is teacher+ and a class name and grade
1204/// are exactly what those routes withhold. That gate is all-or-nothing rather
1205/// than per class, so a viewer who fails it gets an empty block, not a 403: the
1206/// rest of the profile is still public to them.
1207///
1208/// So no *named* thing here crosses a gate the viewer would fail directly. The
1209/// magnitudes deliberately do — **every** one of them, not just the two that
1210/// count the gated blocks. `stats.courses` and `stats.classes` are the obvious
1211/// pair; `pomodoro_focus_ms` and `pomodoro_focus_ms_total` are byte-identical
1212/// to the `total_focus_ms` that `GET /pomodoro/{id}` serves behind
1213/// [`ensure_can_observe`]; and `lessons_attended_total`,
1214/// `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and
1215/// `high_mark_total` are magnitudes of the same report data that gate holds —
1216/// for a reader who is exactly [`Role::Teacher`] they are in fact *wider* than
1217/// the reports themselves, which [`crate::web::marks`] and
1218/// [`crate::web::attendance`] narrow to the courses that teacher manages.
1219///
1220/// That is the decision, not an oversight: every magnitude in `stats` is the
1221/// owner's true total for every reader. They are the motivational counters, a
1222/// per-reader number would make one profile read differently to different
1223/// people, and a magnitude names no course, no class, no lesson and no exam —
1224/// the *named* things stay behind their own gates, above.
1225async fn profile_of(
1226 st: &AppState,
1227 user: &User,
1228 viewer: &User,
1229) -> Result<ProfileResponse, AppError> {
1230 let id = user.get_id();
1231 // One catalog read per request, never one authorization call per course.
1232 let readable = match viewer.get_id() == id || viewer.get_role().at_least(Role::Manager) {
1233 true => None,
1234 false => Some(
1235 visible_courses(viewer, &st.db)
1236 .await?
1237 .iter()
1238 .map(|course| course.get_id().clone())
1239 .collect::<Vec<_>>(),
1240 ),
1241 };
1242 // The class sections the person is reached by — the same set
1243 // `GET /instances/me` serves, each with its own resolved title and hours.
1244 // The block is one row per section, and `stats.courses` counts sections.
1245 let mut sections = super::courses::reached_sections(&st.db, user).await?;
1246 let course_total = sections.len() as i64;
1247 // The window is cut after the intersection, so a filtered viewer still gets
1248 // up to `MAX_PROFILE_COURSES` sections they can actually see.
1249 if let Some(readable) = &readable {
1250 sections.retain(|section| readable.iter().any(|id| id.key() == section.course));
1251 }
1252 sections.truncate(MAX_PROFILE_COURSES);
1253 // The catalog row's `kind` — one read for the window, not one per row.
1254 let course_ids: Vec<crate::domain::course::CourseId> = sections
1255 .iter()
1256 .map(|section| crate::domain::course::CourseId::from_key(&section.course))
1257 .collect();
1258 let kinds: std::collections::HashMap<String, String> =
1259 crate::service::course::list_by_ids(&st.db, &course_ids)
1260 .await?
1261 .iter()
1262 .map(|course| {
1263 (
1264 course.get_id().key(),
1265 course.get_kind().as_str().to_string(),
1266 )
1267 })
1268 .collect();
1269 let (mut members, class_total) = crate::service::class_member::list_for_user(
1270 &st.db,
1271 id,
1272 Some(MAX_PROFILE_CLASSES as i64),
1273 0,
1274 )
1275 .await?;
1276 // The window is safe to take from the database here: the class gate is
1277 // all-or-nothing, so it drops the whole page or none of it — never a row
1278 // out of the middle of one.
1279 if viewer.get_id() != id && ensure_can_observe(viewer, id, &st.db).await.is_err() {
1280 members.clear();
1281 }
1282 // The section rows name their class (`class`/`class_name`/`grade_level`),
1283 // so the same all-or-nothing gate rules what that triple may say here:
1284 // one predicate, computed once, feeding both blocks — never a second
1285 // rule the two blocks could disagree about.
1286 let may_see_class = viewer.get_id() == id
1287 || ensure_can_observe(viewer, id, &st.db).await.is_ok();
1288 let class_ids: Vec<ClassGroupId> = members.iter().map(|row| row.get_class().clone()).collect();
1289 let classes = crate::service::class_group::list_by_ids(&st.db, &class_ids).await?;
1290 // Both totals are the full counts, not the windowed ones — the blocks are a
1291 // preview, the stats are the truth.
1292 let stats = crate::service::profile::load(&st.db, id, course_total, class_total).await?;
1293 let badges = badges_of(st, id, &stats).await?;
1294 Ok(ProfileResponse {
1295 id: id.key().to_string(),
1296 username: user.get_username().as_str().to_string(),
1297 // The whole three-step resolve lives in `PersonRef` — one spelling of
1298 // it, so this profile and every embedded person ref cannot disagree.
1299 display_name: PersonRef::new(user).display_name,
1300 role: user.get_role().into(),
1301 bio: user.get_bio().map(|bio| bio.as_str().to_string()),
1302 branch: user.get_branch().map(str::to_string),
1303 avatar: user
1304 .get_avatar_content_type()
1305 .map(|content_type| ProfileAvatar {
1306 content_type: content_type.as_str().to_string(),
1307 size: user.get_avatar_size().unwrap_or_default(),
1308 }),
1309 classes: classes
1310 .iter()
1311 .map(|class| ProfileClassRef {
1312 id: class.get_id().key().to_string(),
1313 name: class.get_name().as_str().to_string(),
1314 grade_level: class.get_grade_level().get(),
1315 })
1316 .collect(),
1317 courses: sections
1318 .iter()
1319 .map(|section| ProfileCourseRef {
1320 id: section.id.clone(),
1321 course: section.course.clone(),
1322 class: may_see_class.then(|| section.class.clone()),
1323 class_name: may_see_class.then(|| section.class_name.clone()),
1324 title: section.title.clone(),
1325 grade_level: may_see_class.then_some(section.grade_level),
1326 kind: kinds.get(&section.course).cloned().unwrap_or_default(),
1327 })
1328 .collect(),
1329 badges: badges
1330 .iter()
1331 .map(|award| ProfileBadge {
1332 id: award.get_badge().to_string(),
1333 earned_at: award.get_earned_at().as_millis(),
1334 })
1335 .collect(),
1336 stats: ProfileStatsResponse {
1337 pomodoro_sessions: stats.get_pomodoro_sessions(),
1338 pomodoro_focus_ms: stats.get_pomodoro_focus_ms(),
1339 courses: stats.get_courses(),
1340 classes: stats.get_classes(),
1341 homework_submitted_total: stats.get_totals().get_homework_submitted(),
1342 homework_on_time_total: stats.get_totals().get_homework_on_time(),
1343 exam_sat_total: stats.get_totals().get_exam_sat(),
1344 pomodoro_finished_total: stats.get_totals().get_pomodoro_finished(),
1345 pomodoro_focus_ms_total: stats.get_totals().get_pomodoro_focus_ms(),
1346 marks_given_total: stats.get_totals().get_marks_given(),
1347 lessons_held_total: stats.get_totals().get_lessons_held(),
1348 pool_approved_total: stats.get_totals().get_pool_approved(),
1349 pool_published_total: stats.get_totals().get_pool_published(),
1350 lessons_attended_total: stats.get_totals().get_lessons_attended(),
1351 high_mark_total: stats.get_totals().get_high_mark(),
1352 study_streak_total: stats.get_totals().get_study_streak(),
1353 },
1354 })
1355}
1356
1357/// The owner's earned badges, and the backstop that keeps them honest.
1358///
1359/// Every write that moves a counter syncs the badges behind it, so in the
1360/// steady state the earned set holds nothing the award rows do not already
1361/// carry and this is one read and **no write at all**. Only a threshold crossed
1362/// by a path whose sync was lost — a transient database error, which those
1363/// callers log and swallow on purpose — leaves a gap, and that heals here on
1364/// the next profile read of that account.
1365///
1366/// Nothing here revokes: [`badge::sync`] only ever adds, so a counter that has
1367/// since fallen back below its threshold leaves the badge standing. The sync's
1368/// own error is logged and dropped, and the awards already read are served —
1369/// a decoration may not fail the profile it decorates.
1370async fn badges_of(
1371 st: &AppState,
1372 user: &UserId,
1373 stats: &ProfileStats,
1374) -> Result<Vec<BadgeAward>, AppError> {
1375 let awards = crate::service::badge::list_for(&st.db, user).await?;
1376 let complete = badge::earned(stats.get_totals())
1377 .iter()
1378 .all(|id| awards.iter().any(|award| award.get_badge() == *id));
1379 if complete {
1380 return Ok(awards);
1381 }
1382 if let Err(err) = crate::service::badge::sync(&st.db, user).await {
1383 tracing::warn!("failed to sync badges for {}: {err}", user.key());
1384 return Ok(awards);
1385 }
1386 // Re-read so the badge just healed appears on *this* response, stamp and
1387 // all, rather than only on the next one.
1388 crate::service::badge::list_for(&st.db, user).await
1389}
1390
1391/// The profile gate: any authenticated account reads any profile — except a
1392/// parent, who is an observer of their own children and of nobody else. The
1393/// link alone is not the grant either; [`ensure_can_observe`] re-reads the
1394/// target's live role, so a student who was promoted out stops being readable.
1395async fn ensure_may_read_profile(
1396 caller: &User,
1397 target: &UserId,
1398 db: &Database,
1399) -> Result<(), AppError> {
1400 if caller.get_role() == Role::Parent && caller.get_id() != target {
1401 ensure_can_observe(caller, target, db).await?;
1402 }
1403 Ok(())
1404}
1405
1406/// The target's row, 404 if it is gone, once the caller is allowed to see it.
1407async fn readable_profile_user(st: &AppState, caller: &User, id: &str) -> Result<User, AppError> {
1408 let target = UserId::from_key(id);
1409 ensure_may_read_profile(caller, &target, &st.db).await?;
1410 crate::service::user::read(&st.db, &target)
1411 .await?
1412 .ok_or(AppError::NotFound)
1413}
1414
1415/// The caller's own public profile — what everyone else sees of them.
1416#[utoipa::path(
1417 get,
1418 path = "/me/profile",
1419 tag = "users",
1420 security(("session_cookie" = [])),
1421 responses(
1422 (status = 200, description = "The caller's profile", body = ProfileResponse),
1423 (status = 401, description = "Not authenticated", body = ErrorResponse),
1424 ),
1425)]
1426async fn my_profile(
1427 State(st): State<AppState>,
1428 CurrentUser(user): CurrentUser,
1429) -> Result<Json<ProfileResponse>, AppError> {
1430 Ok(Json(profile_of(&st, &user, &user).await?))
1431}
1432
1433/// One user's public profile: display name, bio, avatar meta, their class and
1434/// course blocks, the badges they have earned, and the motivational counters.
1435/// Badges carry an id and the instant they were first earned; their labels and
1436/// icons come from the `badges` catalog at `GET /limits`. Readable by every
1437/// authenticated account — except a parent, who reads only their own and their
1438/// linked students'. Never carries email, phone, or birth date; those stay on
1439/// `GET /users/{id}` (admin) and `GET /auth/me`. The embedded blocks are capped
1440/// at `max_profile_classes` / `max_profile_courses` (see `GET /limits`) — the
1441/// full paged lists are `GET /classes/me` and `GET /courses/me`. The course
1442/// block is also cut to what the *reader* may already see: only courses they
1443/// would pass `GET /courses/{id}` on. The class block holds the same bar as
1444/// `GET /classes/user/{id}` — teacher+, a parent linked to this student, or the
1445/// owner themselves; every other reader gets an empty `classes` array rather
1446/// than a 403. Every number in `stats` stays the owner's true total either way,
1447/// including the ones whose underlying reports are gated (`/pomodoro/{id}`,
1448/// `/marks/user/{id}`, `/attendance/user/{id}`): they are motivational
1449/// counters, and a magnitude names no course, class, lesson or exam.
1450#[utoipa::path(
1451 get,
1452 path = "/{id}/profile",
1453 tag = "users",
1454 security(("session_cookie" = [])),
1455 params(("id" = String, Path, description = "User id")),
1456 responses(
1457 (status = 200, description = "The user's profile", body = ProfileResponse),
1458 (status = 401, description = "Not authenticated", body = ErrorResponse),
1459 (status = 403, description = "A parent without a link to this student", body = ErrorResponse),
1460 (status = 404, description = "User not found", body = ErrorResponse),
1461 ),
1462)]
1463async fn get_user_profile(
1464 State(st): State<AppState>,
1465 CurrentUser(caller): CurrentUser,
1466 Path(id): Path<String>,
1467) -> Result<Json<ProfileResponse>, AppError> {
1468 let target = readable_profile_user(&st, &caller, &id).await?;
1469 Ok(Json(profile_of(&st, &target, &caller).await?))
1470}
1471
1472// ---- the avatar -------------------------------------------------------------
1473// One optional picture per user, the same one-image-on-the-owning-row shape the
1474// question pool uses: bytes on disk under a server-generated ULID, metadata on
1475// the user row. Every write here must take the replaced blob off disk — no
1476// route deletes a user, so nothing else would ever collect it.
1477
1478/// Upload (or replace) the caller's own avatar. `multipart/form-data` with the
1479/// image under a `file` field; the declared content type must be `image/png`,
1480/// `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the
1481/// bytes at most the school's `max_file_bytes` (settings). Replacing one drops
1482/// the previous picture.
1483#[utoipa::path(
1484 post,
1485 path = "/me/avatar",
1486 tag = "users",
1487 security(("session_cookie" = [])),
1488 request_body(content = UploadFileForm, content_type = "multipart/form-data"),
1489 responses(
1490 (status = 201, description = "Avatar stored", body = ProfileAvatar),
1491 (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse),
1492 (status = 401, description = "Not authenticated", body = ErrorResponse),
1493 (status = 404, description = "The account no longer exists", body = ErrorResponse),
1494 (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse),
1495 ),
1496)]
1497async fn upload_my_avatar(
1498 State(st): State<AppState>,
1499 CurrentUser(user): CurrentUser,
1500 mut multipart: Multipart,
1501) -> Result<(StatusCode, Json<ProfileAvatar>), AppError> {
1502 let upload = read_image_upload(&st, &mut multipart).await?;
1503 let size = upload.size();
1504
1505 let file = crate::domain::monotonic_id::next_uuid().to_string();
1506 store_blob(&st, &file, &upload.data, || async {
1507 match crate::service::user::set_avatar(
1508 &st.db,
1509 user.get_id(),
1510 &file,
1511 &upload.content_type,
1512 size,
1513 )
1514 .await?
1515 {
1516 // Row written; the picture this one replaced comes off disk.
1517 Some(before) => Ok(((), before.get_avatar_file().map(str::to_string))),
1518 // The account went away mid-upload — the fresh blob is an orphan.
1519 None => Err(AppError::NotFound),
1520 }
1521 })
1522 .await?;
1523 Ok((
1524 StatusCode::CREATED,
1525 Json(ProfileAvatar {
1526 content_type: upload.content_type.as_str().to_string(),
1527 size,
1528 }),
1529 ))
1530}
1531
1532/// The caller's own avatar bytes. The self alias of `GET /{id}/avatar` — the
1533/// static `/me/avatar` segment wins over `/{id}/avatar` in the router, so
1534/// without this a client that never learned its own id gets a bodyless `405`
1535/// on the obvious route. It serves the caller's own row and nothing else, so
1536/// it asks no gate: the session already proves the reach.
1537#[utoipa::path(
1538 get,
1539 path = "/me/avatar",
1540 tag = "users",
1541 security(("session_cookie" = [])),
1542 responses(
1543 (status = 200, description = "The image bytes", content_type = "image/*"),
1544 (status = 401, description = "Not authenticated", body = ErrorResponse),
1545 (status = 404, description = "The caller has no avatar", body = ErrorResponse),
1546 ),
1547)]
1548async fn get_my_avatar(
1549 State(st): State<AppState>,
1550 CurrentUser(user): CurrentUser,
1551) -> Result<Response, AppError> {
1552 serve_avatar(&st, &user).await
1553}
1554
1555/// The avatar bytes. Same reach as the profile itself: every authenticated
1556/// account, except a parent, who is limited to their own and their linked
1557/// students'.
1558#[utoipa::path(
1559 get,
1560 path = "/{id}/avatar",
1561 tag = "users",
1562 security(("session_cookie" = [])),
1563 params(("id" = String, Path, description = "User id")),
1564 responses(
1565 (status = 200, description = "The image bytes", content_type = "image/*"),
1566 (status = 401, description = "Not authenticated", body = ErrorResponse),
1567 (status = 403, description = "A parent without a link to this student", body = ErrorResponse),
1568 (status = 404, description = "No such user, or they have no avatar", body = ErrorResponse),
1569 ),
1570)]
1571async fn get_avatar(
1572 State(st): State<AppState>,
1573 CurrentUser(caller): CurrentUser,
1574 Path(id): Path<String>,
1575) -> Result<Response, AppError> {
1576 let target = readable_profile_user(&st, &caller, &id).await?;
1577 serve_avatar(&st, &target).await
1578}
1579
1580/// The shared tail of both avatar reads: the bytes, or a `404` when the row
1581/// carries none. The caller owns the gate — this one is reached already.
1582async fn serve_avatar(st: &AppState, user: &User) -> Result<Response, AppError> {
1583 match (user.get_avatar_file(), user.get_avatar_content_type()) {
1584 (Some(file), Some(content_type)) => {
1585 serve_inline_blob(&st.files_path, file, content_type).await
1586 }
1587 _ => Err(AppError::NotFound),
1588 }
1589}
1590
1591/// Remove the caller's own avatar.
1592#[utoipa::path(
1593 delete,
1594 path = "/me/avatar",
1595 tag = "users",
1596 security(("session_cookie" = [])),
1597 responses(
1598 (status = 204, description = "Avatar removed"),
1599 (status = 401, description = "Not authenticated", body = ErrorResponse),
1600 (status = 404, description = "No avatar to remove", body = ErrorResponse),
1601 ),
1602)]
1603async fn delete_my_avatar(
1604 State(st): State<AppState>,
1605 CurrentUser(user): CurrentUser,
1606) -> Result<StatusCode, AppError> {
1607 drop_avatar(&st, user.get_id()).await
1608}
1609
1610/// Remove any user's avatar. Admin only — the moderation path: an offensive
1611/// picture is a school problem, and no route deletes the account it hangs on.
1612#[utoipa::path(
1613 delete,
1614 path = "/{id}/avatar",
1615 tag = "users",
1616 security(("session_cookie" = [])),
1617 params(("id" = String, Path, description = "User id")),
1618 responses(
1619 (status = 204, description = "Avatar removed"),
1620 (status = 401, description = "Not authenticated", body = ErrorResponse),
1621 (status = 403, description = "Requires admin role", body = ErrorResponse),
1622 (status = 404, description = "No such user, or no avatar to remove", body = ErrorResponse),
1623 ),
1624)]
1625async fn delete_avatar(
1626 State(st): State<AppState>,
1627 _admin: RequireAdmin,
1628 Path(id): Path<String>,
1629) -> Result<StatusCode, AppError> {
1630 drop_avatar(&st, &UserId::from_key(&id)).await
1631}
1632
1633/// Clear the row's avatar and take its blob off disk — the shared tail of the
1634/// self and moderation deletes. A row without one (or no row at all) is a 404.
1635async fn drop_avatar(st: &AppState, user: &UserId) -> Result<StatusCode, AppError> {
1636 let before = crate::service::user::clear_avatar(&st.db, user)
1637 .await?
1638 .ok_or(AppError::NotFound)?;
1639 let Some(file) = before.get_avatar_file() else {
1640 return Err(AppError::NotFound);
1641 };
1642 remove_blob(&st.files_path, file).await;
1643 Ok(StatusCode::NO_CONTENT)
1644}
1645
1646#[cfg(test)]
1647mod tests {
1648 use super::*;
1649
1650 fn filter(roles: Option<&str>) -> ListUsersFilter {
1651 ListUsersFilter {
1652 roles: roles.map(str::to_owned),
1653 }
1654 }
1655
1656 #[test]
1657 fn absent_roles_is_every_user() {
1658 assert_eq!(filter(None).resolve().unwrap(), None);
1659 }
1660
1661 #[test]
1662 fn roles_parse_into_the_role_set() {
1663 // The manager tab is one OR set, not an intersection.
1664 assert_eq!(
1665 filter(Some("manager,admin")).resolve().unwrap(),
1666 Some(vec![Role::Manager, Role::Admin])
1667 );
1668 assert_eq!(
1669 filter(Some("student")).resolve().unwrap(),
1670 Some(vec![Role::Student])
1671 );
1672 // A stray space rides the trim, like every other query value.
1673 assert_eq!(
1674 filter(Some(" teacher ")).resolve().unwrap(),
1675 Some(vec![Role::Teacher])
1676 );
1677 }
1678
1679 #[test]
1680 fn a_bad_roles_value_is_refused_naming_roles() {
1681 // Empty value, unknown name, blank token, whitespace-only token, and
1682 // the non-assignable service principal — all the same field naming.
1683 for bad in ["", "nope", "manager,", "manager, ,admin", "ai"] {
1684 let err = filter(Some(bad)).resolve().unwrap_err();
1685 let ValidationError::Invalid { field, .. } = err else {
1686 panic!("expected Invalid for {bad:?}, got {err}");
1687 };
1688 assert_eq!(field, "roles", "{bad:?} must name the roles field");
1689 }
1690 }
1691}