forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 commits

users.rs1294 lines, 55.6 KiBHistoryRawDownload
1use crate::web::tenant_state::{SchoolSlug, 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, UPLOAD_BODY_OVERHEAD_BYTES,
14};
15use crate::database::Database;
16use crate::domain::badge::{self, BadgeAward};
17use crate::domain::class_group::ClassGroupId;
18
19use crate::domain::preferences::{Language, PaletteColor, Theme};
20use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone, ProfileStats};
21use crate::domain::role::Role;
22use crate::domain::user::{User, UserId};
23use crate::error::{AppError, ErrorResponse, ValidationError};
24use crate::service::parent_link::ensure_can_observe;
25use crate::state::AppState;
26
27use super::courses::visible_courses;
28use super::dto::AssignableRole;
29use super::dto::Role as RoleSchema;
30use super::{
31 CurrentUser, Page, PageParams, PersonRef, RequireAdmin, UploadFileForm, UserResponse, paginate,
32 read_image_upload, remove_blob, serve_inline_blob, store_blob,
33};
34
35pub fn routes() -> OpenApiRouter<AppState> {
36 OpenApiRouter::new()
37 .routes(routes!(list_users))
38 .routes(routes!(update_my_profile))
39 .routes(routes!(update_my_preferences))
40 .routes(routes!(my_students))
41 .routes(routes!(my_profile))
42 .routes(routes!(search_users))
43 .routes(routes!(get_user))
44 .routes(routes!(set_role))
45 .routes(routes!(update_user_profile, get_user_profile))
46 .routes(routes!(update_user_preferences))
47 .routes(routes!(link_student, list_parent_students))
48 .routes(routes!(unlink_student))
49 // The avatar routes get their own HTTP body cap, like the note-file and
50 // question-image ones: the server-wide hard ceiling plus multipart
51 // framing headroom. It must stay on this sub-router — on the whole
52 // `/users` router every JSON endpoint would start accepting 25 MB.
53 .merge(
54 OpenApiRouter::new()
55 .routes(routes!(upload_my_avatar, get_my_avatar, delete_my_avatar))
56 .routes(routes!(get_avatar, delete_avatar))
57 .layer(DefaultBodyLimit::max(
58 MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES,
59 )),
60 )
61}
62
63#[derive(Deserialize, ToSchema)]
64struct SetRole {
65 /// The role to assign. Deserialized as a string so an unknown value returns a
66 /// uniform `400`; documented as the `AssignableRole` enum so the docs list
67 /// exactly the choices the server accepts (the response-side `Role` also
68 /// names the `ai` service principal, which this endpoint has always refused).
69 #[schema(value_type = AssignableRole, example = "teacher")]
70 role: String,
71}
72
73/// Partial personal-info update. Per field: omitted (or `null`) keeps the
74/// current value, an empty string clears it, anything else is validated and set.
75#[derive(Deserialize, ToSchema)]
76struct UpdateProfile {
77 #[schema(example = "Ada", max_length = 100)]
78 name: Option<String>,
79 #[schema(example = "Lovelace", max_length = 100)]
80 surname: Option<String>,
81 #[schema(example = "ada@example.com", max_length = 254)]
82 email: Option<String>,
83 /// Any punctuation and spacing; it is the digit count that must land in
84 /// `7`–`15`, so no character-length bound applies.
85 #[schema(example = "+90 555 123 45 67")]
86 phone: Option<String>,
87 /// Birth date in `YYYY-MM-DD` form.
88 #[schema(example = "1990-01-02")]
89 birth_date: Option<String>,
90 /// The name the public profile is shown under, instead of the legal one.
91 #[schema(example = "Ada", max_length = 50)]
92 display_name: Option<String>,
93 /// Free text under the profile's name.
94 #[schema(example = "Sınıfın en hızlı pomodorocusu.", max_length = 500)]
95 bio: Option<String>,
96}
97
98/// Partial UI-preference update. Same field semantics as [`UpdateProfile`]:
99/// omitted (or `null`) keeps the current value, an empty string clears it back
100/// to "never chose" (the client then follows the device preference), anything
101/// else is validated and set.
102#[derive(Deserialize, ToSchema)]
103struct UpdatePreferences {
104 /// `light` or `dark`.
105 #[schema(example = "dark")]
106 theme: Option<String>,
107 /// `tr` or `en` (ISO 639-1).
108 #[schema(example = "tr")]
109 language: Option<String>,
110 /// Accent color as a 6-digit hex with a leading `#`; stored lowercase. Any
111 /// valid hex, not a fixed palette.
112 #[schema(example = "#fefae0")]
113 palette_color: Option<String>,
114}
115
116/// Resolve one patched field into what the save should write: absent (or
117/// `null`) is `None` — the column is not written at all, so a concurrent PATCH
118/// of it survives; `""` is `Some(None)`, an explicit clear; anything else must
119/// parse into the domain newtype, exactly as a create would.
120fn merge_field<T>(
121 patch: Option<&str>,
122 parse: impl Fn(&str) -> Result<T, ValidationError>,
123) -> Result<Option<Option<T>>, ValidationError> {
124 match patch {
125 None => Ok(None),
126 Some("") => Ok(Some(None)),
127 Some(value) => Ok(Some(Some(parse(value)?))),
128 }
129}
130
131/// Validate and persist exactly the info fields `req` carried — nothing is
132/// merged from `user`'s snapshot, so a concurrent PATCH of another field is not
133/// reverted. Shared by the self-service and admin profile endpoints — they
134/// differ only in whose row they load and who may call them.
135async fn apply_profile(
136 user: User,
137 req: &UpdateProfile,
138 db: &Database,
139) -> Result<UserResponse, AppError> {
140 let name = merge_field(req.name.as_deref(), |v| PersonName::try_new("name", v))?;
141 let surname = merge_field(req.surname.as_deref(), |v| {
142 PersonName::try_new("surname", v)
143 })?;
144 let email = merge_field(req.email.as_deref(), Email::try_new)?;
145 let phone = merge_field(req.phone.as_deref(), Phone::try_new)?;
146 let birth_date = merge_field(req.birth_date.as_deref(), BirthDate::try_new)?;
147 let display_name = merge_field(req.display_name.as_deref(), DisplayName::try_new)?;
148 let bio = merge_field(req.bio.as_deref(), Bio::try_new)?;
149 let updated = crate::service::user::set_profile(
150 db,
151 user.get_id(),
152 name,
153 surname,
154 email,
155 phone,
156 birth_date,
157 display_name,
158 bio,
159 )
160 .await?;
161 Ok(UserResponse::new(&updated))
162}
163
164/// Validate and persist exactly the preference fields `req` carried — same
165/// no-merge reasoning as [`apply_profile`]. Shared by the
166/// self-service and admin preference endpoints — they differ only in whose row
167/// they load and who may call them.
168async fn apply_preferences(
169 user: User,
170 req: &UpdatePreferences,
171 db: &Database,
172) -> Result<UserResponse, AppError> {
173 let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?;
174 let language = merge_field(req.language.as_deref(), Language::try_from_str)?;
175 let palette_color = merge_field(req.palette_color.as_deref(), PaletteColor::try_from_str)?;
176 let updated =
177 crate::service::user::set_preferences(db, user.get_id(), theme, language, palette_color)
178 .await?;
179 Ok(UserResponse::new(&updated))
180}
181
182#[derive(Deserialize, IntoParams)]
183struct SearchUsers {
184 /// Case-insensitive fragment of a username, name, or surname. May be
185 /// blank when `role` is given — that lists the whole role.
186 q: String,
187 /// Restrict matches to one role: `parent`, `student`, `teacher`,
188 /// `manager`, or `admin`. Omit to search every role.
189 role: Option<String>,
190 /// Max matches to return. Omit for every match; when given, `1`–`500`.
191 #[param(minimum = 1, maximum = 500, example = 100)]
192 limit: Option<i64>,
193 /// Matches to skip from the start. Defaults to `0`.
194 #[param(minimum = 0, example = 0)]
195 offset: Option<i64>,
196}
197
198/// Find users by username or name — backs the pickers (enroll, grade, mark
199/// attendance) and, for a student or parent, the one way to find the staff
200/// member they are allowed to message. Any authenticated user may ask; a
201/// caller below teacher only ever sees the roles they may message (teacher,
202/// manager, admin), in the items *and* in `total`. `role` narrows to one role
203/// (e.g. `role=student` for an enroll picker) — a student or parent naming a
204/// role they may not message is refused; a blank `q` with a `role` lists
205/// everyone in that role. Paged via `?limit=&offset=` like the other lists
206/// (omit `limit` for every match); returns a `{items, total, limit, offset}`
207/// envelope carrying only id/username/display name — no contact details.
208#[utoipa::path(
209 get,
210 path = "/search",
211 tag = "users",
212 security(("session_cookie" = [])),
213 params(SearchUsers),
214 responses(
215 (status = 200, description = "A page of matching users (all matches when unpaged)", body = Page<PersonRef>),
216 (status = 400, description = "Blank query without a role, unknown role, or invalid limit/offset", body = ErrorResponse),
217 (status = 401, description = "Not authenticated", body = ErrorResponse),
218 (status = 403, description = "A student or parent asked for a role they may not message", body = ErrorResponse),
219 ),
220)]
221async fn search_users(
222 State(st): State<AppState>,
223 CurrentUser(user): CurrentUser,
224 Query(req): Query<SearchUsers>,
225) -> Result<Json<Page<PersonRef>>, AppError> {
226 if req.q.trim().is_empty() && req.role.is_none() {
227 return Err(AppError::Validation(ValidationError::Invalid {
228 field: "q",
229 reason: "must not be empty unless role is given",
230 }));
231 }
232 let (limit, offset) = PageParams {
233 limit: req.limit,
234 offset: req.offset,
235 }
236 .resolve()?;
237 let role = req.role.as_deref().map(Role::try_from_str).transpose()?;
238 // Below staff the caller may only see whom they may write to. Asking for a
239 // role outside that set is a refusal, not a silently empty page.
240 let allowed = user.get_role().messageable_roles();
241 if let (Some(allowed), Some(role)) = (allowed, role)
242 && !allowed.contains(&role)
243 {
244 return Err(AppError::Forbidden(
245 "students and parents may only search staff (teacher or higher)",
246 ));
247 }
248 let (users, total) =
249 crate::service::user::search(&st.db, &req.q, role, allowed, limit, offset).await?;
250 let items = users.iter().map(PersonRef::new).collect();
251 Ok(Json(Page::new(items, total, limit, offset)))
252}
253
254/// List every user with their role, newest first. Admin only. Paged: pass
255/// `?limit=&offset=` to take a window (omit `limit` for the whole list); the
256/// response is a `{items, total, limit, offset}` envelope where `total` counts
257/// every user.
258#[utoipa::path(
259 get,
260 path = "/",
261 tag = "users",
262 security(("session_cookie" = [])),
263 params(PageParams),
264 responses(
265 (status = 200, description = "A page of users (the full list when unpaged)", body = Page<UserResponse>),
266 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
267 (status = 401, description = "Not authenticated", body = ErrorResponse),
268 (status = 403, description = "Requires admin role", body = ErrorResponse),
269 ),
270)]
271async fn list_users(
272 State(st): State<AppState>,
273 _admin: RequireAdmin,
274 Query(page): Query<PageParams>,
275) -> Result<Json<Page<UserResponse>>, AppError> {
276 let (limit, offset) = page.resolve()?;
277 let (users, total) = crate::service::user::list_all(&st.db, limit, offset).await?;
278 let items = users.iter().map(UserResponse::new).collect();
279 Ok(Json(Page::new(items, total, limit, offset)))
280}
281
282/// Update the caller's own personal info: name, surname, email, phone, birth
283/// date, plus the public-profile pair `display_name` and `bio` (both readable
284/// school-wide at `GET /users/{id}/profile`, unlike the contact fields). Any
285/// authenticated role. Omitted fields stay as they are; an empty string clears
286/// a field.
287#[utoipa::path(
288 patch,
289 path = "/me",
290 tag = "users",
291 security(("session_cookie" = [])),
292 request_body = UpdateProfile,
293 responses(
294 (status = 200, description = "Updated user", body = UserResponse),
295 (status = 400, description = "Invalid field", body = ErrorResponse),
296 (status = 401, description = "Not authenticated", body = ErrorResponse),
297 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
298 ),
299)]
300async fn update_my_profile(
301 State(st): State<AppState>,
302 CurrentUser(user): CurrentUser,
303 Json(req): Json<UpdateProfile>,
304) -> Result<Json<UserResponse>, AppError> {
305 Ok(Json(apply_profile(user, &req, &st.db).await?))
306}
307
308/// Update the caller's own UI preferences: `theme` (`light`/`dark`),
309/// `language` (`tr`/`en`), and `palette_color` (accent color as `#rrggbb`).
310/// Any authenticated role. Omitted fields stay as they
311/// are; an empty string clears one back to "never chose" (the client then
312/// follows the device preference). Read them back on any user response, e.g.
313/// `GET /auth/me`.
314#[utoipa::path(
315 patch,
316 path = "/me/preferences",
317 tag = "users",
318 security(("session_cookie" = [])),
319 request_body = UpdatePreferences,
320 responses(
321 (status = 200, description = "Updated user", body = UserResponse),
322 (status = 400, description = "Invalid theme, language, or palette color", body = ErrorResponse),
323 (status = 401, description = "Not authenticated", body = ErrorResponse),
324 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
325 ),
326)]
327async fn update_my_preferences(
328 State(st): State<AppState>,
329 CurrentUser(user): CurrentUser,
330 Json(req): Json<UpdatePreferences>,
331) -> Result<Json<UserResponse>, AppError> {
332 Ok(Json(apply_preferences(user, &req, &st.db).await?))
333}
334
335/// Fetch one user with their role and personal info. Admin only.
336#[utoipa::path(
337 get,
338 path = "/{id}",
339 tag = "users",
340 security(("session_cookie" = [])),
341 params(("id" = String, Path, description = "User id")),
342 responses(
343 (status = 200, description = "The user", body = UserResponse),
344 (status = 401, description = "Not authenticated", body = ErrorResponse),
345 (status = 403, description = "Requires admin role", body = ErrorResponse),
346 (status = 404, description = "User not found", body = ErrorResponse),
347 ),
348)]
349async fn get_user(
350 State(st): State<AppState>,
351 _admin: RequireAdmin,
352 Path(id): Path<String>,
353) -> Result<Json<UserResponse>, AppError> {
354 let user = crate::service::user::read(&st.db, &UserId::from_key(&id))
355 .await?
356 .ok_or(AppError::NotFound)?;
357 Ok(Json(UserResponse::new(&user)))
358}
359
360/// Update any user's personal info. Admin only — the school-office path for
361/// maintaining records on behalf of students and staff. Same field semantics
362/// as `PATCH /users/me`.
363#[utoipa::path(
364 patch,
365 path = "/{id}/profile",
366 tag = "users",
367 security(("session_cookie" = [])),
368 params(("id" = String, Path, description = "User id")),
369 request_body = UpdateProfile,
370 responses(
371 (status = 200, description = "Updated user", body = UserResponse),
372 (status = 400, description = "Invalid field", body = ErrorResponse),
373 (status = 401, description = "Not authenticated", body = ErrorResponse),
374 (status = 403, description = "Requires admin role", body = ErrorResponse),
375 (status = 404, description = "User not found", body = ErrorResponse),
376 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
377 ),
378)]
379async fn update_user_profile(
380 State(st): State<AppState>,
381 _admin: RequireAdmin,
382 Path(id): Path<String>,
383 Json(req): Json<UpdateProfile>,
384) -> Result<Json<UserResponse>, AppError> {
385 let user = crate::service::user::read(&st.db, &UserId::from_key(&id))
386 .await?
387 .ok_or(AppError::NotFound)?;
388 Ok(Json(apply_profile(user, &req, &st.db).await?))
389}
390
391/// Update any user's UI preferences. Admin only — everyone else manages their
392/// own through `PATCH /users/me/preferences`, which this mirrors field for
393/// field.
394#[utoipa::path(
395 patch,
396 path = "/{id}/preferences",
397 tag = "users",
398 security(("session_cookie" = [])),
399 params(("id" = String, Path, description = "User id")),
400 request_body = UpdatePreferences,
401 responses(
402 (status = 200, description = "Updated user", body = UserResponse),
403 (status = 400, description = "Invalid theme, language, or palette color", body = ErrorResponse),
404 (status = 401, description = "Not authenticated", body = ErrorResponse),
405 (status = 403, description = "Requires admin role", body = ErrorResponse),
406 (status = 404, description = "User not found", body = ErrorResponse),
407 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
408 ),
409)]
410async fn update_user_preferences(
411 State(st): State<AppState>,
412 _admin: RequireAdmin,
413 Path(id): Path<String>,
414 Json(req): Json<UpdatePreferences>,
415) -> Result<Json<UserResponse>, AppError> {
416 let user = crate::service::user::read(&st.db, &UserId::from_key(&id))
417 .await?
418 .ok_or(AppError::NotFound)?;
419 Ok(Json(apply_preferences(user, &req, &st.db).await?))
420}
421
422/// Set a user's role. Admin only. An admin cannot change their own role, and
423/// the school's **last** admin cannot be demoted by anyone (`409`) — together
424/// those keep role management from locking everyone out, including when two
425/// admins demote each other at the same instant (the floor is a predicate on
426/// the role write itself, so the racing demotions serialize on row locks).
427/// A school that has already lost its admins is recovered by hand against the
428/// database, since the seed never promotes.
429/// Setting any non-`student` role also drops the user's course enrollments —
430/// only students enroll, so a promoted user leaves every roster. Demoting below
431/// `teacher` drops their course teaching assignments for the mirror reason, and
432/// withdraws their published appointment slots, cancelling the live bookings on
433/// them: nothing could reach either afterwards — a slot is listed only on its
434/// own teacher's calendar and deleted only by a teacher+, and a booking on one
435/// is decided only by a teacher+ and cancelled only by its requester, who is
436/// refused once the window opens. The requester keeps the booking as
437/// `cancelled`, naming the ex-teacher and the reason.
438/// Demoting to `parent` additionally gives back the seats they hold on
439/// still-open event signup lists: a parent can no longer free them, and nobody
440/// else may. Seats on lists that have already closed stay as they are — that
441/// roster is history. It also takes the account off every whiteboard roster and
442/// **closes every board it created** — permanently read-only, nothing deleted.
443/// A demoted creator is a `404` on their own board, the four commands that could
444/// end it are the creator's alone, and no route lists a board the caller is not
445/// on, so the room would otherwise be commandable by nobody while its
446/// participants kept drawing on it. Closed, they keep reading the board, its
447/// history and its epochs; only writes are refused.
448#[utoipa::path(
449 patch,
450 path = "/{id}/role",
451 tag = "users",
452 security(("session_cookie" = [])),
453 params(("id" = String, Path, description = "User id")),
454 request_body = SetRole,
455 responses(
456 (status = 200, description = "Updated user", body = UserResponse),
457 (status = 400, description = "Invalid role", body = ErrorResponse),
458 (status = 401, description = "Not authenticated", body = ErrorResponse),
459 (status = 403, description = "Requires admin, or attempted to change own role", body = ErrorResponse),
460 (status = 404, description = "User not found", body = ErrorResponse),
461 (status = 409, description = "That account is the school's last admin", body = ErrorResponse),
462 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
463 ),
464)]
465async fn set_role(
466 State(st): State<AppState>,
467 SchoolSlug(slug): SchoolSlug,
468 RequireAdmin(admin): RequireAdmin,
469 Path(id): Path<String>,
470 Json(req): Json<SetRole>,
471) -> Result<Json<UserResponse>, AppError> {
472 let role = Role::try_from_str(&req.role)?;
473 let target = UserId::from_key(&id);
474 if &target == admin.get_id() {
475 return Err(AppError::Forbidden("cannot change your own role"));
476 }
477 // The role write and every sweep it owes commit together
478 // ([`crate::service::user::set_role`] carries the whole list and the
479 // reasoning behind each arm). The write ordering *within* a request is
480 // closed from the other end: a handler that assigns a teacher-only role
481 // re-reads the live role after its write ([`super::undo_if_demoted`]), so
482 // a demotion racing an assignment is caught by whichever side is second.
483 let (updated, boards) = crate::service::user::set_role(&st.db, &target, role).await?;
484 // Whiteboard rooms the commit above changed, prompted with the same frames
485 // their own routes publish — after the commit, because the room re-reads the
486 // database before it acts on a frame. A room whose creator was demoted is
487 // now closed, and its `closed` frame is what turns the open sockets
488 // read-only; told only about the roster, they would draw on until each
489 // stroke came back refused.
490 for board in boards {
491 st.board_hub.publish(
492 &slug,
493 board.get_id().key().as_str(),
494 json!({
495 "type": "participants",
496 "creator": board.get_creator().key(),
497 "participants": board
498 .get_participants()
499 .iter()
500 .map(|user| user.key())
501 .collect::<Vec<_>>(),
502 })
503 .to_string(),
504 );
505 if let Some(closed_at) = board.get_closed_at() {
506 st.board_hub.publish(
507 &slug,
508 board.get_id().key().as_str(),
509 json!({"type": "closed", "closed_at": closed_at.as_millis()}).to_string(),
510 );
511 }
512 }
513 Ok(Json(UserResponse::new(&updated)))
514}
515
516#[derive(Deserialize, ToSchema)]
517struct LinkStudent {
518 /// The student to tie to this parent.
519 user_id: String,
520}
521
522#[derive(Serialize, ToSchema)]
523struct ParentLinkResponse {
524 parent: PersonRef,
525 student: PersonRef,
526 /// The admin who created the tie.
527 linked_by: PersonRef,
528}
529
530/// One page of a parent's observed students, sorted by username. Shared by the
531/// admin listing and the parent's own `/me/students` — they differ only in
532/// whose links they read and who may call them.
533async fn students_page(
534 parent: &UserId,
535 page: PageParams,
536 db: &Database,
537) -> Result<Page<PersonRef>, AppError> {
538 let (limit, offset) = page.resolve()?;
539 let links = crate::service::parent_link::list_for_parent(db, parent).await?;
540 let ids: Vec<UserId> = links
541 .iter()
542 .map(|link| link.get_student().clone())
543 .collect();
544 let mut students = crate::service::user::list_by_ids(db, &ids).await?;
545 // The link row alone is not the grant, exactly as [`ensure_can_observe`]
546 // says: a link whose student side changed role (a sweep lost a race with
547 // `link_student`) is inert everywhere else, so it must not name a person
548 // here either. Filtered at read time rather than swept, which also makes
549 // any such row already on disk inert without a migration.
550 students.retain(|student| student.get_role() == Role::Student);
551 students.sort_by(|a, b| a.get_username().as_str().cmp(b.get_username().as_str()));
552 let total = students.len() as i64;
553 // Paged in the web layer: the rows come from a link table and are
554 // re-sorted by username in Rust.
555 let items = paginate(&students, limit, offset)
556 .iter()
557 .map(PersonRef::new)
558 .collect();
559 Ok(Page::new(items, total, limit, offset))
560}
561
562/// Tie a student to a parent account. Admin only — family ties are school-office
563/// records, like roles. `{id}` must hold the `parent` role and `user_id` the
564/// `student` role; a parent may observe any number of students. Idempotent:
565/// linking the same pair again keeps the one tie (the `linked_by` stamp moves
566/// to the latest linker, like re-enrolling). The tie grants the
567/// parent read access to the student's marks, attendance, and pomodoro reports
568/// — nothing else, and never any write.
569#[utoipa::path(
570 post,
571 path = "/{id}/students",
572 tag = "users",
573 security(("session_cookie" = [])),
574 params(("id" = String, Path, description = "Parent user id")),
575 request_body = LinkStudent,
576 responses(
577 (status = 200, description = "The tie (created or already present)", body = ParentLinkResponse),
578 (status = 400, description = "The target is not a parent, or user_id is unknown or not a student", body = ErrorResponse),
579 (status = 401, description = "Not authenticated", body = ErrorResponse),
580 (status = 403, description = "Requires admin role", body = ErrorResponse),
581 (status = 404, description = "Parent user not found", body = ErrorResponse),
582 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
583 ),
584)]
585async fn link_student(
586 State(st): State<AppState>,
587 RequireAdmin(admin): RequireAdmin,
588 Path(id): Path<String>,
589 Json(req): Json<LinkStudent>,
590) -> Result<Json<ParentLinkResponse>, AppError> {
591 let (link, parent, student) = crate::service::parent_link::link(
592 &st.db,
593 &UserId::from_key(&id),
594 &UserId::from_key(&req.user_id),
595 admin.get_id(),
596 )
597 .await?;
598 let people = PersonRef::map_of(&[&parent, &student, &admin]);
599 Ok(Json(ParentLinkResponse {
600 parent: PersonRef::resolve(&people, link.get_parent()),
601 student: PersonRef::resolve(&people, link.get_student()),
602 linked_by: PersonRef::resolve(&people, link.get_linked_by()),
603 }))
604}
605
606/// List the students tied to a parent account, sorted by username. Admin only
607/// — parents read their own list at `GET /users/me/students`. Paged via
608/// `?limit=&offset=` like the other lists.
609#[utoipa::path(
610 get,
611 path = "/{id}/students",
612 tag = "users",
613 security(("session_cookie" = [])),
614 params(("id" = String, Path, description = "Parent user id"), PageParams),
615 responses(
616 (status = 200, description = "A page of the parent's students", body = Page<PersonRef>),
617 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
618 (status = 401, description = "Not authenticated", body = ErrorResponse),
619 (status = 403, description = "Requires admin role", body = ErrorResponse),
620 (status = 404, description = "User not found", body = ErrorResponse),
621 ),
622)]
623async fn list_parent_students(
624 State(st): State<AppState>,
625 _admin: RequireAdmin,
626 Path(id): Path<String>,
627 Query(page): Query<PageParams>,
628) -> Result<Json<Page<PersonRef>>, AppError> {
629 let parent = UserId::from_key(&id);
630 crate::service::user::read(&st.db, &parent)
631 .await?
632 .ok_or(AppError::NotFound)?;
633 Ok(Json(students_page(&parent, page, &st.db).await?))
634}
635
636/// Untie a student from a parent account. Admin only. The student's data is
637/// untouched — only the parent's read grant goes away.
638#[utoipa::path(
639 delete,
640 path = "/{id}/students/{student}",
641 tag = "users",
642 security(("session_cookie" = [])),
643 params(
644 ("id" = String, Path, description = "Parent user id"),
645 ("student" = String, Path, description = "Student user id"),
646 ),
647 responses(
648 (status = 204, description = "Tie removed"),
649 (status = 401, description = "Not authenticated", body = ErrorResponse),
650 (status = 403, description = "Requires admin role", body = ErrorResponse),
651 (status = 404, description = "No such tie", body = ErrorResponse),
652 ),
653)]
654async fn unlink_student(
655 State(st): State<AppState>,
656 _admin: RequireAdmin,
657 Path((id, student)): Path<(String, String)>,
658) -> Result<StatusCode, AppError> {
659 if crate::service::parent_link::remove(
660 &st.db,
661 &UserId::from_key(&id),
662 &UserId::from_key(&student),
663 )
664 .await?
665 .is_none()
666 {
667 return Err(AppError::NotFound);
668 }
669 Ok(StatusCode::NO_CONTENT)
670}
671
672/// The students the calling parent observes, sorted by username. Requires the
673/// `parent` role. Each entry's reports live at `GET /marks/{user}`,
674/// `GET /attendance/{user}`, and `GET /pomodoro/{user}`. Paged via
675/// `?limit=&offset=`.
676#[utoipa::path(
677 get,
678 path = "/me/students",
679 tag = "users",
680 security(("session_cookie" = [])),
681 params(PageParams),
682 responses(
683 (status = 200, description = "A page of the caller's students", body = Page<PersonRef>),
684 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
685 (status = 401, description = "Not authenticated", body = ErrorResponse),
686 (status = 403, description = "Requires the parent role", body = ErrorResponse),
687 ),
688)]
689async fn my_students(
690 State(st): State<AppState>,
691 CurrentUser(user): CurrentUser,
692 Query(page): Query<PageParams>,
693) -> Result<Json<Page<PersonRef>>, AppError> {
694 if user.get_role() != Role::Parent {
695 return Err(AppError::Forbidden("requires the parent role"));
696 }
697 Ok(Json(students_page(user.get_id(), page, &st.db).await?))
698}
699
700// ---- the public profile -----------------------------------------------------
701// The school-wide read half of a user row: who they are, what they belong to,
702// and the counters that motivate. Deliberately *not* `UserResponse` — that one
703// carries email, phone, and birth date, which keep exactly the gate they have
704// today (self, teacher+, admin). Nothing here widens where they are reachable.
705
706/// A user's public profile. Contact details are not part of it, at any role.
707#[derive(Serialize, ToSchema)]
708struct ProfileResponse {
709 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
710 id: String,
711 #[schema(example = "ada")]
712 username: String,
713 /// The self-chosen `display_name`, falling back to `"Name Surname"`, then
714 /// `null` when the row carries neither.
715 #[schema(example = "Ada Lovelace")]
716 display_name: Option<String>,
717 role: RoleSchema,
718 #[schema(example = "Sınıfın en hızlı pomodorocusu.")]
719 bio: Option<String>,
720 /// Present only once a picture is uploaded; the bytes are at
721 /// `GET /users/{id}/avatar`.
722 avatar: Option<ProfileAvatar>,
723 /// At most `max_profile_classes` sections — the full list is at
724 /// `GET /classes/me`.
725 classes: Vec<ProfileClassRef>,
726 /// At most `max_profile_courses` courses, and only the ones the *reader*
727 /// may already read at `GET /courses/{id}` — a stranger sees an empty
728 /// block, the owner and manager+ see it whole. The full list is at
729 /// `GET /courses/me`.
730 courses: Vec<ProfileCourseRef>,
731 /// Every badge this account has earned, oldest first. Ids and stamps only —
732 /// the label and the icon are the client's, keyed by id off the `badges`
733 /// catalog at `GET /limits`.
734 badges: Vec<ProfileBadge>,
735 stats: ProfileStatsResponse,
736}
737
738/// One earned badge. Permanent: once it appears here it never leaves, even if
739/// the counter behind it falls back below the threshold that earned it.
740#[derive(Serialize, ToSchema)]
741struct ProfileBadge {
742 /// A catalog id from `GET /limits` — `badges.catalog[].id`.
743 #[schema(example = "pomodoro_finished_10")]
744 id: String,
745 /// When it was *first* earned, UTC unix-milliseconds. Later syncs never
746 /// move it.
747 #[schema(example = 1_759_000_000_000_i64)]
748 earned_at: i64,
749}
750
751/// What a stored avatar is, without its bytes.
752#[derive(Serialize, ToSchema)]
753struct ProfileAvatar {
754 #[schema(example = "image/png")]
755 content_type: String,
756 /// Size in bytes.
757 #[schema(example = 20_480)]
758 size: i64,
759}
760
761/// A class section as a profile shows it: the label, and nothing about who runs
762/// it. The office-side view (creator, homeroom teacher) stays behind
763/// `GET /classes/{id}`, which is teacher+.
764#[derive(Serialize, ToSchema)]
765struct ProfileClassRef {
766 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
767 id: String,
768 #[schema(example = "9-A")]
769 name: String,
770 #[schema(example = "9")]
771 grade: Option<String>,
772}
773
774/// A course as a profile shows it — a label, nothing more.
775#[derive(Serialize, ToSchema)]
776struct ProfileCourseRef {
777 #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
778 id: String,
779 #[schema(example = "Matematik")]
780 title: String,
781 /// `course`, `study` (etüt), or `club` (kulüp).
782 #[schema(example = "course")]
783 kind: String,
784}
785
786/// The motivational counters. Derived, never settable, and never `null`: an
787/// account with no rows behind a counter reads a true `0`.
788///
789/// Two kinds live here. The first four are **computed at read time** from the
790/// rows that exist right now, so deleting the rows moves them down. Every
791/// `*_total` one is a **stored lifetime counter**, incremented as the work
792/// happens and never recomputed — they can therefore outlive the rows behind
793/// them (an exam deleted by its teacher still counts as sat), which is exactly
794/// why a badge earned off them stays earned. Each is named for a `stat` of the
795/// badge catalog at `GET /limits`, plus `_total`, and that spelling is the join
796/// a client makes between the two surfaces — so the suffix is on the key even
797/// where the counter is not a running total (`study_streak_total` is a longest,
798/// not a sum).
799///
800/// Some are staff counters and some student ones; a role that never does the
801/// work simply reads zero, which is why no key is conditional.
802///
803/// Every number here is the **owner's** true total for every reader, never
804/// narrowed per viewer — deliberately so even where the rows behind it sit
805/// behind a gate this reader would fail (`GET /pomodoro/{id}`,
806/// `GET /marks/user/{id}`, `GET /attendance/user/{id}`). A magnitude names no
807/// course, class, lesson or exam, and a per-reader counter would make one
808/// profile read differently to different people.
809#[derive(Serialize, ToSchema)]
810struct ProfileStatsResponse {
811 /// Finished pomodoro stints; an open one counts for nothing.
812 pomodoro_sessions: i64,
813 /// Total focused milliseconds across those stints.
814 pomodoro_focus_ms: i64,
815 /// Every course behind the `courses` block, not just the embedded window.
816 courses: i64,
817 /// Every class behind the `classes` block, not just the embedded window.
818 classes: i64,
819 /// Lifetime homework hand-ins. Withdrawing a submission gives one back;
820 /// editing one moves nothing.
821 homework_submitted_total: i64,
822 /// Lifetime hand-ins made before their deadline, judged at hand-in.
823 homework_on_time_total: i64,
824 /// Lifetime exams sat, counted at the first sitting of each exam — a retake
825 /// moves nothing, and deleting the exam does not take one back.
826 exam_sat_total: i64,
827 /// Lifetime finished pomodoro stints.
828 pomodoro_finished_total: i64,
829 /// Lifetime focused milliseconds.
830 pomodoro_focus_ms_total: i64,
831 /// Lifetime grades this teacher recorded — exam sittings and homework
832 /// submissions alike, once per pair: a regrade moves nothing, and deleting
833 /// the grade gives it back.
834 marks_given_total: i64,
835 /// Lifetime lessons this teacher held, credited by the **first roll call
836 /// taken at or after the lesson's own `starts_at`** — a lesson scheduled
837 /// and cancelled counts for nothing, and neither does one marked before it
838 /// has begun.
839 lessons_held_total: i64,
840 /// Lifetime pool questions this teacher approved.
841 pool_approved_total: i64,
842 /// Lifetime questions of this author that reached the school-wide pool,
843 /// counted when the approval lands.
844 pool_published_total: i64,
845 /// Lifetime lesson roll calls that put this **student** `present` or
846 /// `late`; a correction to any other status takes one back. Daily and event
847 /// attendance moves it not at all.
848 lessons_attended_total: i64,
849 /// Lifetime exam marks at or above the high-mark cut published as
850 /// `badges.high_mark_min` on `GET /limits`, one per graded sitting;
851 /// deleting the mark gives it back, like the grader's own counter.
852 /// Homework marks never count — they are optional and often status-only.
853 high_mark_total: i64,
854 /// Longest run of consecutive study days ever held — a high-water mark, so
855 /// breaking the run never brings it down. Days end at midnight UTC.
856 study_streak_total: i64,
857}
858
859/// Build one profile as `viewer` may see it. The course block is chosen off the
860/// owner's **live** role, not off the `creator`/`teachers` columns: those are
861/// historical and no demotion sweeps them, so a demoted ex-teacher lists what
862/// they are enrolled in, like any other student.
863///
864/// A course carries a title, and `GET /courses/{id}` hands that title only to
865/// the enrolled, the staff who run it, and manager+ — so the block is
866/// intersected with [`visible_courses`], the same catalog `GET /courses`
867/// serves. Reading your own profile, or reading as manager+, needs no
868/// intersection: both already see the whole list.
869///
870/// The class block answers to [`ensure_can_observe`], the gate
871/// `GET /classes/user/{id}` holds — teacher+, or a parent linked to the target
872/// — because every other `/classes` read is teacher+ and a class name and grade
873/// are exactly what those routes withhold. That gate is all-or-nothing rather
874/// than per class, so a viewer who fails it gets an empty block, not a 403: the
875/// rest of the profile is still public to them.
876///
877/// So no *named* thing here crosses a gate the viewer would fail directly. The
878/// magnitudes deliberately do — **every** one of them, not just the two that
879/// count the gated blocks. `stats.courses` and `stats.classes` are the obvious
880/// pair; `pomodoro_focus_ms` and `pomodoro_focus_ms_total` are byte-identical
881/// to the `total_focus_ms` that `GET /pomodoro/{id}` serves behind
882/// [`ensure_can_observe`]; and `lessons_attended_total`,
883/// `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and
884/// `high_mark_total` are magnitudes of the same report data that gate holds —
885/// for a reader who is exactly [`Role::Teacher`] they are in fact *wider* than
886/// the reports themselves, which [`crate::web::marks`] and
887/// [`crate::web::attendance`] narrow to the courses that teacher manages.
888///
889/// That is the decision, not an oversight: every magnitude in `stats` is the
890/// owner's true total for every reader. They are the motivational counters, a
891/// per-reader number would make one profile read differently to different
892/// people, and a magnitude names no course, no class, no lesson and no exam —
893/// the *named* things stay behind their own gates, above.
894async fn profile_of(
895 st: &AppState,
896 user: &User,
897 viewer: &User,
898) -> Result<ProfileResponse, AppError> {
899 let id = user.get_id();
900 // One catalog read per request, never one authorization call per course.
901 let readable = match viewer.get_id() == id || viewer.get_role().at_least(Role::Manager) {
902 true => None,
903 false => Some(
904 visible_courses(viewer, &st.db)
905 .await?
906 .iter()
907 .map(|course| course.get_id().clone())
908 .collect::<Vec<_>>(),
909 ),
910 };
911 // The window is cut after the intersection, so a filtered viewer still gets
912 // up to `MAX_PROFILE_COURSES` courses they can actually see.
913 let (mut courses, course_total) = match user.get_role().at_least(Role::Teacher) {
914 // The teacher read is unpaged, so the total is what came back.
915 true => {
916 let courses = crate::service::course::list_for_teacher(&st.db, id).await?;
917 let total = courses.len() as i64;
918 (courses, total)
919 }
920 // Unfiltered readers can take the window from the database.
921 false => {
922 let window = readable.is_none().then_some(MAX_PROFILE_COURSES as i64);
923 crate::service::course::list_enrolled(&st.db, id, window, 0).await?
924 }
925 };
926 if let Some(readable) = &readable {
927 courses.retain(|course| readable.contains(course.get_id()));
928 }
929 courses.truncate(MAX_PROFILE_COURSES);
930 let (mut members, class_total) = crate::service::class_member::list_for_user(
931 &st.db,
932 id,
933 Some(MAX_PROFILE_CLASSES as i64),
934 0,
935 )
936 .await?;
937 // The window is safe to take from the database here: the class gate is
938 // all-or-nothing, so it drops the whole page or none of it — never a row
939 // out of the middle of one.
940 if viewer.get_id() != id && ensure_can_observe(viewer, id, &st.db).await.is_err() {
941 members.clear();
942 }
943 let class_ids: Vec<ClassGroupId> = members.iter().map(|row| row.get_class().clone()).collect();
944 let classes = crate::service::class_group::list_by_ids(&st.db, &class_ids).await?;
945 // Both totals are the full counts, not the windowed ones — the blocks are a
946 // preview, the stats are the truth.
947 let stats = crate::service::profile::load(&st.db, id, course_total, class_total).await?;
948 let badges = badges_of(st, id, &stats).await?;
949 Ok(ProfileResponse {
950 id: id.key().to_string(),
951 username: user.get_username().as_str().to_string(),
952 // The whole three-step resolve lives in `PersonRef` — one spelling of
953 // it, so this profile and every embedded person ref cannot disagree.
954 display_name: PersonRef::new(user).display_name,
955 role: user.get_role().into(),
956 bio: user.get_bio().map(|bio| bio.as_str().to_string()),
957 avatar: user
958 .get_avatar_content_type()
959 .map(|content_type| ProfileAvatar {
960 content_type: content_type.as_str().to_string(),
961 size: user.get_avatar_size().unwrap_or_default(),
962 }),
963 classes: classes
964 .iter()
965 .map(|class| ProfileClassRef {
966 id: class.get_id().key().to_string(),
967 name: class.get_name().as_str().to_string(),
968 grade: class.get_grade().map(|grade| grade.as_str().to_string()),
969 })
970 .collect(),
971 courses: courses
972 .iter()
973 .map(|course| ProfileCourseRef {
974 id: course.get_id().key().to_string(),
975 title: course.get_title().as_str().to_string(),
976 kind: course.get_kind().as_str().to_string(),
977 })
978 .collect(),
979 badges: badges
980 .iter()
981 .map(|award| ProfileBadge {
982 id: award.get_badge().to_string(),
983 earned_at: award.get_earned_at().as_millis(),
984 })
985 .collect(),
986 stats: ProfileStatsResponse {
987 pomodoro_sessions: stats.get_pomodoro_sessions(),
988 pomodoro_focus_ms: stats.get_pomodoro_focus_ms(),
989 courses: stats.get_courses(),
990 classes: stats.get_classes(),
991 homework_submitted_total: stats.get_totals().get_homework_submitted(),
992 homework_on_time_total: stats.get_totals().get_homework_on_time(),
993 exam_sat_total: stats.get_totals().get_exam_sat(),
994 pomodoro_finished_total: stats.get_totals().get_pomodoro_finished(),
995 pomodoro_focus_ms_total: stats.get_totals().get_pomodoro_focus_ms(),
996 marks_given_total: stats.get_totals().get_marks_given(),
997 lessons_held_total: stats.get_totals().get_lessons_held(),
998 pool_approved_total: stats.get_totals().get_pool_approved(),
999 pool_published_total: stats.get_totals().get_pool_published(),
1000 lessons_attended_total: stats.get_totals().get_lessons_attended(),
1001 high_mark_total: stats.get_totals().get_high_mark(),
1002 study_streak_total: stats.get_totals().get_study_streak(),
1003 },
1004 })
1005}
1006
1007/// The owner's earned badges, and the backstop that keeps them honest.
1008///
1009/// Every write that moves a counter syncs the badges behind it, so in the
1010/// steady state the earned set holds nothing the award rows do not already
1011/// carry and this is one read and **no write at all**. Only a threshold crossed
1012/// by a path whose sync was lost — a transient database error, which those
1013/// callers log and swallow on purpose — leaves a gap, and that heals here on
1014/// the next profile read of that account.
1015///
1016/// Nothing here revokes: [`badge::sync`] only ever adds, so a counter that has
1017/// since fallen back below its threshold leaves the badge standing. The sync's
1018/// own error is logged and dropped, and the awards already read are served —
1019/// a decoration may not fail the profile it decorates.
1020async fn badges_of(
1021 st: &AppState,
1022 user: &UserId,
1023 stats: &ProfileStats,
1024) -> Result<Vec<BadgeAward>, AppError> {
1025 let awards = crate::service::badge::list_for(&st.db, user).await?;
1026 let complete = badge::earned(stats.get_totals())
1027 .iter()
1028 .all(|id| awards.iter().any(|award| award.get_badge() == *id));
1029 if complete {
1030 return Ok(awards);
1031 }
1032 if let Err(err) = crate::service::badge::sync(&st.db, user).await {
1033 tracing::warn!("failed to sync badges for {}: {err}", user.key());
1034 return Ok(awards);
1035 }
1036 // Re-read so the badge just healed appears on *this* response, stamp and
1037 // all, rather than only on the next one.
1038 crate::service::badge::list_for(&st.db, user).await
1039}
1040
1041/// The profile gate: any authenticated account reads any profile — except a
1042/// parent, who is an observer of their own children and of nobody else. The
1043/// link alone is not the grant either; [`ensure_can_observe`] re-reads the
1044/// target's live role, so a student who was promoted out stops being readable.
1045async fn ensure_may_read_profile(
1046 caller: &User,
1047 target: &UserId,
1048 db: &Database,
1049) -> Result<(), AppError> {
1050 if caller.get_role() == Role::Parent && caller.get_id() != target {
1051 ensure_can_observe(caller, target, db).await?;
1052 }
1053 Ok(())
1054}
1055
1056/// The target's row, 404 if it is gone, once the caller is allowed to see it.
1057async fn readable_profile_user(st: &AppState, caller: &User, id: &str) -> Result<User, AppError> {
1058 let target = UserId::from_key(id);
1059 ensure_may_read_profile(caller, &target, &st.db).await?;
1060 crate::service::user::read(&st.db, &target)
1061 .await?
1062 .ok_or(AppError::NotFound)
1063}
1064
1065/// The caller's own public profile — what everyone else sees of them.
1066#[utoipa::path(
1067 get,
1068 path = "/me/profile",
1069 tag = "users",
1070 security(("session_cookie" = [])),
1071 responses(
1072 (status = 200, description = "The caller's profile", body = ProfileResponse),
1073 (status = 401, description = "Not authenticated", body = ErrorResponse),
1074 ),
1075)]
1076async fn my_profile(
1077 State(st): State<AppState>,
1078 CurrentUser(user): CurrentUser,
1079) -> Result<Json<ProfileResponse>, AppError> {
1080 Ok(Json(profile_of(&st, &user, &user).await?))
1081}
1082
1083/// One user's public profile: display name, bio, avatar meta, their class and
1084/// course blocks, the badges they have earned, and the motivational counters.
1085/// Badges carry an id and the instant they were first earned; their labels and
1086/// icons come from the `badges` catalog at `GET /limits`. Readable by every
1087/// authenticated account — except a parent, who reads only their own and their
1088/// linked students'. Never carries email, phone, or birth date; those stay on
1089/// `GET /users/{id}` (admin) and `GET /auth/me`. The embedded blocks are capped
1090/// at `max_profile_classes` / `max_profile_courses` (see `GET /limits`) — the
1091/// full paged lists are `GET /classes/me` and `GET /courses/me`. The course
1092/// block is also cut to what the *reader* may already see: only courses they
1093/// would pass `GET /courses/{id}` on. The class block holds the same bar as
1094/// `GET /classes/user/{id}` — teacher+, a parent linked to this student, or the
1095/// owner themselves; every other reader gets an empty `classes` array rather
1096/// than a 403. Every number in `stats` stays the owner's true total either way,
1097/// including the ones whose underlying reports are gated (`/pomodoro/{id}`,
1098/// `/marks/user/{id}`, `/attendance/user/{id}`): they are motivational
1099/// counters, and a magnitude names no course, class, lesson or exam.
1100#[utoipa::path(
1101 get,
1102 path = "/{id}/profile",
1103 tag = "users",
1104 security(("session_cookie" = [])),
1105 params(("id" = String, Path, description = "User id")),
1106 responses(
1107 (status = 200, description = "The user's profile", body = ProfileResponse),
1108 (status = 401, description = "Not authenticated", body = ErrorResponse),
1109 (status = 403, description = "A parent without a link to this student", body = ErrorResponse),
1110 (status = 404, description = "User not found", body = ErrorResponse),
1111 ),
1112)]
1113async fn get_user_profile(
1114 State(st): State<AppState>,
1115 CurrentUser(caller): CurrentUser,
1116 Path(id): Path<String>,
1117) -> Result<Json<ProfileResponse>, AppError> {
1118 let target = readable_profile_user(&st, &caller, &id).await?;
1119 Ok(Json(profile_of(&st, &target, &caller).await?))
1120}
1121
1122// ---- the avatar -------------------------------------------------------------
1123// One optional picture per user, the same one-image-on-the-owning-row shape the
1124// question pool uses: bytes on disk under a server-generated ULID, metadata on
1125// the user row. Every write here must take the replaced blob off disk — no
1126// route deletes a user, so nothing else would ever collect it.
1127
1128/// Upload (or replace) the caller's own avatar. `multipart/form-data` with the
1129/// image under a `file` field; the declared content type must be `image/png`,
1130/// `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the
1131/// bytes at most the school's `max_file_bytes` (settings). Replacing one drops
1132/// the previous picture.
1133#[utoipa::path(
1134 post,
1135 path = "/me/avatar",
1136 tag = "users",
1137 security(("session_cookie" = [])),
1138 request_body(content = UploadFileForm, content_type = "multipart/form-data"),
1139 responses(
1140 (status = 201, description = "Avatar stored", body = ProfileAvatar),
1141 (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse),
1142 (status = 401, description = "Not authenticated", body = ErrorResponse),
1143 (status = 404, description = "The account no longer exists", body = ErrorResponse),
1144 (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse),
1145 ),
1146)]
1147async fn upload_my_avatar(
1148 State(st): State<AppState>,
1149 CurrentUser(user): CurrentUser,
1150 mut multipart: Multipart,
1151) -> Result<(StatusCode, Json<ProfileAvatar>), AppError> {
1152 let upload = read_image_upload(&st, &mut multipart).await?;
1153 let size = upload.size();
1154
1155 let file = crate::domain::monotonic_id::next_uuid().to_string();
1156 store_blob(&st, &file, &upload.data, || async {
1157 match crate::service::user::set_avatar(
1158 &st.db,
1159 user.get_id(),
1160 &file,
1161 &upload.content_type,
1162 size,
1163 )
1164 .await?
1165 {
1166 // Row written; the picture this one replaced comes off disk.
1167 Some(before) => Ok(((), before.get_avatar_file().map(str::to_string))),
1168 // The account went away mid-upload — the fresh blob is an orphan.
1169 None => Err(AppError::NotFound),
1170 }
1171 })
1172 .await?;
1173 Ok((
1174 StatusCode::CREATED,
1175 Json(ProfileAvatar {
1176 content_type: upload.content_type.as_str().to_string(),
1177 size,
1178 }),
1179 ))
1180}
1181
1182/// The caller's own avatar bytes. The self alias of `GET /{id}/avatar` — the
1183/// static `/me/avatar` segment wins over `/{id}/avatar` in the router, so
1184/// without this a client that never learned its own id gets a bodyless `405`
1185/// on the obvious route. It serves the caller's own row and nothing else, so
1186/// it asks no gate: the session already proves the reach.
1187#[utoipa::path(
1188 get,
1189 path = "/me/avatar",
1190 tag = "users",
1191 security(("session_cookie" = [])),
1192 responses(
1193 (status = 200, description = "The image bytes", content_type = "image/*"),
1194 (status = 401, description = "Not authenticated", body = ErrorResponse),
1195 (status = 404, description = "The caller has no avatar", body = ErrorResponse),
1196 ),
1197)]
1198async fn get_my_avatar(
1199 State(st): State<AppState>,
1200 CurrentUser(user): CurrentUser,
1201) -> Result<Response, AppError> {
1202 serve_avatar(&st, &user).await
1203}
1204
1205/// The avatar bytes. Same reach as the profile itself: every authenticated
1206/// account, except a parent, who is limited to their own and their linked
1207/// students'.
1208#[utoipa::path(
1209 get,
1210 path = "/{id}/avatar",
1211 tag = "users",
1212 security(("session_cookie" = [])),
1213 params(("id" = String, Path, description = "User id")),
1214 responses(
1215 (status = 200, description = "The image bytes", content_type = "image/*"),
1216 (status = 401, description = "Not authenticated", body = ErrorResponse),
1217 (status = 403, description = "A parent without a link to this student", body = ErrorResponse),
1218 (status = 404, description = "No such user, or they have no avatar", body = ErrorResponse),
1219 ),
1220)]
1221async fn get_avatar(
1222 State(st): State<AppState>,
1223 CurrentUser(caller): CurrentUser,
1224 Path(id): Path<String>,
1225) -> Result<Response, AppError> {
1226 let target = readable_profile_user(&st, &caller, &id).await?;
1227 serve_avatar(&st, &target).await
1228}
1229
1230/// The shared tail of both avatar reads: the bytes, or a `404` when the row
1231/// carries none. The caller owns the gate — this one is reached already.
1232async fn serve_avatar(st: &AppState, user: &User) -> Result<Response, AppError> {
1233 match (user.get_avatar_file(), user.get_avatar_content_type()) {
1234 (Some(file), Some(content_type)) => {
1235 serve_inline_blob(&st.files_path, file, content_type).await
1236 }
1237 _ => Err(AppError::NotFound),
1238 }
1239}
1240
1241/// Remove the caller's own avatar.
1242#[utoipa::path(
1243 delete,
1244 path = "/me/avatar",
1245 tag = "users",
1246 security(("session_cookie" = [])),
1247 responses(
1248 (status = 204, description = "Avatar removed"),
1249 (status = 401, description = "Not authenticated", body = ErrorResponse),
1250 (status = 404, description = "No avatar to remove", body = ErrorResponse),
1251 ),
1252)]
1253async fn delete_my_avatar(
1254 State(st): State<AppState>,
1255 CurrentUser(user): CurrentUser,
1256) -> Result<StatusCode, AppError> {
1257 drop_avatar(&st, user.get_id()).await
1258}
1259
1260/// Remove any user's avatar. Admin only — the moderation path: an offensive
1261/// picture is a school problem, and no route deletes the account it hangs on.
1262#[utoipa::path(
1263 delete,
1264 path = "/{id}/avatar",
1265 tag = "users",
1266 security(("session_cookie" = [])),
1267 params(("id" = String, Path, description = "User id")),
1268 responses(
1269 (status = 204, description = "Avatar removed"),
1270 (status = 401, description = "Not authenticated", body = ErrorResponse),
1271 (status = 403, description = "Requires admin role", body = ErrorResponse),
1272 (status = 404, description = "No such user, or no avatar to remove", body = ErrorResponse),
1273 ),
1274)]
1275async fn delete_avatar(
1276 State(st): State<AppState>,
1277 _admin: RequireAdmin,
1278 Path(id): Path<String>,
1279) -> Result<StatusCode, AppError> {
1280 drop_avatar(&st, &UserId::from_key(&id)).await
1281}
1282
1283/// Clear the row's avatar and take its blob off disk — the shared tail of the
1284/// self and moderation deletes. A row without one (or no row at all) is a 404.
1285async fn drop_avatar(st: &AppState, user: &UserId) -> Result<StatusCode, AppError> {
1286 let before = crate::service::user::clear_avatar(&st.db, user)
1287 .await?
1288 .ok_or(AppError::NotFound)?;
1289 let Some(file) = before.get_avatar_file() else {
1290 return Err(AppError::NotFound);
1291 };
1292 remove_blob(&st.files_path, file).await;
1293 Ok(StatusCode::NO_CONTENT)
1294}