forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB08aa13eAhmet Kaan Gümüş2 months ago378 commits

users.rs1289 lines, 55.5 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::{ClassGroup, ClassGroupId};
18use crate::domain::class_member::ClassMember;
19
20use crate::domain::preferences::{Language, PaletteColor, Theme};
21use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone, ProfileStats};
22use crate::domain::role::Role;
23use crate::domain::user::{User, UserId};
24use crate::error::{AppError, ErrorResponse, ValidationError};
25use crate::service::parent_link::ensure_can_observe;
26use crate::state::AppState;
27
28use super::courses::visible_courses;
29use super::dto::AssignableRole;
30use super::dto::Role as RoleSchema;
31use super::{
32 CurrentUser, Page, PageParams, PersonRef, RequireAdmin, UploadFileForm, UserResponse, paginate,
33 read_image_upload, remove_blob, serve_inline_blob, store_blob,
34};
35
36pub fn routes() -> OpenApiRouter<AppState> {
37 OpenApiRouter::new()
38 .routes(routes!(list_users))
39 .routes(routes!(update_my_profile))
40 .routes(routes!(update_my_preferences))
41 .routes(routes!(my_students))
42 .routes(routes!(my_profile))
43 .routes(routes!(search_users))
44 .routes(routes!(get_user))
45 .routes(routes!(set_role))
46 .routes(routes!(update_user_profile, get_user_profile))
47 .routes(routes!(update_user_preferences))
48 .routes(routes!(link_student, list_parent_students))
49 .routes(routes!(unlink_student))
50 // The avatar routes get their own HTTP body cap, like the note-file and
51 // question-image ones: the server-wide hard ceiling plus multipart
52 // framing headroom. It must stay on this sub-router — on the whole
53 // `/users` router every JSON endpoint would start accepting 25 MB.
54 .merge(
55 OpenApiRouter::new()
56 .routes(routes!(upload_my_avatar, get_my_avatar, delete_my_avatar))
57 .routes(routes!(get_avatar, delete_avatar))
58 .layer(DefaultBodyLimit::max(
59 MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES,
60 )),
61 )
62}
63
64#[derive(Deserialize, ToSchema)]
65struct SetRole {
66 /// The role to assign. Deserialized as a string so an unknown value returns a
67 /// uniform `400`; documented as the `AssignableRole` enum so the docs list
68 /// exactly the choices the server accepts (the response-side `Role` also
69 /// names the `ai` service principal, which this endpoint has always refused).
70 #[schema(value_type = AssignableRole, example = "teacher")]
71 role: String,
72}
73
74/// Partial personal-info update. Per field: omitted (or `null`) keeps the
75/// current value, an empty string clears it, anything else is validated and set.
76#[derive(Deserialize, ToSchema)]
77struct UpdateProfile {
78 #[schema(example = "Ada", max_length = 100)]
79 name: Option<String>,
80 #[schema(example = "Lovelace", max_length = 100)]
81 surname: Option<String>,
82 #[schema(example = "ada@example.com", max_length = 254)]
83 email: Option<String>,
84 /// Any punctuation and spacing; it is the digit count that must land in
85 /// `7`–`15`, so no character-length bound applies.
86 #[schema(example = "+90 555 123 45 67")]
87 phone: Option<String>,
88 /// Birth date in `YYYY-MM-DD` form.
89 #[schema(example = "1990-01-02")]
90 birth_date: Option<String>,
91 /// The name the public profile is shown under, instead of the legal one.
92 #[schema(example = "Ada", max_length = 50)]
93 display_name: Option<String>,
94 /// Free text under the profile's name.
95 #[schema(example = "Sınıfın en hızlı pomodorocusu.", max_length = 500)]
96 bio: Option<String>,
97}
98
99/// Partial UI-preference update. Same field semantics as [`UpdateProfile`]:
100/// omitted (or `null`) keeps the current value, an empty string clears it back
101/// to "never chose" (the client then follows the device preference), anything
102/// else is validated and set.
103#[derive(Deserialize, ToSchema)]
104struct UpdatePreferences {
105 /// `light` or `dark`.
106 #[schema(example = "dark")]
107 theme: Option<String>,
108 /// `tr` or `en` (ISO 639-1).
109 #[schema(example = "tr")]
110 language: Option<String>,
111 /// Accent color as a 6-digit hex with a leading `#`; stored lowercase. Any
112 /// valid hex, not a fixed palette.
113 #[schema(example = "#fefae0")]
114 palette_color: Option<String>,
115}
116
117/// Resolve one patched field into what the save should write: absent (or
118/// `null`) is `None` — the column is not written at all, so a concurrent PATCH
119/// of it survives; `""` is `Some(None)`, an explicit clear; anything else must
120/// parse into the domain newtype, exactly as a create would.
121fn merge_field<T>(
122 patch: Option<&str>,
123 parse: impl Fn(&str) -> Result<T, ValidationError>,
124) -> Result<Option<Option<T>>, ValidationError> {
125 match patch {
126 None => Ok(None),
127 Some("") => Ok(Some(None)),
128 Some(value) => Ok(Some(Some(parse(value)?))),
129 }
130}
131
132/// Validate and persist exactly the info fields `req` carried — nothing is
133/// merged from `user`'s snapshot, so a concurrent PATCH of another field is not
134/// reverted. Shared by the self-service and admin profile endpoints — they
135/// differ only in whose row they load and who may call them.
136async fn apply_profile(
137 user: User,
138 req: &UpdateProfile,
139 db: &Database,
140) -> Result<UserResponse, AppError> {
141 let name = merge_field(req.name.as_deref(), |v| PersonName::try_new("name", v))?;
142 let surname = merge_field(req.surname.as_deref(), |v| {
143 PersonName::try_new("surname", v)
144 })?;
145 let email = merge_field(req.email.as_deref(), Email::try_new)?;
146 let phone = merge_field(req.phone.as_deref(), Phone::try_new)?;
147 let birth_date = merge_field(req.birth_date.as_deref(), BirthDate::try_new)?;
148 let display_name = merge_field(req.display_name.as_deref(), DisplayName::try_new)?;
149 let bio = merge_field(req.bio.as_deref(), Bio::try_new)?;
150 let updated = crate::service::user::set_profile(
151 db,
152 user.get_id(),
153 name,
154 surname,
155 email,
156 phone,
157 birth_date,
158 display_name,
159 bio,
160 )
161 .await?;
162 Ok(UserResponse::new(&updated))
163}
164
165/// Validate and persist exactly the preference fields `req` carried — same
166/// no-merge reasoning as [`apply_profile`]. Shared by the
167/// self-service and admin preference endpoints — they differ only in whose row
168/// they load and who may call them.
169async fn apply_preferences(
170 user: User,
171 req: &UpdatePreferences,
172 db: &Database,
173) -> Result<UserResponse, AppError> {
174 let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?;
175 let language = merge_field(req.language.as_deref(), Language::try_from_str)?;
176 let palette_color = merge_field(req.palette_color.as_deref(), PaletteColor::try_from_str)?;
177 let updated =
178 crate::service::user::set_preferences(db, user.get_id(), theme, language, palette_color)
179 .await?;
180 Ok(UserResponse::new(&updated))
181}
182
183#[derive(Deserialize, IntoParams)]
184struct SearchUsers {
185 /// Case-insensitive fragment of a username, name, or surname. May be
186 /// blank when `role` is given — that lists the whole role.
187 q: String,
188 /// Restrict matches to one role: `parent`, `student`, `teacher`,
189 /// `manager`, or `admin`. Omit to search every role.
190 role: Option<String>,
191 /// Max matches to return. Omit for every match; when given, `1`–`500`.
192 #[param(minimum = 1, maximum = 500, example = 100)]
193 limit: Option<i64>,
194 /// Matches to skip from the start. Defaults to `0`.
195 #[param(minimum = 0, example = 0)]
196 offset: Option<i64>,
197}
198
199/// Find users by username or name — backs the pickers (enroll, grade, mark
200/// attendance) and, for a student or parent, the one way to find the staff
201/// member they are allowed to message. Any authenticated user may ask; a
202/// caller below teacher only ever sees the roles they may message (teacher,
203/// manager, admin), in the items *and* in `total`. `role` narrows to one role
204/// (e.g. `role=student` for an enroll picker) — a student or parent naming a
205/// role they may not message is refused; a blank `q` with a `role` lists
206/// everyone in that role. Paged via `?limit=&offset=` like the other lists
207/// (omit `limit` for every match); returns a `{items, total, limit, offset}`
208/// envelope carrying only id/username/display name — no contact details.
209#[utoipa::path(
210 get,
211 path = "/search",
212 tag = "users",
213 security(("session_cookie" = [])),
214 params(SearchUsers),
215 responses(
216 (status = 200, description = "A page of matching users (all matches when unpaged)", body = Page<PersonRef>),
217 (status = 400, description = "Blank query without a role, unknown role, or invalid limit/offset", body = ErrorResponse),
218 (status = 401, description = "Not authenticated", body = ErrorResponse),
219 (status = 403, description = "A student or parent asked for a role they may not message", body = ErrorResponse),
220 ),
221)]
222async fn search_users(
223 State(st): State<AppState>,
224 CurrentUser(user): CurrentUser,
225 Query(req): Query<SearchUsers>,
226) -> Result<Json<Page<PersonRef>>, AppError> {
227 if req.q.trim().is_empty() && req.role.is_none() {
228 return Err(AppError::Validation(ValidationError::Invalid {
229 field: "q",
230 reason: "must not be empty unless role is given",
231 }));
232 }
233 let (limit, offset) = PageParams {
234 limit: req.limit,
235 offset: req.offset,
236 }
237 .resolve()?;
238 let role = req.role.as_deref().map(Role::try_from_str).transpose()?;
239 // Below staff the caller may only see whom they may write to. Asking for a
240 // role outside that set is a refusal, not a silently empty page.
241 let allowed = user.get_role().messageable_roles();
242 if let (Some(allowed), Some(role)) = (allowed, role)
243 && !allowed.contains(&role)
244 {
245 return Err(AppError::Forbidden(
246 "students and parents may only search staff (teacher or higher)",
247 ));
248 }
249 let (users, total) =
250 crate::service::user::search(&st.db, &req.q, role, allowed, limit, offset).await?;
251 let items = users.iter().map(PersonRef::new).collect();
252 Ok(Json(Page::new(items, total, limit, offset)))
253}
254
255/// List every user with their role, newest first. Admin only. Paged: pass
256/// `?limit=&offset=` to take a window (omit `limit` for the whole list); the
257/// response is a `{items, total, limit, offset}` envelope where `total` counts
258/// every user.
259#[utoipa::path(
260 get,
261 path = "/",
262 tag = "users",
263 security(("session_cookie" = [])),
264 params(PageParams),
265 responses(
266 (status = 200, description = "A page of users (the full list when unpaged)", body = Page<UserResponse>),
267 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
268 (status = 401, description = "Not authenticated", body = ErrorResponse),
269 (status = 403, description = "Requires admin role", body = ErrorResponse),
270 ),
271)]
272async fn list_users(
273 State(st): State<AppState>,
274 _admin: RequireAdmin,
275 Query(page): Query<PageParams>,
276) -> Result<Json<Page<UserResponse>>, AppError> {
277 let (limit, offset) = page.resolve()?;
278 let (users, total) = crate::service::user::list_all(&st.db, limit, offset).await?;
279 let items = users.iter().map(UserResponse::new).collect();
280 Ok(Json(Page::new(items, total, limit, offset)))
281}
282
283/// Update the caller's own personal info: name, surname, email, phone, birth
284/// date, plus the public-profile pair `display_name` and `bio` (both readable
285/// school-wide at `GET /users/{id}/profile`, unlike the contact fields). Any
286/// authenticated role. Omitted fields stay as they are; an empty string clears
287/// a field.
288#[utoipa::path(
289 patch,
290 path = "/me",
291 tag = "users",
292 security(("session_cookie" = [])),
293 request_body = UpdateProfile,
294 responses(
295 (status = 200, description = "Updated user", body = UserResponse),
296 (status = 400, description = "Invalid field", body = ErrorResponse),
297 (status = 401, description = "Not authenticated", body = ErrorResponse),
298 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
299 ),
300)]
301async fn update_my_profile(
302 State(st): State<AppState>,
303 CurrentUser(user): CurrentUser,
304 Json(req): Json<UpdateProfile>,
305) -> Result<Json<UserResponse>, AppError> {
306 Ok(Json(apply_profile(user, &req, &st.db).await?))
307}
308
309/// Update the caller's own UI preferences: `theme` (`light`/`dark`),
310/// `language` (`tr`/`en`), and `palette_color` (accent color as `#rrggbb`).
311/// Any authenticated role. Omitted fields stay as they
312/// are; an empty string clears one back to "never chose" (the client then
313/// follows the device preference). Read them back on any user response, e.g.
314/// `GET /auth/me`.
315#[utoipa::path(
316 patch,
317 path = "/me/preferences",
318 tag = "users",
319 security(("session_cookie" = [])),
320 request_body = UpdatePreferences,
321 responses(
322 (status = 200, description = "Updated user", body = UserResponse),
323 (status = 400, description = "Invalid theme, language, or palette color", body = ErrorResponse),
324 (status = 401, description = "Not authenticated", body = ErrorResponse),
325 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
326 ),
327)]
328async fn update_my_preferences(
329 State(st): State<AppState>,
330 CurrentUser(user): CurrentUser,
331 Json(req): Json<UpdatePreferences>,
332) -> Result<Json<UserResponse>, AppError> {
333 Ok(Json(apply_preferences(user, &req, &st.db).await?))
334}
335
336/// Fetch one user with their role and personal info. Admin only.
337#[utoipa::path(
338 get,
339 path = "/{id}",
340 tag = "users",
341 security(("session_cookie" = [])),
342 params(("id" = String, Path, description = "User id")),
343 responses(
344 (status = 200, description = "The user", body = UserResponse),
345 (status = 401, description = "Not authenticated", body = ErrorResponse),
346 (status = 403, description = "Requires admin role", body = ErrorResponse),
347 (status = 404, description = "User not found", body = ErrorResponse),
348 ),
349)]
350async fn get_user(
351 State(st): State<AppState>,
352 _admin: RequireAdmin,
353 Path(id): Path<String>,
354) -> Result<Json<UserResponse>, AppError> {
355 let user = crate::service::user::read(&st.db, &UserId::from_key(&id))
356 .await?
357 .ok_or(AppError::NotFound)?;
358 Ok(Json(UserResponse::new(&user)))
359}
360
361/// Update any user's personal info. Admin only — the school-office path for
362/// maintaining records on behalf of students and staff. Same field semantics
363/// as `PATCH /users/me`.
364#[utoipa::path(
365 patch,
366 path = "/{id}/profile",
367 tag = "users",
368 security(("session_cookie" = [])),
369 params(("id" = String, Path, description = "User id")),
370 request_body = UpdateProfile,
371 responses(
372 (status = 200, description = "Updated user", body = UserResponse),
373 (status = 400, description = "Invalid field", body = ErrorResponse),
374 (status = 401, description = "Not authenticated", body = ErrorResponse),
375 (status = 403, description = "Requires admin role", body = ErrorResponse),
376 (status = 404, description = "User not found", body = ErrorResponse),
377 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
378 ),
379)]
380async fn update_user_profile(
381 State(st): State<AppState>,
382 _admin: RequireAdmin,
383 Path(id): Path<String>,
384 Json(req): Json<UpdateProfile>,
385) -> Result<Json<UserResponse>, AppError> {
386 let user = crate::service::user::read(&st.db, &UserId::from_key(&id))
387 .await?
388 .ok_or(AppError::NotFound)?;
389 Ok(Json(apply_profile(user, &req, &st.db).await?))
390}
391
392/// Update any user's UI preferences. Admin only — everyone else manages their
393/// own through `PATCH /users/me/preferences`, which this mirrors field for
394/// field.
395#[utoipa::path(
396 patch,
397 path = "/{id}/preferences",
398 tag = "users",
399 security(("session_cookie" = [])),
400 params(("id" = String, Path, description = "User id")),
401 request_body = UpdatePreferences,
402 responses(
403 (status = 200, description = "Updated user", body = UserResponse),
404 (status = 400, description = "Invalid theme, language, or palette color", body = ErrorResponse),
405 (status = 401, description = "Not authenticated", body = ErrorResponse),
406 (status = 403, description = "Requires admin role", body = ErrorResponse),
407 (status = 404, description = "User not found", body = ErrorResponse),
408 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
409 ),
410)]
411async fn update_user_preferences(
412 State(st): State<AppState>,
413 _admin: RequireAdmin,
414 Path(id): Path<String>,
415 Json(req): Json<UpdatePreferences>,
416) -> Result<Json<UserResponse>, AppError> {
417 let user = crate::service::user::read(&st.db, &UserId::from_key(&id))
418 .await?
419 .ok_or(AppError::NotFound)?;
420 Ok(Json(apply_preferences(user, &req, &st.db).await?))
421}
422
423/// Set a user's role. Admin only. An admin cannot change their own role, and
424/// the school's **last** admin cannot be demoted by anyone (`409`) — together
425/// those keep role management from locking everyone out, including when two
426/// admins demote each other at the same instant (the floor is serialized, see
427/// `ADMIN_FLOOR_LOCK`). A school that has already lost its admins is recovered
428/// with the SurrealQL in the README, 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(),
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(),
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) =
931 ClassMember::list_for_user(id, Some(MAX_PROFILE_CLASSES as i64), 0, &st.db).await?;
932 // The window is safe to take from the database here: the class gate is
933 // all-or-nothing, so it drops the whole page or none of it — never a row
934 // out of the middle of one.
935 if viewer.get_id() != id && ensure_can_observe(viewer, id, &st.db).await.is_err() {
936 members.clear();
937 }
938 let class_ids: Vec<ClassGroupId> = members.iter().map(|row| row.get_class().clone()).collect();
939 let classes = ClassGroup::list_by_ids(&class_ids, &st.db).await?;
940 // Both totals are the full counts, not the windowed ones — the blocks are a
941 // preview, the stats are the truth.
942 let stats = crate::service::profile::load(&st.db, id, course_total, class_total).await?;
943 let badges = badges_of(st, id, &stats).await?;
944 Ok(ProfileResponse {
945 id: id.key().to_string(),
946 username: user.get_username().as_str().to_string(),
947 // The whole three-step resolve lives in `PersonRef` — one spelling of
948 // it, so this profile and every embedded person ref cannot disagree.
949 display_name: PersonRef::new(user).display_name,
950 role: user.get_role().into(),
951 bio: user.get_bio().map(|bio| bio.as_str().to_string()),
952 avatar: user
953 .get_avatar_content_type()
954 .map(|content_type| ProfileAvatar {
955 content_type: content_type.as_str().to_string(),
956 size: user.get_avatar_size().unwrap_or_default(),
957 }),
958 classes: classes
959 .iter()
960 .map(|class| ProfileClassRef {
961 id: class.get_id().key().to_string(),
962 name: class.get_name().as_str().to_string(),
963 grade: class.get_grade().map(|grade| grade.as_str().to_string()),
964 })
965 .collect(),
966 courses: courses
967 .iter()
968 .map(|course| ProfileCourseRef {
969 id: course.get_id().key().to_string(),
970 title: course.get_title().as_str().to_string(),
971 kind: course.get_kind().as_str().to_string(),
972 })
973 .collect(),
974 badges: badges
975 .iter()
976 .map(|award| ProfileBadge {
977 id: award.get_badge().to_string(),
978 earned_at: award.get_earned_at().as_millis(),
979 })
980 .collect(),
981 stats: ProfileStatsResponse {
982 pomodoro_sessions: stats.get_pomodoro_sessions(),
983 pomodoro_focus_ms: stats.get_pomodoro_focus_ms(),
984 courses: stats.get_courses(),
985 classes: stats.get_classes(),
986 homework_submitted_total: stats.get_totals().get_homework_submitted(),
987 homework_on_time_total: stats.get_totals().get_homework_on_time(),
988 exam_sat_total: stats.get_totals().get_exam_sat(),
989 pomodoro_finished_total: stats.get_totals().get_pomodoro_finished(),
990 pomodoro_focus_ms_total: stats.get_totals().get_pomodoro_focus_ms(),
991 marks_given_total: stats.get_totals().get_marks_given(),
992 lessons_held_total: stats.get_totals().get_lessons_held(),
993 pool_approved_total: stats.get_totals().get_pool_approved(),
994 pool_published_total: stats.get_totals().get_pool_published(),
995 lessons_attended_total: stats.get_totals().get_lessons_attended(),
996 high_mark_total: stats.get_totals().get_high_mark(),
997 study_streak_total: stats.get_totals().get_study_streak(),
998 },
999 })
1000}
1001
1002/// The owner's earned badges, and the backstop that keeps them honest.
1003///
1004/// Every write that moves a counter syncs the badges behind it, so in the
1005/// steady state the earned set holds nothing the award rows do not already
1006/// carry and this is one read and **no write at all**. Only a threshold crossed
1007/// by a path whose sync was lost — a transient database error, which those
1008/// callers log and swallow on purpose — leaves a gap, and that heals here on
1009/// the next profile read of that account.
1010///
1011/// Nothing here revokes: [`badge::sync`] only ever adds, so a counter that has
1012/// since fallen back below its threshold leaves the badge standing. The sync's
1013/// own error is logged and dropped, and the awards already read are served —
1014/// a decoration may not fail the profile it decorates.
1015async fn badges_of(
1016 st: &AppState,
1017 user: &UserId,
1018 stats: &ProfileStats,
1019) -> Result<Vec<BadgeAward>, AppError> {
1020 let awards = crate::service::badge::list_for(&st.db, user).await?;
1021 let complete = badge::earned(stats.get_totals())
1022 .iter()
1023 .all(|id| awards.iter().any(|award| award.get_badge() == *id));
1024 if complete {
1025 return Ok(awards);
1026 }
1027 if let Err(err) = crate::service::badge::sync(&st.db, user).await {
1028 tracing::warn!("failed to sync badges for {}: {err}", user.key());
1029 return Ok(awards);
1030 }
1031 // Re-read so the badge just healed appears on *this* response, stamp and
1032 // all, rather than only on the next one.
1033 crate::service::badge::list_for(&st.db, user).await
1034}
1035
1036/// The profile gate: any authenticated account reads any profile — except a
1037/// parent, who is an observer of their own children and of nobody else. The
1038/// link alone is not the grant either; [`ensure_can_observe`] re-reads the
1039/// target's live role, so a student who was promoted out stops being readable.
1040async fn ensure_may_read_profile(
1041 caller: &User,
1042 target: &UserId,
1043 db: &Database,
1044) -> Result<(), AppError> {
1045 if caller.get_role() == Role::Parent && caller.get_id() != target {
1046 ensure_can_observe(caller, target, db).await?;
1047 }
1048 Ok(())
1049}
1050
1051/// The target's row, 404 if it is gone, once the caller is allowed to see it.
1052async fn readable_profile_user(st: &AppState, caller: &User, id: &str) -> Result<User, AppError> {
1053 let target = UserId::from_key(id);
1054 ensure_may_read_profile(caller, &target, &st.db).await?;
1055 crate::service::user::read(&st.db, &target)
1056 .await?
1057 .ok_or(AppError::NotFound)
1058}
1059
1060/// The caller's own public profile — what everyone else sees of them.
1061#[utoipa::path(
1062 get,
1063 path = "/me/profile",
1064 tag = "users",
1065 security(("session_cookie" = [])),
1066 responses(
1067 (status = 200, description = "The caller's profile", body = ProfileResponse),
1068 (status = 401, description = "Not authenticated", body = ErrorResponse),
1069 ),
1070)]
1071async fn my_profile(
1072 State(st): State<AppState>,
1073 CurrentUser(user): CurrentUser,
1074) -> Result<Json<ProfileResponse>, AppError> {
1075 Ok(Json(profile_of(&st, &user, &user).await?))
1076}
1077
1078/// One user's public profile: display name, bio, avatar meta, their class and
1079/// course blocks, the badges they have earned, and the motivational counters.
1080/// Badges carry an id and the instant they were first earned; their labels and
1081/// icons come from the `badges` catalog at `GET /limits`. Readable by every
1082/// authenticated account — except a parent, who reads only their own and their
1083/// linked students'. Never carries email, phone, or birth date; those stay on
1084/// `GET /users/{id}` (admin) and `GET /auth/me`. The embedded blocks are capped
1085/// at `max_profile_classes` / `max_profile_courses` (see `GET /limits`) — the
1086/// full paged lists are `GET /classes/me` and `GET /courses/me`. The course
1087/// block is also cut to what the *reader* may already see: only courses they
1088/// would pass `GET /courses/{id}` on. The class block holds the same bar as
1089/// `GET /classes/user/{id}` — teacher+, a parent linked to this student, or the
1090/// owner themselves; every other reader gets an empty `classes` array rather
1091/// than a 403. Every number in `stats` stays the owner's true total either way,
1092/// including the ones whose underlying reports are gated (`/pomodoro/{id}`,
1093/// `/marks/user/{id}`, `/attendance/user/{id}`): they are motivational
1094/// counters, and a magnitude names no course, class, lesson or exam.
1095#[utoipa::path(
1096 get,
1097 path = "/{id}/profile",
1098 tag = "users",
1099 security(("session_cookie" = [])),
1100 params(("id" = String, Path, description = "User id")),
1101 responses(
1102 (status = 200, description = "The user's profile", body = ProfileResponse),
1103 (status = 401, description = "Not authenticated", body = ErrorResponse),
1104 (status = 403, description = "A parent without a link to this student", body = ErrorResponse),
1105 (status = 404, description = "User not found", body = ErrorResponse),
1106 ),
1107)]
1108async fn get_user_profile(
1109 State(st): State<AppState>,
1110 CurrentUser(caller): CurrentUser,
1111 Path(id): Path<String>,
1112) -> Result<Json<ProfileResponse>, AppError> {
1113 let target = readable_profile_user(&st, &caller, &id).await?;
1114 Ok(Json(profile_of(&st, &target, &caller).await?))
1115}
1116
1117// ---- the avatar -------------------------------------------------------------
1118// One optional picture per user, the same one-image-on-the-owning-row shape the
1119// question pool uses: bytes on disk under a server-generated ULID, metadata on
1120// the user row. Every write here must take the replaced blob off disk — no
1121// route deletes a user, so nothing else would ever collect it.
1122
1123/// Upload (or replace) the caller's own avatar. `multipart/form-data` with the
1124/// image under a `file` field; the declared content type must be `image/png`,
1125/// `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the
1126/// bytes at most the school's `max_file_bytes` (settings). Replacing one drops
1127/// the previous picture.
1128#[utoipa::path(
1129 post,
1130 path = "/me/avatar",
1131 tag = "users",
1132 security(("session_cookie" = [])),
1133 request_body(content = UploadFileForm, content_type = "multipart/form-data"),
1134 responses(
1135 (status = 201, description = "Avatar stored", body = ProfileAvatar),
1136 (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse),
1137 (status = 401, description = "Not authenticated", body = ErrorResponse),
1138 (status = 404, description = "The account no longer exists", body = ErrorResponse),
1139 (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse),
1140 ),
1141)]
1142async fn upload_my_avatar(
1143 State(st): State<AppState>,
1144 CurrentUser(user): CurrentUser,
1145 mut multipart: Multipart,
1146) -> Result<(StatusCode, Json<ProfileAvatar>), AppError> {
1147 let upload = read_image_upload(&st, &mut multipart).await?;
1148 let size = upload.size();
1149
1150 let file = ulid::Ulid::new().to_string();
1151 store_blob(&st, &file, &upload.data, || async {
1152 match crate::service::user::set_avatar(
1153 &st.db,
1154 user.get_id(),
1155 &file,
1156 &upload.content_type,
1157 size,
1158 )
1159 .await?
1160 {
1161 // Row written; the picture this one replaced comes off disk.
1162 Some(before) => Ok(((), before.get_avatar_file().map(str::to_string))),
1163 // The account went away mid-upload — the fresh blob is an orphan.
1164 None => Err(AppError::NotFound),
1165 }
1166 })
1167 .await?;
1168 Ok((
1169 StatusCode::CREATED,
1170 Json(ProfileAvatar {
1171 content_type: upload.content_type.as_str().to_string(),
1172 size,
1173 }),
1174 ))
1175}
1176
1177/// The caller's own avatar bytes. The self alias of `GET /{id}/avatar` — the
1178/// static `/me/avatar` segment wins over `/{id}/avatar` in the router, so
1179/// without this a client that never learned its own id gets a bodyless `405`
1180/// on the obvious route. It serves the caller's own row and nothing else, so
1181/// it asks no gate: the session already proves the reach.
1182#[utoipa::path(
1183 get,
1184 path = "/me/avatar",
1185 tag = "users",
1186 security(("session_cookie" = [])),
1187 responses(
1188 (status = 200, description = "The image bytes", content_type = "image/*"),
1189 (status = 401, description = "Not authenticated", body = ErrorResponse),
1190 (status = 404, description = "The caller has no avatar", body = ErrorResponse),
1191 ),
1192)]
1193async fn get_my_avatar(
1194 State(st): State<AppState>,
1195 CurrentUser(user): CurrentUser,
1196) -> Result<Response, AppError> {
1197 serve_avatar(&st, &user).await
1198}
1199
1200/// The avatar bytes. Same reach as the profile itself: every authenticated
1201/// account, except a parent, who is limited to their own and their linked
1202/// students'.
1203#[utoipa::path(
1204 get,
1205 path = "/{id}/avatar",
1206 tag = "users",
1207 security(("session_cookie" = [])),
1208 params(("id" = String, Path, description = "User id")),
1209 responses(
1210 (status = 200, description = "The image bytes", content_type = "image/*"),
1211 (status = 401, description = "Not authenticated", body = ErrorResponse),
1212 (status = 403, description = "A parent without a link to this student", body = ErrorResponse),
1213 (status = 404, description = "No such user, or they have no avatar", body = ErrorResponse),
1214 ),
1215)]
1216async fn get_avatar(
1217 State(st): State<AppState>,
1218 CurrentUser(caller): CurrentUser,
1219 Path(id): Path<String>,
1220) -> Result<Response, AppError> {
1221 let target = readable_profile_user(&st, &caller, &id).await?;
1222 serve_avatar(&st, &target).await
1223}
1224
1225/// The shared tail of both avatar reads: the bytes, or a `404` when the row
1226/// carries none. The caller owns the gate — this one is reached already.
1227async fn serve_avatar(st: &AppState, user: &User) -> Result<Response, AppError> {
1228 match (user.get_avatar_file(), user.get_avatar_content_type()) {
1229 (Some(file), Some(content_type)) => {
1230 serve_inline_blob(&st.files_path, file, content_type).await
1231 }
1232 _ => Err(AppError::NotFound),
1233 }
1234}
1235
1236/// Remove the caller's own avatar.
1237#[utoipa::path(
1238 delete,
1239 path = "/me/avatar",
1240 tag = "users",
1241 security(("session_cookie" = [])),
1242 responses(
1243 (status = 204, description = "Avatar removed"),
1244 (status = 401, description = "Not authenticated", body = ErrorResponse),
1245 (status = 404, description = "No avatar to remove", body = ErrorResponse),
1246 ),
1247)]
1248async fn delete_my_avatar(
1249 State(st): State<AppState>,
1250 CurrentUser(user): CurrentUser,
1251) -> Result<StatusCode, AppError> {
1252 drop_avatar(&st, user.get_id()).await
1253}
1254
1255/// Remove any user's avatar. Admin only — the moderation path: an offensive
1256/// picture is a school problem, and no route deletes the account it hangs on.
1257#[utoipa::path(
1258 delete,
1259 path = "/{id}/avatar",
1260 tag = "users",
1261 security(("session_cookie" = [])),
1262 params(("id" = String, Path, description = "User id")),
1263 responses(
1264 (status = 204, description = "Avatar removed"),
1265 (status = 401, description = "Not authenticated", body = ErrorResponse),
1266 (status = 403, description = "Requires admin role", body = ErrorResponse),
1267 (status = 404, description = "No such user, or no avatar to remove", body = ErrorResponse),
1268 ),
1269)]
1270async fn delete_avatar(
1271 State(st): State<AppState>,
1272 _admin: RequireAdmin,
1273 Path(id): Path<String>,
1274) -> Result<StatusCode, AppError> {
1275 drop_avatar(&st, &UserId::from_key(&id)).await
1276}
1277
1278/// Clear the row's avatar and take its blob off disk — the shared tail of the
1279/// self and moderation deletes. A row without one (or no row at all) is a 404.
1280async fn drop_avatar(st: &AppState, user: &UserId) -> Result<StatusCode, AppError> {
1281 let before = crate::service::user::clear_avatar(&st.db, user)
1282 .await?
1283 .ok_or(AppError::NotFound)?;
1284 let Some(file) = before.get_avatar_file() else {
1285 return Err(AppError::NotFound);
1286 };
1287 remove_blob(&st.files_path, file).await;
1288 Ok(StatusCode::NO_CONTENT)
1289}