πͺͺ give every person a public profile
Browse files at this commitb326165b3751e073227562254d0da50284a64d47Parent: 0e3eae0- feat
- πͺͺ give every person a public profile
13 changed files +1809 -21
- README.md +118 -4
- src/constant.rs +11 -0
- src/domain/course.rs +13 -0
- src/domain/pomodoro.rs +38 -1
- src/domain/profile.rs +206 -3
- src/domain/user.rs +223 -4
- src/lib.rs +1 -1
- src/migration_sql.rs +5 -0
- src/web/dto.rs +10 -0
- src/web/limits.rs +13 -0
- src/web/users.rs +466 -7
- tests/regress_profile.rs +697 -0
- tests/spec_bounds.rs +8 -1
README.mdmodified+118 -4
| @@ -114,6 +114,13 @@ also carries its own **UI preferences** β theme (`light`/`dark`), language | |||
| 114 | any hex, deliberately not a fixed palette) β self-managed, admin-editable for | 114 | any hex, deliberately not a fixed palette) β self-managed, admin-editable for |
| 115 | anyone, `null` until chosen so the client can fall back to the device | 115 | anyone, `null` until chosen so the client can fall back to the device |
| 116 | preference (or, for the accent, its own default). | 116 | preference (or, for the accent, its own default). |
| 117 | +Every account also has a **public profile** (`/users/{id}/profile`): a | ||
| 118 | +self-chosen `display_name` and `bio`, one **avatar**, the classes and courses | ||
| 119 | +it belongs to, and counters computed at read (finished pomodoro stints, course | ||
| 120 | +and class totals). Contact details are deliberately not part of it β email, | ||
| 121 | +phone and birth date keep the gate they already have β and any authenticated | ||
| 122 | +account reads any profile, except a `parent`, who reads their own and their | ||
| 123 | +linked students' only (see "User profiles & avatars"). | ||
| 117 | The **AI features live in separate projects**, so the backend also opens a | 124 | The **AI features live in separate projects**, so the backend also opens a |
| 118 | QUIC **AI bridge** (`AI_QUIC_ADDR`, off by default): AI services dial in, | 125 | QUIC **AI bridge** (`AI_QUIC_ADDR`, off by default): AI services dial in, |
| 119 | register the capabilities they serve, and each request rides its own QUIC | 126 | register the capabilities they serve, and each request rides its own QUIC |
| @@ -318,7 +325,10 @@ response in the same commit. | |||
| 318 | "username_separators": [".", "_", "-"], | 325 | "username_separators": [".", "_", "-"], |
| 319 | "reserved_usernames": ["admin", "β¦"], | 326 | "reserved_usernames": ["admin", "β¦"], |
| 320 | "min_password_len": 6, "max_password_len": 128, | 327 | "min_password_len": 6, "max_password_len": 128, |
| 321 | - "max_name_len": 100, "max_email_len": 254, | 328 | + "max_name_len": 100, "max_display_name_len": 50, |
| 329 | + "max_bio_len": 500, | ||
| 330 | + "max_profile_courses": 20, "max_profile_classes": 5, | ||
| 331 | + "max_email_len": 254, | ||
| 322 | "min_phone_digits": 7, "max_phone_digits": 15, | 332 | "min_phone_digits": 7, "max_phone_digits": 15, |
| 323 | "roles": ["parent", "student", "teacher", "manager", "admin"], | 333 | "roles": ["parent", "student", "teacher", "manager", "admin"], |
| 324 | "themes": ["light", "dark"], "languages": ["tr", "en"], | 334 | "themes": ["light", "dark"], "languages": ["tr", "en"], |
| @@ -588,6 +598,7 @@ still left exactly as they stand. | |||
| 588 | | Read another user's homework report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full β statuses/marks/flags, never files | | 598 | | Read another user's homework report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full β statuses/marks/flags, never files | |
| 589 | | Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields | | 599 | | Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields | |
| 590 | | Edit **own** UI preferences (theme, language, accent color) | student | `null` until chosen β the client then follows the device preference | | 600 | | Edit **own** UI preferences (theme, language, accent color) | student | `null` until chosen β the client then follows the device preference | |
| 601 | +| Read any user's **public profile** and avatar; upload/remove **own** avatar | student | A `parent` is the exception: own and linked students' only, the link and the target's live role re-read per call. Removing *another* user's avatar is admin-only moderation | | ||
| 591 | | List **own** linked students | parent | Read-only: the list plus each student's mark/attendance/pomodoro/homework reports β a parent changes nothing, anywhere | | 602 | | List **own** linked students | parent | Read-only: the list plus each student's mark/attendance/pomodoro/homework reports β a parent changes nothing, anywhere | |
| 592 | | Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar | | 603 | | Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar | |
| 593 | | Edit school settings; create / edit / delete terms | manager | School policy (exam kinds, attendance statuses, grade bands, the note-file size limit) and the academic calendar are management's call | | 604 | | Edit school settings; create / edit / delete terms | manager | School policy (exam kinds, attendance statuses, grade bands, the note-file size limit) and the academic calendar are management's call | |
| @@ -721,14 +732,21 @@ window filtering, before paging; negative values are a `400` naming the field. | |||
| 721 | | POST | `/auth/login` | no | `{username, password}` -> cookie| | 732 | | POST | `/auth/login` | no | `{username, password}` -> cookie| |
| 722 | | POST | `/auth/logout` | no | Clear session (no-op if none) | | 733 | | POST | `/auth/logout` | no | Clear session (no-op if none) | |
| 723 | | GET | `/auth/me` | student | Current user (incl. `role` and personal info) | | 734 | | GET | `/auth/me` | student | Current user (incl. `role` and personal info) | |
| 724 | -| PATCH | `/users/me` | student | Update own personal info (see below) | | 735 | +| PATCH | `/users/me` | student | Update own personal info, `display_name` and `bio` included (see below) | |
| 725 | | PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` β own UI preferences (see below) | | 736 | | PATCH | `/users/me/preferences` | student | `{theme?, language?, palette_color?}` β own UI preferences (see below) | |
| 737 | +| GET | `/users/me/profile` | student | Own public profile β what everyone else sees of the caller | | ||
| 738 | +| POST | `/users/me/avatar` | student | Upload/replace own avatar: `multipart/form-data`, one `file` part, raster images only, β€ the school's `max_file_bytes` -> `{content_type, size}` | | ||
| 739 | +| GET | `/users/me/avatar` | student | Own avatar bytes (`404` if there is none) β the self alias of `/users/{id}/avatar` | | ||
| 740 | +| DELETE | `/users/me/avatar` | student | Remove own avatar (`404` if there is none) | | ||
| 726 | | GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) Β· paged | | 741 | | GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) Β· paged | |
| 727 | | GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` β find users by username/name fragment (pickers); refs only, no contact info Β· paged | | 742 | | GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` β find users by username/name fragment (pickers); refs only, no contact info Β· paged | |
| 728 | | GET | `/users` | admin | List all users Β· paged | | 743 | | GET | `/users` | admin | List all users Β· paged | |
| 744 | +| GET | `/users/{id}/profile` | student | Any user's public profile β a `parent` reads only their own and their linked students' (`403`) | | ||
| 745 | +| GET | `/users/{id}/avatar` | student | The avatar bytes (`nosniff`, `private, no-store`); same reach as the profile | | ||
| 746 | +| DELETE | `/users/{id}/avatar` | admin | Remove any user's avatar β the moderation path | | ||
| 729 | | GET | `/users/{id}` | admin | Get one user | | 747 | | GET | `/users/{id}` | admin | Get one user | |
| 730 | | PATCH | `/users/{id}/role` | admin | `{role}` β set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll), and a demotion to `parent` also frees their seats on still-open event signup lists | | 748 | | PATCH | `/users/{id}/role` | admin | `{role}` β set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll), and a demotion to `parent` also frees their seats on still-open event signup lists | |
| 731 | -| PATCH | `/users/{id}/profile` | admin | Update any user's personal info | | 749 | +| PATCH | `/users/{id}/profile` | admin | Update any user's personal info, `display_name` and `bio` included | |
| 732 | | PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences | | 750 | | PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences | |
| 733 | | POST | `/users/{id}/students` | admin | `{user_id}` β tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant | | 751 | | POST | `/users/{id}/students` | admin | `{user_id}` β tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant | |
| 734 | | GET | `/users/{id}/students` | admin | List a parent's linked students Β· paged | | 752 | | GET | `/users/{id}/students` | admin | List a parent's linked students Β· paged | |
| @@ -1068,7 +1086,8 @@ digits plus non-consecutive interior `.`, `_`, `-` separators, starting and | |||
| 1068 | ending with a letter or digit (3β32 chars). Staff-looking names (`admin`, | 1086 | ending with a letter or digit (3β32 chars). Staff-looking names (`admin`, |
| 1069 | `administrator`, `root`, `support`, `system`, `moderator`, `staff`) are | 1087 | `administrator`, `root`, `support`, `system`, `moderator`, `staff`) are |
| 1070 | rejected at `/auth/register` only β the `ADMIN_USERNAME` bootstrap may still | 1088 | rejected at `/auth/register` only β the `ADMIN_USERNAME` bootstrap may still |
| 1071 | -seed them. | 1089 | +seed them. `display_name` (β€ 50) and `bio` (β€ 500) ride the same two patches |
| 1090 | +under the same rules, `""` clearing either (see "User profiles & avatars"). | ||
| 1072 | UI preferences (`theme`: `light`/`dark`, `language`: `tr`/`en`, | 1091 | UI preferences (`theme`: `light`/`dark`, `language`: `tr`/`en`, |
| 1073 | `palette_color`: an accent color as `#` plus exactly 6 hex digits) ride on the | 1092 | `palette_color`: an accent color as `#` plus exactly 6 hex digits) ride on the |
| 1074 | same account row and come back on every user response (`/auth/me` included). | 1093 | same account row and come back on every user response (`/auth/me` included). |
| @@ -1081,6 +1100,101 @@ passes (mixed case in, stored and returned lowercase), so a new frontend | |||
| 1081 | palette needs no backend change β `/limits` publishes its pattern rather than a | 1100 | palette needs no backend change β `/limits` publishes its pattern rather than a |
| 1082 | list of colors. | 1101 | list of colors. |
| 1083 | 1102 | ||
| 1103 | +## User profiles & avatars | ||
| 1104 | + | ||
| 1105 | +The public half of an account: who someone is inside the school, readable by | ||
| 1106 | +the school. `GET /users/me/profile` is the caller's own copy of it, | ||
| 1107 | +`GET /users/{id}/profile` anyone's, and both return the same document: | ||
| 1108 | + | ||
| 1109 | +```json | ||
| 1110 | +{ | ||
| 1111 | + "id": "01J8XZ0K3Q8G7X2M4N5P6R7S8T", | ||
| 1112 | + "username": "ada", | ||
| 1113 | + "display_name": "Ada Lovelace", | ||
| 1114 | + "role": "student", | ||
| 1115 | + "bio": "SΔ±nΔ±fΔ±n en hΔ±zlΔ± pomodorocusu.", | ||
| 1116 | + "avatar": { "content_type": "image/png", "size": 20480 }, | ||
| 1117 | + "classes": [ { "id": "01J8β¦", "name": "9-A", "grade": "9" } ], | ||
| 1118 | + "courses": [ { "id": "01J8β¦", "title": "Matematik", "kind": "course" } ], | ||
| 1119 | + "stats": { "pomodoro_sessions": 42, "pomodoro_focus_ms": 63000000, | ||
| 1120 | + "courses": 7, "classes": 1 } | ||
| 1121 | +} | ||
| 1122 | +``` | ||
| 1123 | + | ||
| 1124 | +**Contact fields are absent by design.** `email`, `phone` and `birth_date` are | ||
| 1125 | +not on this document at any role β they keep exactly the gate they have today | ||
| 1126 | +(`GET /auth/me` for oneself, `GET /users/{id}` for an admin). A school-wide | ||
| 1127 | +read surface is not the place to widen where a phone number is reachable. | ||
| 1128 | + | ||
| 1129 | +**Visibility** is every authenticated account reading every profile, with one | ||
| 1130 | +exception: a `parent` reads their own and their currently-linked students', and | ||
| 1131 | +nothing else (`403`). Both halves of that grant are re-read on each call β the | ||
| 1132 | +link *and* the target's live role β so unlinking a student, or promoting one | ||
| 1133 | +out of `student`, stops the reads at once rather than at the next login. | ||
| 1134 | + | ||
| 1135 | +**`display_name`** resolves in three steps: the stored `display_name`, else the | ||
| 1136 | +`"name surname"` join, else `null`. It does **not** replace `name`/`surname` β | ||
| 1137 | +those stay the school-office record, and an admin still edits them β and it | ||
| 1138 | +deliberately does not enter the user search fold: `/users/search` finds people | ||
| 1139 | +by the name the office knows them under, not by a nickname they picked this | ||
| 1140 | +morning. `display_name` and `bio` are patched through the ordinary | ||
| 1141 | +`PATCH /users/me` (or the admin `PATCH /users/{id}/profile`) with the same | ||
| 1142 | +field semantics as the rest: omitted keeps, `""` clears, anything else is | ||
| 1143 | +validated. | ||
| 1144 | + | ||
| 1145 | +**The class and course blocks are a narrowed projection**, not the rows | ||
| 1146 | +themselves: id/name/grade for a class, id/title/kind for a course. A class's | ||
| 1147 | +`creator` and its homeroom teacher are office data behind the teacher+ | ||
| 1148 | +`GET /classes/{id}` and stay there β a profile that carried them would widen | ||
| 1149 | +that gate by accident. Both blocks are truncated (20 courses, 5 classes, both | ||
| 1150 | +published in `/limits` as `max_profile_courses` / `max_profile_classes`); a | ||
| 1151 | +profile is a preview, and `GET /courses/me` and `GET /classes/me` are the full | ||
| 1152 | +paged lists. | ||
| 1153 | + | ||
| 1154 | +**The courses block follows the profile owner's live role**: teacher+ lists the | ||
| 1155 | +courses they teach, everyone else the courses they are enrolled in. It is read | ||
| 1156 | +off the role, never off the stored `creator`/`teachers` columns, because | ||
| 1157 | +ownership here is a live grant and no demotion sweeps those columns β so a | ||
| 1158 | +demoted ex-teacher lists what they are enrolled in, like any other student. | ||
| 1159 | + | ||
| 1160 | +**and it is then cut to what the *reader* may already see**: a course appears | ||
| 1161 | +only if the reader would pass the ordinary course-read gate for it | ||
| 1162 | +(`GET /courses/{id}` β enrolled, creator, assigned teacher, or manager+). A | ||
| 1163 | +course title is not public: a peer who is `403` on the course itself, and gets | ||
| 1164 | +an empty `GET /courses`, must not read it off somebody's profile instead. Your | ||
| 1165 | +own profile and a manager's read are never cut, since both already see the | ||
| 1166 | +whole list, and the 20-course truncation runs *after* the filter, so a reader | ||
| 1167 | +gets up to 20 courses they can actually open. `stats.courses` stays the | ||
| 1168 | +owner's true total on purpose β it is the motivational counter, a per-reader | ||
| 1169 | +number would be meaningless, and a magnitude names no course. One consequence, | ||
| 1170 | +by design: a teacher you share nothing with has an empty `courses` block. | ||
| 1171 | + | ||
| 1172 | +**Stats are computed at read, never stored.** No counter column can drift out | ||
| 1173 | +of sync with the rows behind it, and an account with no data reads a true `0` | ||
| 1174 | +rather than `null`. Only *finished* pomodoro stints count β a timer left | ||
| 1175 | +running is not study time. Exam averages, homework-done rates and attendance | ||
| 1176 | +rates are deliberately absent: those tables are indexed for their own reads, so | ||
| 1177 | +a per-user aggregate over them is a full table scan, and a profile is far too | ||
| 1178 | +cheap a page to pay for one. | ||
| 1179 | + | ||
| 1180 | +**The avatar** is one picture per account, uploaded as `multipart/form-data` | ||
| 1181 | +with the image under a `file` field. Raster types only (`image/png`, | ||
| 1182 | +`image/jpeg`, `image/webp`, `image/gif`) β an SVG can carry script, and these | ||
| 1183 | +bytes render inline all over the school. The size cap is the school's existing | ||
| 1184 | +`max_file_bytes` setting rather than a new knob: one number to raise when a | ||
| 1185 | +school wants bigger uploads. Uploading replaces, and the picture it replaced | ||
| 1186 | +comes off disk. The owner removes theirs at `DELETE /users/me/avatar`; an admin | ||
| 1187 | +removes anyone's at `DELETE /users/{id}/avatar`, the moderation path β an | ||
| 1188 | +offensive picture is a school problem. The bytes come back from | ||
| 1189 | +`GET /users/{id}/avatar` under the same reach as the profile itself, served | ||
| 1190 | +`X-Content-Type-Options: nosniff` and `Cache-Control: private, no-store`; | ||
| 1191 | +`GET /users/me/avatar` is the same read for the caller's own picture, so a | ||
| 1192 | +client that never learned its own id still has a route. | ||
| 1193 | + | ||
| 1194 | +There is no `badges` key yet. Auto-earned badges are a planned second pass and | ||
| 1195 | +will be added to `stats`' neighborhood additively, so a client written against | ||
| 1196 | +today's document keeps working. | ||
| 1197 | + | ||
| 1084 | ## Appointments | 1198 | ## Appointments |
| 1085 | 1199 | ||
| 1086 | Office hours and parent-teacher conferences, booked instead of arranged by | 1200 | Office hours and parent-teacher conferences, booked instead of arranged by |
src/constant.rsmodified+11 -0
| @@ -29,6 +29,17 @@ pub const MAX_PASSWORD_LEN: usize = 128; | |||
| 29 | 29 | ||
| 30 | pub const MAX_NAME_LEN: usize = 100; | 30 | pub const MAX_NAME_LEN: usize = 100; |
| 31 | 31 | ||
| 32 | +/// Profile fields: the self-chosen name a user is shown under, and the free | ||
| 33 | +/// text under it. | ||
| 34 | +pub const MAX_DISPLAY_NAME_LEN: usize = 50; | ||
| 35 | +pub const MAX_BIO_LEN: usize = 500; | ||
| 36 | + | ||
| 37 | +/// How many course and class references one profile read embeds. A cap on the | ||
| 38 | +/// response, not on membership β the full lists stay at `/courses/me` and | ||
| 39 | +/// `/classes/me`. | ||
| 40 | +pub const MAX_PROFILE_COURSES: usize = 20; | ||
| 41 | +pub const MAX_PROFILE_CLASSES: usize = 5; | ||
| 42 | + | ||
| 32 | /// RFC 5321's practical upper bound for a full address. | 43 | /// RFC 5321's practical upper bound for a full address. |
| 33 | pub const MAX_EMAIL_LEN: usize = 254; | 44 | pub const MAX_EMAIL_LEN: usize = 254; |
| 34 | 45 | ||
src/domain/course.rsmodified+13 -0
| @@ -244,6 +244,19 @@ impl Course { | |||
| 244 | 244 | ||
| 245 | /// The courses `user` runs β the ones they created plus the ones a manager | 245 | /// The courses `user` runs β the ones they created plus the ones a manager |
| 246 | /// assigned them to. A teacher's slice of the catalog. | 246 | /// assigned them to. A teacher's slice of the catalog. |
| 247 | + /// | ||
| 248 | + /// ponytail: unpaged full table scan, and it stays one β every profile read | ||
| 249 | + /// of a teacher pays it, so the ceiling is the course table's size. It | ||
| 250 | + /// cannot be indexed away on SurrealDB 3.2.3: an index on `creator` alone | ||
| 251 | + /// leaves the `OR` a `TableScan` (EXPLAIN), and the per-element index the | ||
| 252 | + /// membership half would need (`DEFINE INDEX ... FIELDS teachers[*]`) is | ||
| 253 | + /// *wrong*, not merely useless β with it, `$usr IN teachers` and | ||
| 254 | + /// `teachers CONTAINS $usr` return **no rows at all**, which is what the | ||
| 255 | + /// integration test `assigned_teacher_manages_course_without_owning_it` | ||
| 256 | + /// catches. A plain `FIELDS teachers` index is correct but unused. The | ||
| 257 | + /// upgrade path is structural: a `course_teacher` link table indexed on | ||
| 258 | + /// `user`, the shape `enrollment` already has, turning this into two | ||
| 259 | + /// index-backed reads. | ||
| 247 | pub async fn list_for_teacher(user: &UserId, db: &Database) -> Result<Vec<Course>, AppError> { | 260 | pub async fn list_for_teacher(user: &UserId, db: &Database) -> Result<Vec<Course>, AppError> { |
| 248 | let mut result = db | 261 | let mut result = db |
| 249 | .query("SELECT * FROM course WHERE creator = $usr OR $usr IN teachers ORDER BY id DESC") | 262 | .query("SELECT * FROM course WHERE creator = $usr OR $usr IN teachers ORDER BY id DESC") |
src/domain/pomodoro.rsmodified+38 -1
| @@ -107,6 +107,15 @@ impl PomodoroSession { | |||
| 107 | /// `CREATE` cannot answer "already exists" on the way back β the table | 107 | /// `CREATE` cannot answer "already exists" on the way back β the table |
| 108 | /// carries no `UNIQUE` index and `$closed` is one freshly minted ULID. | 108 | /// carries no `UNIQUE` index and `$closed` is one freshly minted ULID. |
| 109 | /// Only the guard's own `THROW` is a decision, and it stays a 409. | 109 | /// Only the guard's own `THROW` is a decision, and it stays a 409. |
| 110 | + /// | ||
| 111 | + /// `finished_at` is floored at the row's own `started_at`. Both stamps come | ||
| 112 | + /// from [`Timestamp::now`], i.e. the wall clock, which an NTP step can move | ||
| 113 | + /// *backwards* mid-stint β so a close can legitimately read earlier than its | ||
| 114 | + /// own start with nothing wrong on the client's side. Refusing it would lose | ||
| 115 | + /// a real study session and leave the open slot wedged for a fault the | ||
| 116 | + /// student did not cause; recording a zero-length stint keeps the session | ||
| 117 | + /// count honest and its duration merely understated. Nothing downstream may | ||
| 118 | + /// then read a negative duration (`ProfileStats::load` sums these). | ||
| 110 | pub async fn finish(user: &UserId, db: &Database) -> Result<PomodoroSession, AppError> { | 119 | pub async fn finish(user: &UserId, db: &Database) -> Result<PomodoroSession, AppError> { |
| 111 | let (mut result, mut errors) = transaction_with_retry( | 120 | let (mut result, mut errors) = transaction_with_retry( |
| 112 | db, | 121 | db, |
| @@ -116,7 +125,7 @@ impl PomodoroSession { | |||
| 116 | CREATE $closed CONTENT { | 125 | CREATE $closed CONTENT { |
| 117 | user: $before[0].user, | 126 | user: $before[0].user, |
| 118 | started_at: $before[0].started_at, | 127 | started_at: $before[0].started_at, |
| 119 | - finished_at: $done, | 128 | + finished_at: math::max([$before[0].started_at, $done]), |
| 120 | }; | 129 | }; |
| 121 | COMMIT TRANSACTION;", | 130 | COMMIT TRANSACTION;", |
| 122 | &[ | 131 | &[ |
| @@ -212,4 +221,32 @@ mod tests { | |||
| 212 | let sessions = PomodoroSession::list_for_user(&user, &db).await.unwrap(); | 221 | let sessions = PomodoroSession::list_for_user(&user, &db).await.unwrap(); |
| 213 | assert_eq!(sessions.len(), 2); | 222 | assert_eq!(sessions.len(), 2); |
| 214 | } | 223 | } |
| 224 | + | ||
| 225 | + #[tokio::test] | ||
| 226 | + async fn a_backwards_clock_records_a_zero_stint_not_a_negative_one() { | ||
| 227 | + let db = database::init_mem().await.unwrap(); | ||
| 228 | + let user = UserId::from_key(&Ulid::new().to_string()); | ||
| 229 | + | ||
| 230 | + PomodoroSession::start(&user, &db).await.unwrap(); | ||
| 231 | + // Stand in for the NTP step: push the running stint's start an hour | ||
| 232 | + // ahead, so the server clock `finish` reads is *behind* it. | ||
| 233 | + db.query("UPDATE $open SET started_at = $future") | ||
| 234 | + .bind(("open", PomodoroSessionId::open_for(&user).record())) | ||
| 235 | + .bind(("future", Timestamp::now().as_millis() + 3_600_000)) | ||
| 236 | + .await | ||
| 237 | + .unwrap() | ||
| 238 | + .check() | ||
| 239 | + .unwrap(); | ||
| 240 | + | ||
| 241 | + let closed = PomodoroSession::finish(&user, &db).await.unwrap(); | ||
| 242 | + let started = closed.get_started_at().as_millis(); | ||
| 243 | + assert_eq!(closed.get_finished_at().unwrap().as_millis(), started); | ||
| 244 | + | ||
| 245 | + // And the stat that sums these stays non-negative. | ||
| 246 | + let stats = crate::domain::profile::ProfileStats::load(&user, 0, 0, &db) | ||
| 247 | + .await | ||
| 248 | + .unwrap(); | ||
| 249 | + assert_eq!(stats.get_pomodoro_sessions(), 1); | ||
| 250 | + assert_eq!(stats.get_pomodoro_focus_ms(), 0); | ||
| 251 | + } | ||
| 215 | } | 252 | } |
src/domain/profile.rsmodified+206 -3
| @@ -3,10 +3,12 @@ | |||
| 3 | 3 | ||
| 4 | use surrealdb::types::SurrealValue; | 4 | use surrealdb::types::SurrealValue; |
| 5 | 5 | ||
| 6 | -use crate::constant::MAX_NAME_LEN; | 6 | +use crate::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN, MAX_NAME_LEN}; |
| 7 | +use crate::database::Database; | ||
| 7 | use crate::domain::timestamp::Timestamp; | 8 | use crate::domain::timestamp::Timestamp; |
| 8 | -use crate::error::ValidationError; | 9 | +use crate::domain::user::UserId; |
| 9 | -use crate::validate::{validate_email, validate_phone, validate_required}; | 10 | +use crate::error::{AppError, ValidationError}; |
| 11 | +use crate::validate::{validate_email, validate_optional, validate_phone, validate_required}; | ||
| 10 | 12 | ||
| 11 | /// A person's given or family name. One type serves both fields β the `field` | 13 | /// A person's given or family name. One type serves both fields β the `field` |
| 12 | /// tag only steers the error message ("name β¦" vs "surname β¦"). Stored trimmed; | 14 | /// tag only steers the error message ("name β¦" vs "surname β¦"). Stored trimmed; |
| @@ -92,6 +94,122 @@ impl BirthDate { | |||
| 92 | } | 94 | } |
| 93 | } | 95 | } |
| 94 | 96 | ||
| 97 | +/// The name a profile shows instead of the legal one β a nickname, a shortened | ||
| 98 | +/// form, whatever the person answers to. Stored trimmed; unicode is welcome, | ||
| 99 | +/// same as [`PersonName`] and unlike the ASCII-only username. | ||
| 100 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 101 | +pub struct DisplayName(String); | ||
| 102 | + | ||
| 103 | +impl DisplayName { | ||
| 104 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 105 | + validate_required("display_name", value, MAX_DISPLAY_NAME_LEN)?; | ||
| 106 | + Ok(Self(value.trim().to_string())) | ||
| 107 | + } | ||
| 108 | + | ||
| 109 | + pub fn as_str(&self) -> &str { | ||
| 110 | + &self.0 | ||
| 111 | + } | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +/// A short self-description on the public profile. Free text within | ||
| 115 | +/// [`MAX_BIO_LEN`], blank allowed β an empty bio is a written-then-erased one, | ||
| 116 | +/// which is a legitimate state and not an error. Stored trimmed. | ||
| 117 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 118 | +pub struct Bio(String); | ||
| 119 | + | ||
| 120 | +impl Bio { | ||
| 121 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 122 | + validate_optional("bio", value, MAX_BIO_LEN)?; | ||
| 123 | + Ok(Self(value.trim().to_string())) | ||
| 124 | + } | ||
| 125 | + | ||
| 126 | + pub fn as_str(&self) -> &str { | ||
| 127 | + &self.0 | ||
| 128 | + } | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +/// The motivational counters on a public profile. Every field is a derived | ||
| 132 | +/// count, never a settable one: zero rows is a true zero, so these are `i64` | ||
| 133 | +/// and never `Option` β a `null` in this API means "never chose", which a | ||
| 134 | +/// derived number can't be. An account that predates the feature therefore | ||
| 135 | +/// reads exactly like a fresh one. | ||
| 136 | +/// | ||
| 137 | +/// One named struct on purpose: the auto-earned badge rules take a whole | ||
| 138 | +/// `ProfileStats` as their sole input, so a counter added here reaches them | ||
| 139 | +/// without touching a signature. | ||
| 140 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 141 | +pub struct ProfileStats { | ||
| 142 | + pomodoro_sessions: i64, | ||
| 143 | + pomodoro_focus_ms: i64, | ||
| 144 | + courses: i64, | ||
| 145 | + classes: i64, | ||
| 146 | +} | ||
| 147 | + | ||
| 148 | +impl ProfileStats { | ||
| 149 | + pub fn get_pomodoro_sessions(&self) -> i64 { | ||
| 150 | + self.pomodoro_sessions | ||
| 151 | + } | ||
| 152 | + | ||
| 153 | + pub fn get_pomodoro_focus_ms(&self) -> i64 { | ||
| 154 | + self.pomodoro_focus_ms | ||
| 155 | + } | ||
| 156 | + | ||
| 157 | + pub fn get_courses(&self) -> i64 { | ||
| 158 | + self.courses | ||
| 159 | + } | ||
| 160 | + | ||
| 161 | + pub fn get_classes(&self) -> i64 { | ||
| 162 | + self.classes | ||
| 163 | + } | ||
| 164 | + | ||
| 165 | + /// One query, and only one: `courses` and `classes` arrive from the caller, | ||
| 166 | + /// which already holds them as the `total` of the paged class and course | ||
| 167 | + /// readers it ran for the profile's own blocks β re-counting them here | ||
| 168 | + /// would be two extra reads for numbers already in hand. | ||
| 169 | + /// | ||
| 170 | + /// The pomodoro aggregate rides the per-user index, so it is a lookup and | ||
| 171 | + /// not a scan. `finished_at != NONE` is the filter because NONE is falsy: a | ||
| 172 | + /// bare truthiness test would also drop a stint that finished at epoch. An | ||
| 173 | + /// open stint contributes to neither the count nor the sum β unfinished | ||
| 174 | + /// focus has no honest duration to add. | ||
| 175 | + pub async fn load( | ||
| 176 | + user: &UserId, | ||
| 177 | + courses: i64, | ||
| 178 | + classes: i64, | ||
| 179 | + db: &Database, | ||
| 180 | + ) -> Result<ProfileStats, AppError> { | ||
| 181 | + let mut result = db | ||
| 182 | + .query( | ||
| 183 | + "SELECT count() AS sessions, math::sum(finished_at - started_at) AS focus_ms | ||
| 184 | + FROM pomodoro_session WHERE user = $usr AND finished_at != NONE GROUP ALL", | ||
| 185 | + ) | ||
| 186 | + .bind(("usr", user.record())) | ||
| 187 | + .await? | ||
| 188 | + .check()?; | ||
| 189 | + // `GROUP ALL` yields no row at all when nothing matched β that is the | ||
| 190 | + // zero case, not a missing one. | ||
| 191 | + let row = result.take::<Vec<PomodoroTotals>>(0)?.into_iter().next(); | ||
| 192 | + Ok(ProfileStats { | ||
| 193 | + pomodoro_sessions: row.as_ref().map_or(0, |totals| totals.sessions), | ||
| 194 | + // Floored at zero: a stint stamped by a wall clock that stepped | ||
| 195 | + // backwards mid-session sums as negative time, and "you focused for | ||
| 196 | + // minus five seconds" is never the truthful answer. New stints | ||
| 197 | + // cannot go inverted (see [`PomodoroSession::finish`]); rows written | ||
| 198 | + // before that guard still can, and this is what covers them. | ||
| 199 | + pomodoro_focus_ms: row.map_or(0, |totals| totals.focus_ms.max(0)), | ||
| 200 | + courses, | ||
| 201 | + classes, | ||
| 202 | + }) | ||
| 203 | + } | ||
| 204 | +} | ||
| 205 | + | ||
| 206 | +/// The aggregate row of [`ProfileStats::load`]. | ||
| 207 | +#[derive(Debug, SurrealValue)] | ||
| 208 | +struct PomodoroTotals { | ||
| 209 | + sessions: i64, | ||
| 210 | + focus_ms: i64, | ||
| 211 | +} | ||
| 212 | + | ||
| 95 | #[cfg(test)] | 213 | #[cfg(test)] |
| 96 | mod tests { | 214 | mod tests { |
| 97 | use super::*; | 215 | use super::*; |
| @@ -156,4 +274,89 @@ mod tests { | |||
| 156 | let two_days_out = today.succ_opt().unwrap().succ_opt().unwrap(); | 274 | let two_days_out = today.succ_opt().unwrap().succ_opt().unwrap(); |
| 157 | assert!(BirthDate::try_new(&fmt(two_days_out)).is_err()); | 275 | assert!(BirthDate::try_new(&fmt(two_days_out)).is_err()); |
| 158 | } | 276 | } |
| 277 | + | ||
| 278 | + #[tokio::test] | ||
| 279 | + async fn display_name_trims_and_validates() { | ||
| 280 | + assert_eq!(DisplayName::try_new(" Ada ").unwrap().as_str(), "Ada"); | ||
| 281 | + // A display name is a name, not a username: unicode passes. | ||
| 282 | + assert_eq!( | ||
| 283 | + DisplayName::try_new("GΓΌmΓΌΕ π’").unwrap().as_str(), | ||
| 284 | + "GΓΌmΓΌΕ π’" | ||
| 285 | + ); | ||
| 286 | + assert!(DisplayName::try_new(" ").is_err()); | ||
| 287 | + assert!(DisplayName::try_new(&"x".repeat(MAX_DISPLAY_NAME_LEN + 1)).is_err()); | ||
| 288 | + } | ||
| 289 | + | ||
| 290 | + #[tokio::test] | ||
| 291 | + async fn bio_trims_and_validates() { | ||
| 292 | + assert_eq!(Bio::try_new(" hello ").unwrap().as_str(), "hello"); | ||
| 293 | + // Blank is a legitimate bio (erased), unlike a blank display name. | ||
| 294 | + assert_eq!(Bio::try_new(" ").unwrap().as_str(), ""); | ||
| 295 | + assert!(Bio::try_new(&"Γ©".repeat(MAX_BIO_LEN)).is_ok()); | ||
| 296 | + assert!(Bio::try_new(&"Γ©".repeat(MAX_BIO_LEN + 1)).is_err()); | ||
| 297 | + } | ||
| 298 | + | ||
| 299 | + #[tokio::test] | ||
| 300 | + async fn stats_are_zero_without_pomodoro_rows() { | ||
| 301 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 302 | + let user = UserId::from_key(&ulid::Ulid::new().to_string()); | ||
| 303 | + | ||
| 304 | + let stats = ProfileStats::load(&user, 3, 1, &db).await.unwrap(); | ||
| 305 | + // Derived counters: no rows is a true zero, never a null. | ||
| 306 | + assert_eq!(stats.get_pomodoro_sessions(), 0); | ||
| 307 | + assert_eq!(stats.get_pomodoro_focus_ms(), 0); | ||
| 308 | + // The passed-in counts survive untouched. | ||
| 309 | + assert_eq!(stats.get_courses(), 3); | ||
| 310 | + assert_eq!(stats.get_classes(), 1); | ||
| 311 | + } | ||
| 312 | + | ||
| 313 | + #[tokio::test] | ||
| 314 | + async fn stats_count_finished_stints_only() { | ||
| 315 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 316 | + let user = UserId::from_key(&ulid::Ulid::new().to_string()); | ||
| 317 | + let other = UserId::from_key(&ulid::Ulid::new().to_string()); | ||
| 318 | + | ||
| 319 | + // Two finished stints (1000 ms + 2500 ms), one still running, and one | ||
| 320 | + // finished stint belonging to somebody else. | ||
| 321 | + db.query( | ||
| 322 | + "CREATE pomodoro_session CONTENT { user: $usr, started_at: 1000, finished_at: 2000 }; | ||
| 323 | + CREATE pomodoro_session CONTENT { user: $usr, started_at: 5000, finished_at: 7500 }; | ||
| 324 | + CREATE pomodoro_session CONTENT { user: $usr, started_at: 9000 }; | ||
| 325 | + CREATE pomodoro_session CONTENT { user: $oth, started_at: 0, finished_at: 60000 };", | ||
| 326 | + ) | ||
| 327 | + .bind(("usr", user.record())) | ||
| 328 | + .bind(("oth", other.record())) | ||
| 329 | + .await | ||
| 330 | + .unwrap() | ||
| 331 | + .check() | ||
| 332 | + .unwrap(); | ||
| 333 | + | ||
| 334 | + let stats = ProfileStats::load(&user, 0, 0, &db).await.unwrap(); | ||
| 335 | + assert_eq!(stats.get_pomodoro_sessions(), 2); | ||
| 336 | + assert_eq!(stats.get_pomodoro_focus_ms(), 3500); | ||
| 337 | + } | ||
| 338 | + | ||
| 339 | + #[tokio::test] | ||
| 340 | + async fn focus_time_never_reads_negative() { | ||
| 341 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 342 | + let user = UserId::from_key(&ulid::Ulid::new().to_string()); | ||
| 343 | + | ||
| 344 | + // One honest 1000 ms stint and one inverted row β what a backwards | ||
| 345 | + // clock step left behind before `finish` grew its floor. The raw sum is | ||
| 346 | + // -5000; the profile must still answer a duration, not an accusation. | ||
| 347 | + db.query( | ||
| 348 | + "CREATE pomodoro_session CONTENT { user: $usr, started_at: 1000, finished_at: 2000 }; | ||
| 349 | + CREATE pomodoro_session CONTENT { user: $usr, started_at: 9000, finished_at: 3000 };", | ||
| 350 | + ) | ||
| 351 | + .bind(("usr", user.record())) | ||
| 352 | + .await | ||
| 353 | + .unwrap() | ||
| 354 | + .check() | ||
| 355 | + .unwrap(); | ||
| 356 | + | ||
| 357 | + let stats = ProfileStats::load(&user, 0, 0, &db).await.unwrap(); | ||
| 358 | + // The stints still happened, so the count is honest at 2. | ||
| 359 | + assert_eq!(stats.get_pomodoro_sessions(), 2); | ||
| 360 | + assert_eq!(stats.get_pomodoro_focus_ms(), 0); | ||
| 361 | + } | ||
| 159 | } | 362 | } |
src/domain/user.rsmodified+223 -4
| @@ -9,13 +9,14 @@ use crate::constant::{ | |||
| 9 | DECOY_PASSWORD, ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE, PARENT_LINK_TABLE, | 9 | DECOY_PASSWORD, ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE, PARENT_LINK_TABLE, |
| 10 | REGISTRATION_COUNT_FIELD, REGISTRATION_FROZEN_GUARD, REGISTRATION_TABLE, USER_TABLE, | 10 | REGISTRATION_COUNT_FIELD, REGISTRATION_FROZEN_GUARD, REGISTRATION_TABLE, USER_TABLE, |
| 11 | }; | 11 | }; |
| 12 | -use crate::database::{Database, transaction_with_retry}; | 12 | +use crate::database::{Database, transaction_with_retry, write_with_retry}; |
| 13 | use crate::domain::board::Board; | 13 | use crate::domain::board::Board; |
| 14 | use crate::domain::field_update::FieldUpdate; | 14 | use crate::domain::field_update::FieldUpdate; |
| 15 | use crate::domain::monotonic_id::next_ulid; | 15 | use crate::domain::monotonic_id::next_ulid; |
| 16 | +use crate::domain::note_file::FileContentType; | ||
| 16 | use crate::domain::page::PagedList; | 17 | use crate::domain::page::PagedList; |
| 17 | use crate::domain::preferences::{Language, PaletteColor, Theme}; | 18 | use crate::domain::preferences::{Language, PaletteColor, Theme}; |
| 18 | -use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; | 19 | +use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; |
| 19 | use crate::domain::role::Role; | 20 | use crate::domain::role::Role; |
| 20 | use crate::domain::text_fold::{search_fold, search_fold_sql}; | 21 | use crate::domain::text_fold::{search_fold, search_fold_sql}; |
| 21 | use crate::domain::timestamp::Timestamp; | 22 | use crate::domain::timestamp::Timestamp; |
| @@ -216,6 +217,17 @@ pub struct User { | |||
| 216 | theme: Option<Theme>, | 217 | theme: Option<Theme>, |
| 217 | language: Option<Language>, | 218 | language: Option<Language>, |
| 218 | palette_color: Option<PaletteColor>, | 219 | palette_color: Option<PaletteColor>, |
| 220 | + // The public profile: what other people see instead of the credentials. | ||
| 221 | + // Optional like everything above β a profile is written after the account | ||
| 222 | + // exists, so rows from before these fields existed read back as `None`, | ||
| 223 | + // which is exactly a fresh account that never filled one in. The avatar is | ||
| 224 | + // a blob on disk (`FILES_PATH`) like every other upload; only its name, | ||
| 225 | + // type and size live on the row. | ||
| 226 | + display_name: Option<DisplayName>, | ||
| 227 | + bio: Option<Bio>, | ||
| 228 | + avatar_file: Option<String>, | ||
| 229 | + avatar_content_type: Option<FileContentType>, | ||
| 230 | + avatar_size: Option<i64>, | ||
| 219 | } | 231 | } |
| 220 | 232 | ||
| 221 | impl User { | 233 | impl User { |
| @@ -267,6 +279,26 @@ impl User { | |||
| 267 | self.palette_color.as_ref() | 279 | self.palette_color.as_ref() |
| 268 | } | 280 | } |
| 269 | 281 | ||
| 282 | + pub fn get_display_name(&self) -> Option<&DisplayName> { | ||
| 283 | + self.display_name.as_ref() | ||
| 284 | + } | ||
| 285 | + | ||
| 286 | + pub fn get_bio(&self) -> Option<&Bio> { | ||
| 287 | + self.bio.as_ref() | ||
| 288 | + } | ||
| 289 | + | ||
| 290 | + pub fn get_avatar_file(&self) -> Option<&str> { | ||
| 291 | + self.avatar_file.as_deref() | ||
| 292 | + } | ||
| 293 | + | ||
| 294 | + pub fn get_avatar_content_type(&self) -> Option<&FileContentType> { | ||
| 295 | + self.avatar_content_type.as_ref() | ||
| 296 | + } | ||
| 297 | + | ||
| 298 | + pub fn get_avatar_size(&self) -> Option<i64> { | ||
| 299 | + self.avatar_size | ||
| 300 | + } | ||
| 301 | + | ||
| 270 | /// Register a new account. New users always start as [`Role::Student`]; | 302 | /// Register a new account. New users always start as [`Role::Student`]; |
| 271 | /// elevation is a separate, admin-only action (see [`User::set_role`]). | 303 | /// elevation is a separate, admin-only action (see [`User::set_role`]). |
| 272 | pub async fn create( | 304 | pub async fn create( |
| @@ -308,6 +340,11 @@ impl User { | |||
| 308 | theme: None, | 340 | theme: None, |
| 309 | language: None, | 341 | language: None, |
| 310 | palette_color: None, | 342 | palette_color: None, |
| 343 | + display_name: None, | ||
| 344 | + bio: None, | ||
| 345 | + avatar_file: None, | ||
| 346 | + avatar_content_type: None, | ||
| 347 | + avatar_size: None, | ||
| 311 | }; | 348 | }; |
| 312 | let created: Result<Option<User>, surrealdb::Error> = | 349 | let created: Result<Option<User>, surrealdb::Error> = |
| 313 | db.create(user.id.record()).content(user.clone()).await; | 350 | db.create(user.id.record()).content(user.clone()).await; |
| @@ -594,7 +631,9 @@ impl User { | |||
| 594 | Ok((updated, boards)) | 631 | Ok((updated, boards)) |
| 595 | } | 632 | } |
| 596 | 633 | ||
| 597 | - /// Write the personal-info fields the request actually carried. Every | 634 | + /// Write the personal-info and public-profile fields the request actually |
| 635 | + /// carried β everything a person edits about themselves except the avatar | ||
| 636 | + /// blob, which needs its own writer ([`User::set_avatar`]). Every | ||
| 598 | /// column is nullable, so each argument is an outer/inner `Option`: `None` | 637 | /// column is nullable, so each argument is an outer/inner `Option`: `None` |
| 599 | /// = omitted (not written at all), `Some(None)` = cleared, `Some(Some(v))` | 638 | /// = omitted (not written at all), `Some(None)` = cleared, `Some(Some(v))` |
| 600 | /// = set. Merging the request against the current row is the HTTP layer's | 639 | /// = set. Merging the request against the current row is the HTTP layer's |
| @@ -605,6 +644,10 @@ impl User { | |||
| 605 | /// for an omitted field would revert a concurrent PATCH of that field β | 644 | /// for an omitted field would revert a concurrent PATCH of that field β |
| 606 | /// two profile edits (a name and a phone) used to lose each other. See | 645 | /// two profile edits (a name and a phone) used to lose each other. See |
| 607 | /// [`User::set_role`] for why no writer here touches the whole row. | 646 | /// [`User::set_role`] for why no writer here touches the whole row. |
| 647 | + // One argument per nullable column is the point: folding them into a struct | ||
| 648 | + // would just re-spell the HTTP DTO here and cost the compiler's check that | ||
| 649 | + // every column was considered at the call site. | ||
| 650 | + #[allow(clippy::too_many_arguments)] | ||
| 608 | pub async fn set_profile( | 651 | pub async fn set_profile( |
| 609 | self, | 652 | self, |
| 610 | name: Option<Option<PersonName>>, | 653 | name: Option<Option<PersonName>>, |
| @@ -612,6 +655,8 @@ impl User { | |||
| 612 | email: Option<Option<Email>>, | 655 | email: Option<Option<Email>>, |
| 613 | phone: Option<Option<Phone>>, | 656 | phone: Option<Option<Phone>>, |
| 614 | birth_date: Option<Option<BirthDate>>, | 657 | birth_date: Option<Option<BirthDate>>, |
| 658 | + display_name: Option<Option<DisplayName>>, | ||
| 659 | + bio: Option<Option<Bio>>, | ||
| 615 | db: &Database, | 660 | db: &Database, |
| 616 | ) -> Result<User, AppError> { | 661 | ) -> Result<User, AppError> { |
| 617 | FieldUpdate::new(self.id.record()) | 662 | FieldUpdate::new(self.id.record()) |
| @@ -620,10 +665,60 @@ impl User { | |||
| 620 | .set("email", email) | 665 | .set("email", email) |
| 621 | .set("phone", phone) | 666 | .set("phone", phone) |
| 622 | .set("birth_date", birth_date) | 667 | .set("birth_date", birth_date) |
| 668 | + .set("display_name", display_name) | ||
| 669 | + .set("bio", bio) | ||
| 623 | .run::<User>(db) | 670 | .run::<User>(db) |
| 624 | .await | 671 | .await |
| 625 | } | 672 | } |
| 626 | 673 | ||
| 674 | + /// Point the row at a freshly uploaded avatar blob, returning the row *as | ||
| 675 | + /// it was* β the caller deletes `before.get_avatar_file()` off disk. Losing | ||
| 676 | + /// `RETURN BEFORE` here strands the replaced blob forever: no route ever | ||
| 677 | + /// deletes a user, so nothing else would collect it. | ||
| 678 | + /// | ||
| 679 | + /// Field-scoped for the same reason as [`User::set_profile`]: an avatar | ||
| 680 | + /// upload must not carry a stale snapshot's role back over an admin's | ||
| 681 | + /// change. `None` means the row is gone. | ||
| 682 | + /// | ||
| 683 | + /// Sent through [`write_with_retry`] like every other single-statement row | ||
| 684 | + /// write here, unguarded or not: the user row is contended (preferences, | ||
| 685 | + /// profile, role all write it), and a lost round wrote nothing, so | ||
| 686 | + /// re-sending it is the recovery rather than a 500 in the caller's face. | ||
| 687 | + pub async fn set_avatar( | ||
| 688 | + id: &UserId, | ||
| 689 | + file: &str, | ||
| 690 | + content_type: &FileContentType, | ||
| 691 | + size: i64, | ||
| 692 | + db: &Database, | ||
| 693 | + ) -> Result<Option<User>, AppError> { | ||
| 694 | + let rows: Vec<User> = write_with_retry( | ||
| 695 | + db, | ||
| 696 | + "UPDATE $u SET avatar_file = $file, avatar_content_type = $ct, avatar_size = $size \ | ||
| 697 | + RETURN BEFORE", | ||
| 698 | + &[ | ||
| 699 | + ("u".into(), id.record().into_value()), | ||
| 700 | + ("file".into(), file.to_string().into_value()), | ||
| 701 | + ("ct".into(), content_type.clone().into_value()), | ||
| 702 | + ("size".into(), size.into_value()), | ||
| 703 | + ], | ||
| 704 | + ) | ||
| 705 | + .await?; | ||
| 706 | + Ok(rows.into_iter().next()) | ||
| 707 | + } | ||
| 708 | + | ||
| 709 | + /// Drop the avatar, returning the row as it was so the caller can delete | ||
| 710 | + /// the blob. Same `RETURN BEFORE` contract as [`User::set_avatar`]. | ||
| 711 | + pub async fn clear_avatar(id: &UserId, db: &Database) -> Result<Option<User>, AppError> { | ||
| 712 | + let rows: Vec<User> = write_with_retry( | ||
| 713 | + db, | ||
| 714 | + "UPDATE $u SET avatar_file = NONE, avatar_content_type = NONE, \ | ||
| 715 | + avatar_size = NONE RETURN BEFORE", | ||
| 716 | + &[("u".into(), id.record().into_value())], | ||
| 717 | + ) | ||
| 718 | + .await?; | ||
| 719 | + Ok(rows.into_iter().next()) | ||
| 720 | + } | ||
| 721 | + | ||
| 627 | /// Write the UI-preference fields the request actually carried. Same | 722 | /// Write the UI-preference fields the request actually carried. Same |
| 628 | /// contract as [`User::set_profile`]: `None` = omitted (not written), | 723 | /// contract as [`User::set_profile`]: `None` = omitted (not written), |
| 629 | /// `Some(None)` = cleared back to "never chose", `Some(Some(v))` = set. | 724 | /// `Some(None)` = cleared back to "never chose", `Some(Some(v))` = set. |
| @@ -734,7 +829,16 @@ mod tests { | |||
| 734 | // admin's change. | 829 | // admin's change. |
| 735 | let name = PersonName::try_new("name", "AyΕenur").unwrap(); | 830 | let name = PersonName::try_new("name", "AyΕenur").unwrap(); |
| 736 | stale | 831 | stale |
| 737 | - .set_profile(Some(Some(name.clone())), None, None, None, None, &db) | 832 | + .set_profile( |
| 833 | + Some(Some(name.clone())), | ||
| 834 | + None, | ||
| 835 | + None, | ||
| 836 | + None, | ||
| 837 | + None, | ||
| 838 | + None, | ||
| 839 | + None, | ||
| 840 | + &db, | ||
| 841 | + ) | ||
| 738 | .await | 842 | .await |
| 739 | .unwrap(); | 843 | .unwrap(); |
| 740 | 844 | ||
| @@ -751,6 +855,121 @@ mod tests { | |||
| 751 | ); | 855 | ); |
| 752 | } | 856 | } |
| 753 | 857 | ||
| 858 | + fn png() -> FileContentType { | ||
| 859 | + FileContentType::try_new("image/png").unwrap() | ||
| 860 | + } | ||
| 861 | + | ||
| 862 | + async fn a_user(username: &str, db: &Database) -> User { | ||
| 863 | + User::create( | ||
| 864 | + Username::try_new(username).unwrap(), | ||
| 865 | + Password::try_new("secret1").unwrap().hash().unwrap(), | ||
| 866 | + db, | ||
| 867 | + ) | ||
| 868 | + .await | ||
| 869 | + .unwrap() | ||
| 870 | + } | ||
| 871 | + | ||
| 872 | + #[tokio::test] | ||
| 873 | + async fn an_avatar_upload_cannot_revert_a_role_change() { | ||
| 874 | + let db = init_mem().await.unwrap(); | ||
| 875 | + let user = a_user("berk", &db).await; | ||
| 876 | + | ||
| 877 | + // The upload handler holds its snapshot (role = student)... | ||
| 878 | + let stale = User::read(user.get_id(), &db).await.unwrap().unwrap(); | ||
| 879 | + | ||
| 880 | + // ...an admin promotes and the person edits their bio, both while the | ||
| 881 | + // blob is still being written... | ||
| 882 | + User::read(user.get_id(), &db) | ||
| 883 | + .await | ||
| 884 | + .unwrap() | ||
| 885 | + .unwrap() | ||
| 886 | + .set_role(Role::Teacher, &db) | ||
| 887 | + .await | ||
| 888 | + .unwrap(); | ||
| 889 | + let display_name = DisplayName::try_new("Berk").unwrap(); | ||
| 890 | + User::read(user.get_id(), &db) | ||
| 891 | + .await | ||
| 892 | + .unwrap() | ||
| 893 | + .unwrap() | ||
| 894 | + .set_profile( | ||
| 895 | + None, | ||
| 896 | + None, | ||
| 897 | + None, | ||
| 898 | + None, | ||
| 899 | + None, | ||
| 900 | + Some(Some(display_name.clone())), | ||
| 901 | + None, | ||
| 902 | + &db, | ||
| 903 | + ) | ||
| 904 | + .await | ||
| 905 | + .unwrap(); | ||
| 906 | + | ||
| 907 | + // ...and only then does the avatar land, from the stale row's id. | ||
| 908 | + User::set_avatar(stale.get_id(), "blob-1", &png(), 42, &db) | ||
| 909 | + .await | ||
| 910 | + .unwrap() | ||
| 911 | + .expect("the row exists"); | ||
| 912 | + | ||
| 913 | + let after = User::read(user.get_id(), &db).await.unwrap().unwrap(); | ||
| 914 | + assert_eq!( | ||
| 915 | + after.get_role(), | ||
| 916 | + Role::Teacher, | ||
| 917 | + "the role change must survive the racing avatar write" | ||
| 918 | + ); | ||
| 919 | + assert_eq!( | ||
| 920 | + after.get_display_name(), | ||
| 921 | + Some(&display_name), | ||
| 922 | + "and so must every other column the avatar write never named" | ||
| 923 | + ); | ||
| 924 | + assert_eq!(after.get_avatar_file(), Some("blob-1")); | ||
| 925 | + assert_eq!(after.get_avatar_content_type(), Some(&png())); | ||
| 926 | + assert_eq!(after.get_avatar_size(), Some(42)); | ||
| 927 | + } | ||
| 928 | + | ||
| 929 | + /// The blob cleanup is built entirely on `RETURN BEFORE`: without the old | ||
| 930 | + /// `avatar_file` coming back, every replace strands a file on disk that no | ||
| 931 | + /// route ever collects. | ||
| 932 | + #[tokio::test] | ||
| 933 | + async fn the_avatar_writers_return_the_replaced_blob() { | ||
| 934 | + let db = init_mem().await.unwrap(); | ||
| 935 | + let user = a_user("ceyda", &db).await; | ||
| 936 | + | ||
| 937 | + let before = User::set_avatar(user.get_id(), "blob-1", &png(), 10, &db) | ||
| 938 | + .await | ||
| 939 | + .unwrap() | ||
| 940 | + .expect("the row exists"); | ||
| 941 | + assert_eq!(before.get_avatar_file(), None, "no blob to collect yet"); | ||
| 942 | + | ||
| 943 | + let before = User::set_avatar(user.get_id(), "blob-2", &png(), 20, &db) | ||
| 944 | + .await | ||
| 945 | + .unwrap() | ||
| 946 | + .expect("the row exists"); | ||
| 947 | + assert_eq!( | ||
| 948 | + before.get_avatar_file(), | ||
| 949 | + Some("blob-1"), | ||
| 950 | + "the replaced blob is what the caller must delete" | ||
| 951 | + ); | ||
| 952 | + | ||
| 953 | + let before = User::clear_avatar(user.get_id(), &db) | ||
| 954 | + .await | ||
| 955 | + .unwrap() | ||
| 956 | + .expect("the row exists"); | ||
| 957 | + assert_eq!(before.get_avatar_file(), Some("blob-2")); | ||
| 958 | + | ||
| 959 | + let after = User::read(user.get_id(), &db).await.unwrap().unwrap(); | ||
| 960 | + assert_eq!(after.get_avatar_file(), None); | ||
| 961 | + assert_eq!(after.get_avatar_content_type(), None); | ||
| 962 | + assert_eq!(after.get_avatar_size(), None); | ||
| 963 | + | ||
| 964 | + assert!( | ||
| 965 | + User::clear_avatar(&UserId::from_key("yok"), &db) | ||
| 966 | + .await | ||
| 967 | + .unwrap() | ||
| 968 | + .is_none(), | ||
| 969 | + "a missing row is None, not an error" | ||
| 970 | + ); | ||
| 971 | + } | ||
| 972 | + | ||
| 754 | #[tokio::test] | 973 | #[tokio::test] |
| 755 | async fn username_newtype_validates() { | 974 | async fn username_newtype_validates() { |
| 756 | assert_eq!(Username::try_new("ali").unwrap().as_str(), "ali"); | 975 | assert_eq!(Username::try_new("ali").unwrap().as_str(), "ali"); |
src/lib.rsmodified+1 -1
| @@ -44,7 +44,7 @@ use crate::state::AppState; | |||
| 44 | (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling β public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With no certificate configured the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"), | 44 | (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling β public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With no certificate configured the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"), |
| 45 | (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` β the echoed name and the `student` role every fresh account gets β and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"), | 45 | (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` β the echoed name and the `student` role every fresh account gets β and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"), |
| 46 | (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner β nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed β or its name cleared β with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is a claimed job rather than an in-process task: whichever backend process holds a `chat.reply` worker picks it up (within ~200ms), dispatches it and stamps the result, so a restart no longer strands an accepted turn and a claim its owner never finishes is retried after 90 seconds. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) β both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` β the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"), | 46 | (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner β nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed β or its name cleared β with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is a claimed job rather than an in-process task: whichever backend process holds a `chat.reply` worker picks it up (within ~200ms), dispatches it and stamps the result, so a restart no longer strands an accepted turn and a claim its owner never finishes is retried after 90 seconds. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) β both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` β the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"), |
| 47 | - (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` β returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). Also the parentβstudent ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink β a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else"), | 47 | + (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` β returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). Also the parentβstudent ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink β a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` β it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only β never a class's creator or homeroom teacher β capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), and stats computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts; `0`, never `null`). Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile β except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created β and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter, and `stats.courses` stays the owner's true total either way. `display_name` (β€ 50) and `bio` (β€ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only β no SVG, whose script can run when the bytes render inline school-wide β at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` β or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id β (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"), |
| 48 | (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete β at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"), | 48 | (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete β at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"), |
| 49 | (name = "messages", description = "One-to-one mail-style messages between any two users (parents included β messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread β with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), | 49 | (name = "messages", description = "One-to-one mail-style messages between any two users (parents included β messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread β with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), |
| 50 | (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00β10:30 and 10:30β11:00 are two slots and not a collision, and a weekly publish is all-or-nothing β one colliding occurrence refuses the whole series. Students and parents book one with a required reason β a parent books for themselves, this is the parent-teacher conference β and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked, an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel β declining included, since a decline *is* a cancel β only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) β visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"), | 50 | (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00β10:30 and 10:30β11:00 are two slots and not a collision, and a weekly publish is all-or-nothing β one colliding occurrence refuses the whole series. Students and parents book one with a required reason β a parent books for themselves, this is the parent-teacher conference β and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked, an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel β declining included, since a decline *is* a cancel β only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) β visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"), |
src/migration_sql.rsmodified+5 -0
| @@ -58,6 +58,11 @@ pub const MIGRATION: &str = " | |||
| 58 | DEFINE FIELD IF NOT EXISTS theme ON user TYPE option<string>; | 58 | DEFINE FIELD IF NOT EXISTS theme ON user TYPE option<string>; |
| 59 | DEFINE FIELD IF NOT EXISTS language ON user TYPE option<string>; | 59 | DEFINE FIELD IF NOT EXISTS language ON user TYPE option<string>; |
| 60 | DEFINE FIELD IF NOT EXISTS palette_color ON user TYPE option<string>; | 60 | DEFINE FIELD IF NOT EXISTS palette_color ON user TYPE option<string>; |
| 61 | + DEFINE FIELD IF NOT EXISTS display_name ON user TYPE option<string>; | ||
| 62 | + DEFINE FIELD IF NOT EXISTS bio ON user TYPE option<string>; | ||
| 63 | + DEFINE FIELD IF NOT EXISTS avatar_file ON user TYPE option<string>; | ||
| 64 | + DEFINE FIELD IF NOT EXISTS avatar_content_type ON user TYPE option<string>; | ||
| 65 | + DEFINE FIELD IF NOT EXISTS avatar_size ON user TYPE option<int>; | ||
| 61 | DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option<int>; | 66 | DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option<int>; |
| 62 | DEFINE FIELD IF NOT EXISTS board_count ON user TYPE option<int>; | 67 | DEFINE FIELD IF NOT EXISTS board_count ON user TYPE option<int>; |
| 63 | DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; | 68 | DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; |
src/web/dto.rsmodified+10 -0
| @@ -140,6 +140,14 @@ pub struct UserResponse { | |||
| 140 | /// never chosen β the client should fall back to its default accent. | 140 | /// never chosen β the client should fall back to its default accent. |
| 141 | #[schema(example = "#fefae0")] | 141 | #[schema(example = "#fefae0")] |
| 142 | pub palette_color: Option<String>, | 142 | pub palette_color: Option<String>, |
| 143 | + /// The name the public profile is shown under, instead of the legal one. | ||
| 144 | + /// `null` = never chosen; unlike [`PersonRef::display_name`] this is the | ||
| 145 | + /// stored column, never a fallback to `"Name Surname"`. | ||
| 146 | + #[schema(example = "Ada")] | ||
| 147 | + pub display_name: Option<String>, | ||
| 148 | + /// Free text under the profile's name; `null` when unset. | ||
| 149 | + #[schema(example = "SΔ±nΔ±fΔ±n en hΔ±zlΔ± pomodorocusu.")] | ||
| 150 | + pub bio: Option<String>, | ||
| 143 | } | 151 | } |
| 144 | 152 | ||
| 145 | impl UserResponse { | 153 | impl UserResponse { |
| @@ -156,6 +164,8 @@ impl UserResponse { | |||
| 156 | theme: user.get_theme().map(|v| v.as_str().to_string()), | 164 | theme: user.get_theme().map(|v| v.as_str().to_string()), |
| 157 | language: user.get_language().map(|v| v.as_str().to_string()), | 165 | language: user.get_language().map(|v| v.as_str().to_string()), |
| 158 | palette_color: user.get_palette_color().map(|v| v.as_str().to_string()), | 166 | palette_color: user.get_palette_color().map(|v| v.as_str().to_string()), |
| 167 | + display_name: user.get_display_name().map(|v| v.as_str().to_string()), | ||
| 168 | + bio: user.get_bio().map(|v| v.as_str().to_string()), | ||
| 159 | } | 169 | } |
| 160 | } | 170 | } |
| 161 | } | 171 | } |
src/web/limits.rsmodified+13 -0
| @@ -39,6 +39,15 @@ struct UserLimits { | |||
| 39 | min_password_len: usize, | 39 | min_password_len: usize, |
| 40 | max_password_len: usize, | 40 | max_password_len: usize, |
| 41 | max_name_len: usize, | 41 | max_name_len: usize, |
| 42 | + /// The self-chosen name a user's profile is shown under. | ||
| 43 | + max_display_name_len: usize, | ||
| 44 | + /// Free text under a profile's name. | ||
| 45 | + max_bio_len: usize, | ||
| 46 | + /// How many course references a profile read embeds β a cap on the | ||
| 47 | + /// response, not on membership. The full list stays at `/courses/me`. | ||
| 48 | + max_profile_courses: usize, | ||
| 49 | + /// Same, for classes; the full list stays at `/classes/me`. | ||
| 50 | + max_profile_classes: usize, | ||
| 42 | max_email_len: usize, | 51 | max_email_len: usize, |
| 43 | /// Digit count, ignoring spaces and punctuation. | 52 | /// Digit count, ignoring spaces and punctuation. |
| 44 | min_phone_digits: usize, | 53 | min_phone_digits: usize, |
| @@ -388,6 +397,10 @@ impl LimitsResponse { | |||
| 388 | min_password_len: MIN_PASSWORD_LEN, | 397 | min_password_len: MIN_PASSWORD_LEN, |
| 389 | max_password_len: MAX_PASSWORD_LEN, | 398 | max_password_len: MAX_PASSWORD_LEN, |
| 390 | max_name_len: MAX_NAME_LEN, | 399 | max_name_len: MAX_NAME_LEN, |
| 400 | + max_display_name_len: MAX_DISPLAY_NAME_LEN, | ||
| 401 | + max_bio_len: MAX_BIO_LEN, | ||
| 402 | + max_profile_courses: MAX_PROFILE_COURSES, | ||
| 403 | + max_profile_classes: MAX_PROFILE_CLASSES, | ||
| 391 | max_email_len: MAX_EMAIL_LEN, | 404 | max_email_len: MAX_EMAIL_LEN, |
| 392 | min_phone_digits: MIN_PHONE_DIGITS, | 405 | min_phone_digits: MIN_PHONE_DIGITS, |
| 393 | max_phone_digits: MAX_PHONE_DIGITS, | 406 | max_phone_digits: MAX_PHONE_DIGITS, |
src/web/users.rsmodified+466 -7
| @@ -1,24 +1,34 @@ | |||
| 1 | use axum::Json; | 1 | use axum::Json; |
| 2 | -use axum::extract::{Path, Query, State}; | 2 | +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; |
| 3 | use axum::http::StatusCode; | 3 | use axum::http::StatusCode; |
| 4 | +use axum::response::Response; | ||
| 4 | use serde::{Deserialize, Serialize}; | 5 | use serde::{Deserialize, Serialize}; |
| 5 | use serde_json::json; | 6 | use serde_json::json; |
| 6 | use utoipa::{IntoParams, ToSchema}; | 7 | use utoipa::{IntoParams, ToSchema}; |
| 7 | use utoipa_axum::router::OpenApiRouter; | 8 | use utoipa_axum::router::OpenApiRouter; |
| 8 | use utoipa_axum::routes; | 9 | use utoipa_axum::routes; |
| 9 | 10 | ||
| 11 | +use crate::constant::{ | ||
| 12 | + MAX_MAX_FILE_BYTES, MAX_PROFILE_CLASSES, MAX_PROFILE_COURSES, UPLOAD_BODY_OVERHEAD_BYTES, | ||
| 13 | +}; | ||
| 10 | use crate::database::Database; | 14 | use crate::database::Database; |
| 15 | +use crate::domain::class_group::{ClassGroup, ClassGroupId}; | ||
| 16 | +use crate::domain::class_member::ClassMember; | ||
| 17 | +use crate::domain::course::Course; | ||
| 11 | use crate::domain::parent_link::ParentLink; | 18 | use crate::domain::parent_link::ParentLink; |
| 12 | use crate::domain::preferences::{Language, PaletteColor, Theme}; | 19 | use crate::domain::preferences::{Language, PaletteColor, Theme}; |
| 13 | -use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; | 20 | +use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone, ProfileStats}; |
| 14 | use crate::domain::role::Role; | 21 | use crate::domain::role::Role; |
| 15 | use crate::domain::user::{User, UserId}; | 22 | use crate::domain::user::{User, UserId}; |
| 16 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 23 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 17 | use crate::state::AppState; | 24 | use crate::state::AppState; |
| 18 | 25 | ||
| 26 | +use super::courses::visible_courses; | ||
| 19 | use super::dto::Role as RoleSchema; | 27 | use super::dto::Role as RoleSchema; |
| 20 | use super::{ | 28 | use super::{ |
| 21 | - CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireTeacher, UserResponse, paginate, | 29 | + CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireTeacher, UploadFileForm, |
| 30 | + UserResponse, ensure_can_observe, paginate, read_image_upload, remove_blob, serve_inline_blob, | ||
| 31 | + store_blob, | ||
| 22 | }; | 32 | }; |
| 23 | 33 | ||
| 24 | pub fn routes() -> OpenApiRouter<AppState> { | 34 | pub fn routes() -> OpenApiRouter<AppState> { |
| @@ -27,13 +37,26 @@ pub fn routes() -> OpenApiRouter<AppState> { | |||
| 27 | .routes(routes!(update_my_profile)) | 37 | .routes(routes!(update_my_profile)) |
| 28 | .routes(routes!(update_my_preferences)) | 38 | .routes(routes!(update_my_preferences)) |
| 29 | .routes(routes!(my_students)) | 39 | .routes(routes!(my_students)) |
| 40 | + .routes(routes!(my_profile)) | ||
| 30 | .routes(routes!(search_users)) | 41 | .routes(routes!(search_users)) |
| 31 | .routes(routes!(get_user)) | 42 | .routes(routes!(get_user)) |
| 32 | .routes(routes!(set_role)) | 43 | .routes(routes!(set_role)) |
| 33 | - .routes(routes!(update_user_profile)) | 44 | + .routes(routes!(update_user_profile, get_user_profile)) |
| 34 | .routes(routes!(update_user_preferences)) | 45 | .routes(routes!(update_user_preferences)) |
| 35 | .routes(routes!(link_student, list_parent_students)) | 46 | .routes(routes!(link_student, list_parent_students)) |
| 36 | .routes(routes!(unlink_student)) | 47 | .routes(routes!(unlink_student)) |
| 48 | + // The avatar routes get their own HTTP body cap, like the note-file and | ||
| 49 | + // question-image ones: the server-wide hard ceiling plus multipart | ||
| 50 | + // framing headroom. It must stay on this sub-router β on the whole | ||
| 51 | + // `/users` router every JSON endpoint would start accepting 25 MB. | ||
| 52 | + .merge( | ||
| 53 | + OpenApiRouter::new() | ||
| 54 | + .routes(routes!(upload_my_avatar, get_my_avatar, delete_my_avatar)) | ||
| 55 | + .routes(routes!(get_avatar, delete_avatar)) | ||
| 56 | + .layer(DefaultBodyLimit::max( | ||
| 57 | + MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES, | ||
| 58 | + )), | ||
| 59 | + ) | ||
| 37 | } | 60 | } |
| 38 | 61 | ||
| 39 | #[derive(Deserialize, ToSchema)] | 62 | #[derive(Deserialize, ToSchema)] |
| @@ -61,6 +84,12 @@ struct UpdateProfile { | |||
| 61 | /// Birth date in `YYYY-MM-DD` form. | 84 | /// Birth date in `YYYY-MM-DD` form. |
| 62 | #[schema(example = "1990-01-02")] | 85 | #[schema(example = "1990-01-02")] |
| 63 | birth_date: Option<String>, | 86 | birth_date: Option<String>, |
| 87 | + /// The name the public profile is shown under, instead of the legal one. | ||
| 88 | + #[schema(example = "Ada", max_length = 50)] | ||
| 89 | + display_name: Option<String>, | ||
| 90 | + /// Free text under the profile's name. | ||
| 91 | + #[schema(example = "SΔ±nΔ±fΔ±n en hΔ±zlΔ± pomodorocusu.", max_length = 500)] | ||
| 92 | + bio: Option<String>, | ||
| 64 | } | 93 | } |
| 65 | 94 | ||
| 66 | /// Partial UI-preference update. Same field semantics as [`UpdateProfile`]: | 95 | /// Partial UI-preference update. Same field semantics as [`UpdateProfile`]: |
| @@ -112,8 +141,19 @@ async fn apply_profile( | |||
| 112 | let email = merge_field(req.email.as_deref(), Email::try_new)?; | 141 | let email = merge_field(req.email.as_deref(), Email::try_new)?; |
| 113 | let phone = merge_field(req.phone.as_deref(), Phone::try_new)?; | 142 | let phone = merge_field(req.phone.as_deref(), Phone::try_new)?; |
| 114 | let birth_date = merge_field(req.birth_date.as_deref(), BirthDate::try_new)?; | 143 | let birth_date = merge_field(req.birth_date.as_deref(), BirthDate::try_new)?; |
| 144 | + let display_name = merge_field(req.display_name.as_deref(), DisplayName::try_new)?; | ||
| 145 | + let bio = merge_field(req.bio.as_deref(), Bio::try_new)?; | ||
| 115 | let updated = user | 146 | let updated = user |
| 116 | - .set_profile(name, surname, email, phone, birth_date, db) | 147 | + .set_profile( |
| 148 | + name, | ||
| 149 | + surname, | ||
| 150 | + email, | ||
| 151 | + phone, | ||
| 152 | + birth_date, | ||
| 153 | + display_name, | ||
| 154 | + bio, | ||
| 155 | + db, | ||
| 156 | + ) | ||
| 117 | .await?; | 157 | .await?; |
| 118 | Ok(UserResponse::new(&updated)) | 158 | Ok(UserResponse::new(&updated)) |
| 119 | } | 159 | } |
| @@ -222,8 +262,10 @@ async fn list_users( | |||
| 222 | } | 262 | } |
| 223 | 263 | ||
| 224 | /// Update the caller's own personal info: name, surname, email, phone, birth | 264 | /// Update the caller's own personal info: name, surname, email, phone, birth |
| 225 | -/// date. Any authenticated role. Omitted fields stay as they are; an empty | 265 | +/// date, plus the public-profile pair `display_name` and `bio` (both readable |
| 226 | -/// string clears a field. | 266 | +/// school-wide at `GET /users/{id}/profile`, unlike the contact fields). Any |
| 267 | +/// authenticated role. Omitted fields stay as they are; an empty string clears | ||
| 268 | +/// a field. | ||
| 227 | #[utoipa::path( | 269 | #[utoipa::path( |
| 228 | patch, | 270 | patch, |
| 229 | path = "/me", | 271 | path = "/me", |
| @@ -615,3 +657,420 @@ async fn my_students( | |||
| 615 | } | 657 | } |
| 616 | Ok(Json(students_page(user.get_id(), page, &st.db).await?)) | 658 | Ok(Json(students_page(user.get_id(), page, &st.db).await?)) |
| 617 | } | 659 | } |
| 660 | + | ||
| 661 | +// ---- the public profile ----------------------------------------------------- | ||
| 662 | +// The school-wide read half of a user row: who they are, what they belong to, | ||
| 663 | +// and the counters that motivate. Deliberately *not* `UserResponse` β that one | ||
| 664 | +// carries email, phone, and birth date, which keep exactly the gate they have | ||
| 665 | +// today (self, teacher+, admin). Nothing here widens where they are reachable. | ||
| 666 | + | ||
| 667 | +/// A user's public profile. Contact details are not part of it, at any role. | ||
| 668 | +#[derive(Serialize, ToSchema)] | ||
| 669 | +struct ProfileResponse { | ||
| 670 | + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | ||
| 671 | + id: String, | ||
| 672 | + #[schema(example = "ada")] | ||
| 673 | + username: String, | ||
| 674 | + /// The self-chosen `display_name`, falling back to `"Name Surname"`, then | ||
| 675 | + /// `null` when the row carries neither. | ||
| 676 | + #[schema(example = "Ada Lovelace")] | ||
| 677 | + display_name: Option<String>, | ||
| 678 | + role: RoleSchema, | ||
| 679 | + #[schema(example = "SΔ±nΔ±fΔ±n en hΔ±zlΔ± pomodorocusu.")] | ||
| 680 | + bio: Option<String>, | ||
| 681 | + /// Present only once a picture is uploaded; the bytes are at | ||
| 682 | + /// `GET /users/{id}/avatar`. | ||
| 683 | + avatar: Option<ProfileAvatar>, | ||
| 684 | + /// At most `max_profile_classes` sections β the full list is at | ||
| 685 | + /// `GET /classes/me`. | ||
| 686 | + classes: Vec<ProfileClassRef>, | ||
| 687 | + /// At most `max_profile_courses` courses, and only the ones the *reader* | ||
| 688 | + /// may already read at `GET /courses/{id}` β a stranger sees an empty | ||
| 689 | + /// block, the owner and manager+ see it whole. The full list is at | ||
| 690 | + /// `GET /courses/me`. | ||
| 691 | + courses: Vec<ProfileCourseRef>, | ||
| 692 | + stats: ProfileStatsResponse, | ||
| 693 | +} | ||
| 694 | + | ||
| 695 | +/// What a stored avatar is, without its bytes. | ||
| 696 | +#[derive(Serialize, ToSchema)] | ||
| 697 | +struct ProfileAvatar { | ||
| 698 | + #[schema(example = "image/png")] | ||
| 699 | + content_type: String, | ||
| 700 | + /// Size in bytes. | ||
| 701 | + #[schema(example = 20_480)] | ||
| 702 | + size: i64, | ||
| 703 | +} | ||
| 704 | + | ||
| 705 | +/// A class section as a profile shows it: the label, and nothing about who runs | ||
| 706 | +/// it. The office-side view (creator, homeroom teacher) stays behind | ||
| 707 | +/// `GET /classes/{id}`, which is teacher+. | ||
| 708 | +#[derive(Serialize, ToSchema)] | ||
| 709 | +struct ProfileClassRef { | ||
| 710 | + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | ||
| 711 | + id: String, | ||
| 712 | + #[schema(example = "9-A")] | ||
| 713 | + name: String, | ||
| 714 | + #[schema(example = "9")] | ||
| 715 | + grade: Option<String>, | ||
| 716 | +} | ||
| 717 | + | ||
| 718 | +/// A course as a profile shows it β a label, nothing more. | ||
| 719 | +#[derive(Serialize, ToSchema)] | ||
| 720 | +struct ProfileCourseRef { | ||
| 721 | + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | ||
| 722 | + id: String, | ||
| 723 | + #[schema(example = "Matematik")] | ||
| 724 | + title: String, | ||
| 725 | + /// `course`, `study` (etΓΌt), or `club` (kulΓΌp). | ||
| 726 | + #[schema(example = "course")] | ||
| 727 | + kind: String, | ||
| 728 | +} | ||
| 729 | + | ||
| 730 | +/// The motivational counters. Derived, never settable, and never `null`: an | ||
| 731 | +/// account with no rows behind a counter reads a true `0`. | ||
| 732 | +#[derive(Serialize, ToSchema)] | ||
| 733 | +struct ProfileStatsResponse { | ||
| 734 | + /// Finished pomodoro stints; an open one counts for nothing. | ||
| 735 | + pomodoro_sessions: i64, | ||
| 736 | + /// Total focused milliseconds across those stints. | ||
| 737 | + pomodoro_focus_ms: i64, | ||
| 738 | + /// Every course behind the `courses` block, not just the embedded window. | ||
| 739 | + courses: i64, | ||
| 740 | + /// Every class behind the `classes` block, not just the embedded window. | ||
| 741 | + classes: i64, | ||
| 742 | +} | ||
| 743 | + | ||
| 744 | +/// Build one profile as `viewer` may see it. The course block is chosen off the | ||
| 745 | +/// owner's **live** role, not off the `creator`/`teachers` columns: those are | ||
| 746 | +/// historical and no demotion sweeps them, so a demoted ex-teacher lists what | ||
| 747 | +/// they are enrolled in, like any other student. | ||
| 748 | +/// | ||
| 749 | +/// A course carries a title, and `GET /courses/{id}` hands that title only to | ||
| 750 | +/// the enrolled, the staff who run it, and manager+ β so the block is | ||
| 751 | +/// intersected with [`visible_courses`], the same catalog `GET /courses` | ||
| 752 | +/// serves. Nothing here crosses a gate the viewer would fail directly. Reading | ||
| 753 | +/// your own profile, or reading as manager+, needs no intersection: both | ||
| 754 | +/// already see the whole list. `stats.courses` stays the owner's true total β | ||
| 755 | +/// it is the motivational counter, and a magnitude names no course. | ||
| 756 | +async fn profile_of( | ||
| 757 | + st: &AppState, | ||
| 758 | + user: &User, | ||
| 759 | + viewer: &User, | ||
| 760 | +) -> Result<ProfileResponse, AppError> { | ||
| 761 | + let id = user.get_id(); | ||
| 762 | + // One catalog read per request, never one authorization call per course. | ||
| 763 | + let readable = match viewer.get_id() == id || viewer.get_role().at_least(Role::Manager) { | ||
| 764 | + true => None, | ||
| 765 | + false => Some( | ||
| 766 | + visible_courses(viewer, &st.db) | ||
| 767 | + .await? | ||
| 768 | + .iter() | ||
| 769 | + .map(|course| course.get_id().clone()) | ||
| 770 | + .collect::<Vec<_>>(), | ||
| 771 | + ), | ||
| 772 | + }; | ||
| 773 | + // The window is cut after the intersection, so a filtered viewer still gets | ||
| 774 | + // up to `MAX_PROFILE_COURSES` courses they can actually see. | ||
| 775 | + let (mut courses, course_total) = match user.get_role().at_least(Role::Teacher) { | ||
| 776 | + // The teacher read is unpaged, so the total is what came back. | ||
| 777 | + true => { | ||
| 778 | + let courses = Course::list_for_teacher(id, &st.db).await?; | ||
| 779 | + let total = courses.len() as i64; | ||
| 780 | + (courses, total) | ||
| 781 | + } | ||
| 782 | + // Unfiltered readers can take the window from the database. | ||
| 783 | + false => { | ||
| 784 | + let window = readable.is_none().then_some(MAX_PROFILE_COURSES as i64); | ||
| 785 | + Course::list_enrolled(id, window, 0, &st.db).await? | ||
| 786 | + } | ||
| 787 | + }; | ||
| 788 | + if let Some(readable) = &readable { | ||
| 789 | + courses.retain(|course| readable.contains(course.get_id())); | ||
| 790 | + } | ||
| 791 | + courses.truncate(MAX_PROFILE_COURSES); | ||
| 792 | + let (members, class_total) = | ||
| 793 | + ClassMember::list_for_user(id, Some(MAX_PROFILE_CLASSES as i64), 0, &st.db).await?; | ||
| 794 | + let class_ids: Vec<ClassGroupId> = members.iter().map(|row| row.get_class().clone()).collect(); | ||
| 795 | + let classes = ClassGroup::list_by_ids(&class_ids, &st.db).await?; | ||
| 796 | + // Both totals are the full counts, not the windowed ones β the blocks are a | ||
| 797 | + // preview, the stats are the truth. | ||
| 798 | + let stats = ProfileStats::load(id, course_total, class_total, &st.db).await?; | ||
| 799 | + Ok(ProfileResponse { | ||
| 800 | + id: id.key().to_string(), | ||
| 801 | + username: user.get_username().as_str().to_string(), | ||
| 802 | + display_name: user | ||
| 803 | + .get_display_name() | ||
| 804 | + .map(|name| name.as_str().to_string()) | ||
| 805 | + // The legal-name join lives in `PersonRef` β one spelling of it. | ||
| 806 | + .or_else(|| PersonRef::new(user).display_name), | ||
| 807 | + role: user.get_role().into(), | ||
| 808 | + bio: user.get_bio().map(|bio| bio.as_str().to_string()), | ||
| 809 | + avatar: user | ||
| 810 | + .get_avatar_content_type() | ||
| 811 | + .map(|content_type| ProfileAvatar { | ||
| 812 | + content_type: content_type.as_str().to_string(), | ||
| 813 | + size: user.get_avatar_size().unwrap_or_default(), | ||
| 814 | + }), | ||
| 815 | + classes: classes | ||
| 816 | + .iter() | ||
| 817 | + .map(|class| ProfileClassRef { | ||
| 818 | + id: class.get_id().key().to_string(), | ||
| 819 | + name: class.get_name().as_str().to_string(), | ||
| 820 | + grade: class.get_grade().map(|grade| grade.as_str().to_string()), | ||
| 821 | + }) | ||
| 822 | + .collect(), | ||
| 823 | + courses: courses | ||
| 824 | + .iter() | ||
| 825 | + .map(|course| ProfileCourseRef { | ||
| 826 | + id: course.get_id().key().to_string(), | ||
| 827 | + title: course.get_title().as_str().to_string(), | ||
| 828 | + kind: course.get_kind().as_str().to_string(), | ||
| 829 | + }) | ||
| 830 | + .collect(), | ||
| 831 | + stats: ProfileStatsResponse { | ||
| 832 | + pomodoro_sessions: stats.get_pomodoro_sessions(), | ||
| 833 | + pomodoro_focus_ms: stats.get_pomodoro_focus_ms(), | ||
| 834 | + courses: stats.get_courses(), | ||
| 835 | + classes: stats.get_classes(), | ||
| 836 | + }, | ||
| 837 | + }) | ||
| 838 | +} | ||
| 839 | + | ||
| 840 | +/// The profile gate: any authenticated account reads any profile β except a | ||
| 841 | +/// parent, who is an observer of their own children and of nobody else. The | ||
| 842 | +/// link alone is not the grant either; [`ensure_can_observe`] re-reads the | ||
| 843 | +/// target's live role, so a student who was promoted out stops being readable. | ||
| 844 | +async fn ensure_may_read_profile( | ||
| 845 | + caller: &User, | ||
| 846 | + target: &UserId, | ||
| 847 | + db: &Database, | ||
| 848 | +) -> Result<(), AppError> { | ||
| 849 | + if caller.get_role() == Role::Parent && caller.get_id() != target { | ||
| 850 | + ensure_can_observe(caller, target, db).await?; | ||
| 851 | + } | ||
| 852 | + Ok(()) | ||
| 853 | +} | ||
| 854 | + | ||
| 855 | +/// The target's row, 404 if it is gone, once the caller is allowed to see it. | ||
| 856 | +async fn readable_profile_user(st: &AppState, caller: &User, id: &str) -> Result<User, AppError> { | ||
| 857 | + let target = UserId::from_key(id); | ||
| 858 | + ensure_may_read_profile(caller, &target, &st.db).await?; | ||
| 859 | + User::read(&target, &st.db).await?.ok_or(AppError::NotFound) | ||
| 860 | +} | ||
| 861 | + | ||
| 862 | +/// The caller's own public profile β what everyone else sees of them. | ||
| 863 | +#[utoipa::path( | ||
| 864 | + get, | ||
| 865 | + path = "/me/profile", | ||
| 866 | + tag = "users", | ||
| 867 | + security(("session_cookie" = [])), | ||
| 868 | + responses( | ||
| 869 | + (status = 200, description = "The caller's profile", body = ProfileResponse), | ||
| 870 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 871 | + ), | ||
| 872 | +)] | ||
| 873 | +async fn my_profile( | ||
| 874 | + State(st): State<AppState>, | ||
| 875 | + CurrentUser(user): CurrentUser, | ||
| 876 | +) -> Result<Json<ProfileResponse>, AppError> { | ||
| 877 | + Ok(Json(profile_of(&st, &user, &user).await?)) | ||
| 878 | +} | ||
| 879 | + | ||
| 880 | +/// One user's public profile: display name, bio, avatar meta, their class and | ||
| 881 | +/// course blocks, and the motivational counters. Readable by every | ||
| 882 | +/// authenticated account β except a parent, who reads only their own and their | ||
| 883 | +/// linked students'. Never carries email, phone, or birth date; those stay on | ||
| 884 | +/// `GET /users/{id}` (admin) and `GET /auth/me`. The embedded blocks are capped | ||
| 885 | +/// at `max_profile_classes` / `max_profile_courses` (see `GET /limits`) β the | ||
| 886 | +/// full paged lists are `GET /classes/me` and `GET /courses/me`. The course | ||
| 887 | +/// block is also cut to what the *reader* may already see: only courses they | ||
| 888 | +/// would pass `GET /courses/{id}` on. `stats.courses` stays the owner's true | ||
| 889 | +/// total either way. | ||
| 890 | +#[utoipa::path( | ||
| 891 | + get, | ||
| 892 | + path = "/{id}/profile", | ||
| 893 | + tag = "users", | ||
| 894 | + security(("session_cookie" = [])), | ||
| 895 | + params(("id" = String, Path, description = "User id")), | ||
| 896 | + responses( | ||
| 897 | + (status = 200, description = "The user's profile", body = ProfileResponse), | ||
| 898 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 899 | + (status = 403, description = "A parent without a link to this student", body = ErrorResponse), | ||
| 900 | + (status = 404, description = "User not found", body = ErrorResponse), | ||
| 901 | + ), | ||
| 902 | +)] | ||
| 903 | +async fn get_user_profile( | ||
| 904 | + State(st): State<AppState>, | ||
| 905 | + CurrentUser(caller): CurrentUser, | ||
| 906 | + Path(id): Path<String>, | ||
| 907 | +) -> Result<Json<ProfileResponse>, AppError> { | ||
| 908 | + let target = readable_profile_user(&st, &caller, &id).await?; | ||
| 909 | + Ok(Json(profile_of(&st, &target, &caller).await?)) | ||
| 910 | +} | ||
| 911 | + | ||
| 912 | +// ---- the avatar ------------------------------------------------------------- | ||
| 913 | +// One optional picture per user, the same one-image-on-the-owning-row shape the | ||
| 914 | +// question pool uses: bytes on disk under a server-generated ULID, metadata on | ||
| 915 | +// the user row. Every write here must take the replaced blob off disk β no | ||
| 916 | +// route deletes a user, so nothing else would ever collect it. | ||
| 917 | + | ||
| 918 | +/// Upload (or replace) the caller's own avatar. `multipart/form-data` with the | ||
| 919 | +/// image under a `file` field; the declared content type must be `image/png`, | ||
| 920 | +/// `image/jpeg`, `image/webp`, or `image/gif` (rasters only β no SVG), the | ||
| 921 | +/// bytes at most the school's `max_file_bytes` (settings). Replacing one drops | ||
| 922 | +/// the previous picture. | ||
| 923 | +#[utoipa::path( | ||
| 924 | + post, | ||
| 925 | + path = "/me/avatar", | ||
| 926 | + tag = "users", | ||
| 927 | + security(("session_cookie" = [])), | ||
| 928 | + request_body(content = UploadFileForm, content_type = "multipart/form-data"), | ||
| 929 | + responses( | ||
| 930 | + (status = 201, description = "Avatar stored", body = ProfileAvatar), | ||
| 931 | + (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse), | ||
| 932 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 933 | + (status = 404, description = "The account no longer exists", body = ErrorResponse), | ||
| 934 | + (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), | ||
| 935 | + ), | ||
| 936 | +)] | ||
| 937 | +async fn upload_my_avatar( | ||
| 938 | + State(st): State<AppState>, | ||
| 939 | + CurrentUser(user): CurrentUser, | ||
| 940 | + mut multipart: Multipart, | ||
| 941 | +) -> Result<(StatusCode, Json<ProfileAvatar>), AppError> { | ||
| 942 | + let upload = read_image_upload(&st, &mut multipart).await?; | ||
| 943 | + let size = upload.size(); | ||
| 944 | + | ||
| 945 | + let file = ulid::Ulid::new().to_string(); | ||
| 946 | + store_blob(&st, &file, &upload.data, || async { | ||
| 947 | + match User::set_avatar(user.get_id(), &file, &upload.content_type, size, &st.db).await? { | ||
| 948 | + // Row written; the picture this one replaced comes off disk. | ||
| 949 | + Some(before) => Ok(((), before.get_avatar_file().map(str::to_string))), | ||
| 950 | + // The account went away mid-upload β the fresh blob is an orphan. | ||
| 951 | + None => Err(AppError::NotFound), | ||
| 952 | + } | ||
| 953 | + }) | ||
| 954 | + .await?; | ||
| 955 | + Ok(( | ||
| 956 | + StatusCode::CREATED, | ||
| 957 | + Json(ProfileAvatar { | ||
| 958 | + content_type: upload.content_type.as_str().to_string(), | ||
| 959 | + size, | ||
| 960 | + }), | ||
| 961 | + )) | ||
| 962 | +} | ||
| 963 | + | ||
| 964 | +/// The caller's own avatar bytes. The self alias of `GET /{id}/avatar` β the | ||
| 965 | +/// static `/me/avatar` segment wins over `/{id}/avatar` in the router, so | ||
| 966 | +/// without this a client that never learned its own id gets a bodyless `405` | ||
| 967 | +/// on the obvious route. It serves the caller's own row and nothing else, so | ||
| 968 | +/// it asks no gate: the session already proves the reach. | ||
| 969 | +#[utoipa::path( | ||
| 970 | + get, | ||
| 971 | + path = "/me/avatar", | ||
| 972 | + tag = "users", | ||
| 973 | + security(("session_cookie" = [])), | ||
| 974 | + responses( | ||
| 975 | + (status = 200, description = "The image bytes", content_type = "image/*"), | ||
| 976 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 977 | + (status = 404, description = "The caller has no avatar", body = ErrorResponse), | ||
| 978 | + ), | ||
| 979 | +)] | ||
| 980 | +async fn get_my_avatar( | ||
| 981 | + State(st): State<AppState>, | ||
| 982 | + CurrentUser(user): CurrentUser, | ||
| 983 | +) -> Result<Response, AppError> { | ||
| 984 | + serve_avatar(&st, &user).await | ||
| 985 | +} | ||
| 986 | + | ||
| 987 | +/// The avatar bytes. Same reach as the profile itself: every authenticated | ||
| 988 | +/// account, except a parent, who is limited to their own and their linked | ||
| 989 | +/// students'. | ||
| 990 | +#[utoipa::path( | ||
| 991 | + get, | ||
| 992 | + path = "/{id}/avatar", | ||
| 993 | + tag = "users", | ||
| 994 | + security(("session_cookie" = [])), | ||
| 995 | + params(("id" = String, Path, description = "User id")), | ||
| 996 | + responses( | ||
| 997 | + (status = 200, description = "The image bytes", content_type = "image/*"), | ||
| 998 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 999 | + (status = 403, description = "A parent without a link to this student", body = ErrorResponse), | ||
| 1000 | + (status = 404, description = "No such user, or they have no avatar", body = ErrorResponse), | ||
| 1001 | + ), | ||
| 1002 | +)] | ||
| 1003 | +async fn get_avatar( | ||
| 1004 | + State(st): State<AppState>, | ||
| 1005 | + CurrentUser(caller): CurrentUser, | ||
| 1006 | + Path(id): Path<String>, | ||
| 1007 | +) -> Result<Response, AppError> { | ||
| 1008 | + let target = readable_profile_user(&st, &caller, &id).await?; | ||
| 1009 | + serve_avatar(&st, &target).await | ||
| 1010 | +} | ||
| 1011 | + | ||
| 1012 | +/// The shared tail of both avatar reads: the bytes, or a `404` when the row | ||
| 1013 | +/// carries none. The caller owns the gate β this one is reached already. | ||
| 1014 | +async fn serve_avatar(st: &AppState, user: &User) -> Result<Response, AppError> { | ||
| 1015 | + match (user.get_avatar_file(), user.get_avatar_content_type()) { | ||
| 1016 | + (Some(file), Some(content_type)) => { | ||
| 1017 | + serve_inline_blob(&st.files_path, file, content_type).await | ||
| 1018 | + } | ||
| 1019 | + _ => Err(AppError::NotFound), | ||
| 1020 | + } | ||
| 1021 | +} | ||
| 1022 | + | ||
| 1023 | +/// Remove the caller's own avatar. | ||
| 1024 | +#[utoipa::path( | ||
| 1025 | + delete, | ||
| 1026 | + path = "/me/avatar", | ||
| 1027 | + tag = "users", | ||
| 1028 | + security(("session_cookie" = [])), | ||
| 1029 | + responses( | ||
| 1030 | + (status = 204, description = "Avatar removed"), | ||
| 1031 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 1032 | + (status = 404, description = "No avatar to remove", body = ErrorResponse), | ||
| 1033 | + ), | ||
| 1034 | +)] | ||
| 1035 | +async fn delete_my_avatar( | ||
| 1036 | + State(st): State<AppState>, | ||
| 1037 | + CurrentUser(user): CurrentUser, | ||
| 1038 | +) -> Result<StatusCode, AppError> { | ||
| 1039 | + drop_avatar(&st, user.get_id()).await | ||
| 1040 | +} | ||
| 1041 | + | ||
| 1042 | +/// Remove any user's avatar. Admin only β the moderation path: an offensive | ||
| 1043 | +/// picture is a school problem, and no route deletes the account it hangs on. | ||
| 1044 | +#[utoipa::path( | ||
| 1045 | + delete, | ||
| 1046 | + path = "/{id}/avatar", | ||
| 1047 | + tag = "users", | ||
| 1048 | + security(("session_cookie" = [])), | ||
| 1049 | + params(("id" = String, Path, description = "User id")), | ||
| 1050 | + responses( | ||
| 1051 | + (status = 204, description = "Avatar removed"), | ||
| 1052 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 1053 | + (status = 403, description = "Requires admin role", body = ErrorResponse), | ||
| 1054 | + (status = 404, description = "No such user, or no avatar to remove", body = ErrorResponse), | ||
| 1055 | + ), | ||
| 1056 | +)] | ||
| 1057 | +async fn delete_avatar( | ||
| 1058 | + State(st): State<AppState>, | ||
| 1059 | + _admin: RequireAdmin, | ||
| 1060 | + Path(id): Path<String>, | ||
| 1061 | +) -> Result<StatusCode, AppError> { | ||
| 1062 | + drop_avatar(&st, &UserId::from_key(&id)).await | ||
| 1063 | +} | ||
| 1064 | + | ||
| 1065 | +/// Clear the row's avatar and take its blob off disk β the shared tail of the | ||
| 1066 | +/// self and moderation deletes. A row without one (or no row at all) is a 404. | ||
| 1067 | +async fn drop_avatar(st: &AppState, user: &UserId) -> Result<StatusCode, AppError> { | ||
| 1068 | + let before = User::clear_avatar(user, &st.db) | ||
| 1069 | + .await? | ||
| 1070 | + .ok_or(AppError::NotFound)?; | ||
| 1071 | + let Some(file) = before.get_avatar_file() else { | ||
| 1072 | + return Err(AppError::NotFound); | ||
| 1073 | + }; | ||
| 1074 | + remove_blob(&st.files_path, file).await; | ||
| 1075 | + Ok(StatusCode::NO_CONTENT) | ||
| 1076 | +} | ||
tests/regress_profile.rsadded+697 -0
| @@ -0,0 +1,697 @@ | |||
| 1 | +//! The public-profile surface: who may read a profile, what it may never | ||
| 2 | +//! carry, the display-name fallback, the derived stats, and the avatar's | ||
| 3 | +//! blob discipline. | ||
| 4 | +//! | ||
| 5 | +//! Every gate here is a *read* gate on data that is otherwise school-wide, so | ||
| 6 | +//! each test is written to fail if its guard is deleted: the parent tests | ||
| 7 | +//! assert the 403 *and* the 200 that proves the read would otherwise work, and | ||
| 8 | +//! the blob test counts what is actually on disk rather than trusting the API's | ||
| 9 | +//! own answer. | ||
| 10 | + | ||
| 11 | +mod common; | ||
| 12 | + | ||
| 13 | +use axum::Router; | ||
| 14 | +use axum::http::StatusCode; | ||
| 15 | +use common::{app_and_db, create_course, enroll, login, login_as, me_id, send, set_role}; | ||
| 16 | +use hezarfen_backend::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN}; | ||
| 17 | +use serde_json::{Value, json}; | ||
| 18 | + | ||
| 19 | +const BOUNDARY: &str = "multipart/form-data; boundary=hezarfen-test-boundary"; | ||
| 20 | + | ||
| 21 | +/// Upload `bytes` as the caller's avatar; returns the status and parsed body. | ||
| 22 | +async fn upload_avatar( | ||
| 23 | + app: &Router, | ||
| 24 | + cookie: &str, | ||
| 25 | + content_type: &str, | ||
| 26 | + bytes: &[u8], | ||
| 27 | +) -> (StatusCode, Value) { | ||
| 28 | + let (status, _, body) = common::send_raw( | ||
| 29 | + app, | ||
| 30 | + "POST", | ||
| 31 | + "/users/me/avatar", | ||
| 32 | + Some(cookie), | ||
| 33 | + Some(BOUNDARY), | ||
| 34 | + common::multipart_file("pic.png", content_type, bytes), | ||
| 35 | + ) | ||
| 36 | + .await; | ||
| 37 | + let body = serde_json::from_slice(&body).unwrap_or(Value::Null); | ||
| 38 | + (status, body) | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +/// How many blobs in the test files dir hold exactly `bytes`. The dir is shared | ||
| 42 | +/// by every app in this binary, so a payload no other test writes is the only | ||
| 43 | +/// concurrency-safe way to count one test's own blobs. | ||
| 44 | +fn blobs_holding(bytes: &[u8]) -> usize { | ||
| 45 | + std::fs::read_dir(common::files_dir()) | ||
| 46 | + .expect("files dir") | ||
| 47 | + .filter_map(|entry| std::fs::read(entry.expect("dir entry").path()).ok()) | ||
| 48 | + .filter(|found| found == bytes) | ||
| 49 | + .count() | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +/// Tie `student_id` to `parent_id` (admin only), asserting the tie landed. | ||
| 53 | +async fn link_student(app: &Router, admin: &str, parent_id: &str, student_id: &str) { | ||
| 54 | + let res = send( | ||
| 55 | + app, | ||
| 56 | + "POST", | ||
| 57 | + &format!("/users/{parent_id}/students"), | ||
| 58 | + Some(admin), | ||
| 59 | + Some(json!({ "user_id": student_id })), | ||
| 60 | + ) | ||
| 61 | + .await; | ||
| 62 | + assert_eq!(res.status, StatusCode::OK, "link student: {}", res.body); | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +async fn profile(app: &Router, cookie: &str, id: &str) -> common::Res { | ||
| 66 | + send( | ||
| 67 | + app, | ||
| 68 | + "GET", | ||
| 69 | + &format!("/users/{id}/profile"), | ||
| 70 | + Some(cookie), | ||
| 71 | + None, | ||
| 72 | + ) | ||
| 73 | + .await | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// A profile is the *public* half of a user row: a peer reads it, and the | ||
| 77 | +/// contact fields that `GET /users/{id}` gates behind teacher+ are absent from | ||
| 78 | +/// it entirely. `badges` is pass 2 β no empty key ships early. | ||
| 79 | +#[tokio::test] | ||
| 80 | +async fn a_peer_profile_carries_no_contact_fields() { | ||
| 81 | + let (app, _db) = app_and_db().await; | ||
| 82 | + let ada = login(&app, "ada").await; | ||
| 83 | + let ada_id = me_id(&app, &ada).await; | ||
| 84 | + let peer = login(&app, "peer").await; | ||
| 85 | + | ||
| 86 | + let res = send( | ||
| 87 | + &app, | ||
| 88 | + "PATCH", | ||
| 89 | + "/users/me", | ||
| 90 | + Some(&ada), | ||
| 91 | + Some(json!({ | ||
| 92 | + "name": "Ada", | ||
| 93 | + "surname": "Lovelace", | ||
| 94 | + "email": "ada@example.com", | ||
| 95 | + "phone": "+90 555 123 45 67", | ||
| 96 | + "birth_date": "1990-01-02", | ||
| 97 | + })), | ||
| 98 | + ) | ||
| 99 | + .await; | ||
| 100 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 101 | + | ||
| 102 | + let seen = profile(&app, &peer, &ada_id).await; | ||
| 103 | + assert_eq!(seen.status, StatusCode::OK, "{}", seen.body); | ||
| 104 | + assert_eq!(seen.body["username"], "ada"); | ||
| 105 | + for private in ["email", "phone", "birth_date", "badges"] { | ||
| 106 | + assert!( | ||
| 107 | + seen.body.get(private).is_none(), | ||
| 108 | + "{private} must not ride on a profile: {}", | ||
| 109 | + seen.body | ||
| 110 | + ); | ||
| 111 | + } | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +/// A parent is an observer of their own children and of nobody else: the | ||
| 115 | +/// unlinked student is a 403, the linked one a 200, and their own row a 200. | ||
| 116 | +/// The 200s are the half that proves the 403 is the gate biting, not the read | ||
| 117 | +/// being broken for everyone. | ||
| 118 | +#[tokio::test] | ||
| 119 | +async fn a_parent_reads_only_their_own_and_their_linked_students() { | ||
| 120 | + let (app, db) = app_and_db().await; | ||
| 121 | + let admin = login_as(&app, &db, "boss", "admin").await; | ||
| 122 | + let parent = login_as(&app, &db, "mom", "parent").await; | ||
| 123 | + let parent_id = me_id(&app, &parent).await; | ||
| 124 | + let mine = login(&app, "kid").await; | ||
| 125 | + let mine_id = me_id(&app, &mine).await; | ||
| 126 | + let stranger = login(&app, "stranger").await; | ||
| 127 | + let stranger_id = me_id(&app, &stranger).await; | ||
| 128 | + | ||
| 129 | + link_student(&app, &admin, &parent_id, &mine_id).await; | ||
| 130 | + | ||
| 131 | + let blocked = profile(&app, &parent, &stranger_id).await; | ||
| 132 | + assert_eq!( | ||
| 133 | + blocked.status, | ||
| 134 | + StatusCode::FORBIDDEN, | ||
| 135 | + "an unlinked student: {}", | ||
| 136 | + blocked.body | ||
| 137 | + ); | ||
| 138 | + let linked = profile(&app, &parent, &mine_id).await; | ||
| 139 | + assert_eq!(linked.status, StatusCode::OK, "{}", linked.body); | ||
| 140 | + let own = profile(&app, &parent, &parent_id).await; | ||
| 141 | + assert_eq!(own.status, StatusCode::OK, "{}", own.body); | ||
| 142 | + let own_me = send(&app, "GET", "/users/me/profile", Some(&parent), None).await; | ||
| 143 | + assert_eq!(own_me.status, StatusCode::OK, "{}", own_me.body); | ||
| 144 | + | ||
| 145 | + // The avatar bytes ride the same gate as the profile they hang on. | ||
| 146 | + let (status, _, _) = common::send_raw( | ||
| 147 | + &app, | ||
| 148 | + "GET", | ||
| 149 | + &format!("/users/{stranger_id}/avatar"), | ||
| 150 | + Some(&parent), | ||
| 151 | + None, | ||
| 152 | + Vec::new(), | ||
| 153 | + ) | ||
| 154 | + .await; | ||
| 155 | + assert_eq!( | ||
| 156 | + status, | ||
| 157 | + StatusCode::FORBIDDEN, | ||
| 158 | + "avatar of an unlinked student" | ||
| 159 | + ); | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +/// The link row alone is not the grant: the target's live role is re-read per | ||
| 163 | +/// call, so a linked student promoted out of the student role stops being | ||
| 164 | +/// readable β a stale link cannot leave a colleague's profile open to a parent. | ||
| 165 | +#[tokio::test] | ||
| 166 | +async fn promoting_a_linked_student_closes_the_parent_read() { | ||
| 167 | + let (app, db) = app_and_db().await; | ||
| 168 | + let admin = login_as(&app, &db, "boss", "admin").await; | ||
| 169 | + let parent = login_as(&app, &db, "mom", "parent").await; | ||
| 170 | + let parent_id = me_id(&app, &parent).await; | ||
| 171 | + let kid = login(&app, "kid").await; | ||
| 172 | + let kid_id = me_id(&app, &kid).await; | ||
| 173 | + | ||
| 174 | + link_student(&app, &admin, &parent_id, &kid_id).await; | ||
| 175 | + let before = profile(&app, &parent, &kid_id).await; | ||
| 176 | + assert_eq!(before.status, StatusCode::OK, "{}", before.body); | ||
| 177 | + | ||
| 178 | + set_role(&db, "kid", "teacher").await; | ||
| 179 | + | ||
| 180 | + let after = profile(&app, &parent, &kid_id).await; | ||
| 181 | + assert_eq!( | ||
| 182 | + after.status, | ||
| 183 | + StatusCode::FORBIDDEN, | ||
| 184 | + "a promoted-out student must stop being readable: {}", | ||
| 185 | + after.body | ||
| 186 | + ); | ||
| 187 | +} | ||
| 188 | + | ||
| 189 | +/// `display_name` is the self-chosen label, the joined legal name is the | ||
| 190 | +/// fallback, and an account carrying neither reads `null` β never the username, | ||
| 191 | +/// never an empty string. | ||
| 192 | +#[tokio::test] | ||
| 193 | +async fn display_name_falls_back_to_the_legal_name_then_null() { | ||
| 194 | + let (app, _db) = app_and_db().await; | ||
| 195 | + let ada = login(&app, "ada").await; | ||
| 196 | + | ||
| 197 | + let res = send( | ||
| 198 | + &app, | ||
| 199 | + "PATCH", | ||
| 200 | + "/users/me", | ||
| 201 | + Some(&ada), | ||
| 202 | + Some(json!({ "name": "Ada", "surname": "Lovelace", "display_name": "Countess" })), | ||
| 203 | + ) | ||
| 204 | + .await; | ||
| 205 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 206 | + let mine = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; | ||
| 207 | + assert_eq!( | ||
| 208 | + mine.body["display_name"], "Countess", | ||
| 209 | + "the chosen name wins" | ||
| 210 | + ); | ||
| 211 | + | ||
| 212 | + let res = send( | ||
| 213 | + &app, | ||
| 214 | + "PATCH", | ||
| 215 | + "/users/me", | ||
| 216 | + Some(&ada), | ||
| 217 | + Some(json!({ "display_name": "" })), | ||
| 218 | + ) | ||
| 219 | + .await; | ||
| 220 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 221 | + let mine = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; | ||
| 222 | + assert_eq!(mine.body["display_name"], "Ada Lovelace", "the legal name"); | ||
| 223 | + | ||
| 224 | + let res = send( | ||
| 225 | + &app, | ||
| 226 | + "PATCH", | ||
| 227 | + "/users/me", | ||
| 228 | + Some(&ada), | ||
| 229 | + Some(json!({ "name": "", "surname": "" })), | ||
| 230 | + ) | ||
| 231 | + .await; | ||
| 232 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 233 | + let mine = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; | ||
| 234 | + assert!( | ||
| 235 | + mine.body["display_name"].is_null(), | ||
| 236 | + "nothing to show: {}", | ||
| 237 | + mine.body | ||
| 238 | + ); | ||
| 239 | +} | ||
| 240 | + | ||
| 241 | +/// The counters are derived, so a fresh account reads a true `0` on all four β | ||
| 242 | +/// never `null`, never an absent key a client would have to guard. | ||
| 243 | +#[tokio::test] | ||
| 244 | +async fn fresh_stats_read_zero_on_every_field() { | ||
| 245 | + let (app, _db) = app_and_db().await; | ||
| 246 | + let fresh = login(&app, "fresh").await; | ||
| 247 | + | ||
| 248 | + let mine = send(&app, "GET", "/users/me/profile", Some(&fresh), None).await; | ||
| 249 | + assert_eq!(mine.status, StatusCode::OK, "{}", mine.body); | ||
| 250 | + let stats = mine.body["stats"].as_object().expect("stats object"); | ||
| 251 | + for field in [ | ||
| 252 | + "pomodoro_sessions", | ||
| 253 | + "pomodoro_focus_ms", | ||
| 254 | + "courses", | ||
| 255 | + "classes", | ||
| 256 | + ] { | ||
| 257 | + assert_eq!( | ||
| 258 | + stats.get(field).and_then(Value::as_i64), | ||
| 259 | + Some(0), | ||
| 260 | + "stats.{field} must be a numeric 0: {:?}", | ||
| 261 | + stats.get(field) | ||
| 262 | + ); | ||
| 263 | + } | ||
| 264 | + assert_eq!(stats.len(), 4, "no fifth counter shipped: {stats:?}"); | ||
| 265 | + assert!(mine.body["avatar"].is_null()); | ||
| 266 | + assert_eq!(mine.body["classes"], json!([])); | ||
| 267 | + assert_eq!(mine.body["courses"], json!([])); | ||
| 268 | +} | ||
| 269 | + | ||
| 270 | +/// Upload, read back the exact bytes and the declared type, delete, gone. | ||
| 271 | +#[tokio::test] | ||
| 272 | +async fn an_avatar_round_trips_and_delete_makes_it_a_404() { | ||
| 273 | + let (app, db) = app_and_db().await; | ||
| 274 | + let ada = login(&app, "ada").await; | ||
| 275 | + let ada_id = me_id(&app, &ada).await; | ||
| 276 | + let teacher = login_as(&app, &db, "teach", "teacher").await; | ||
| 277 | + let bytes = b"ROUNDTRIP-\x89PNG"; | ||
| 278 | + | ||
| 279 | + let (status, _, _) = common::send_raw( | ||
| 280 | + &app, | ||
| 281 | + "DELETE", | ||
| 282 | + "/users/me/avatar", | ||
| 283 | + Some(&ada), | ||
| 284 | + None, | ||
| 285 | + Vec::new(), | ||
| 286 | + ) | ||
| 287 | + .await; | ||
| 288 | + assert_eq!(status, StatusCode::NOT_FOUND, "nothing to delete yet"); | ||
| 289 | + | ||
| 290 | + let (status, body) = upload_avatar(&app, &ada, "image/png", bytes).await; | ||
| 291 | + assert_eq!(status, StatusCode::CREATED, "{body}"); | ||
| 292 | + assert_eq!(body["content_type"], "image/png"); | ||
| 293 | + assert_eq!(body["size"], bytes.len()); | ||
| 294 | + | ||
| 295 | + let meta = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; | ||
| 296 | + assert_eq!(meta.body["avatar"]["content_type"], "image/png"); | ||
| 297 | + assert_eq!(meta.body["avatar"]["size"], bytes.len()); | ||
| 298 | + | ||
| 299 | + let (status, headers, served) = common::send_raw( | ||
| 300 | + &app, | ||
| 301 | + "GET", | ||
| 302 | + &format!("/users/{ada_id}/avatar"), | ||
| 303 | + Some(&teacher), | ||
| 304 | + None, | ||
| 305 | + Vec::new(), | ||
| 306 | + ) | ||
| 307 | + .await; | ||
| 308 | + assert_eq!(status, StatusCode::OK); | ||
| 309 | + assert_eq!(headers["content-type"], "image/png"); | ||
| 310 | + assert_eq!(served, bytes, "the exact bytes come back"); | ||
| 311 | + | ||
| 312 | + let (status, _, _) = common::send_raw( | ||
| 313 | + &app, | ||
| 314 | + "DELETE", | ||
| 315 | + "/users/me/avatar", | ||
| 316 | + Some(&ada), | ||
| 317 | + None, | ||
| 318 | + Vec::new(), | ||
| 319 | + ) | ||
| 320 | + .await; | ||
| 321 | + assert_eq!(status, StatusCode::NO_CONTENT); | ||
| 322 | + | ||
| 323 | + let (status, _, _) = common::send_raw( | ||
| 324 | + &app, | ||
| 325 | + "GET", | ||
| 326 | + &format!("/users/{ada_id}/avatar"), | ||
| 327 | + Some(&teacher), | ||
| 328 | + None, | ||
| 329 | + Vec::new(), | ||
| 330 | + ) | ||
| 331 | + .await; | ||
| 332 | + assert_eq!(status, StatusCode::NOT_FOUND, "the picture is gone"); | ||
| 333 | + let meta = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; | ||
| 334 | + assert!(meta.body["avatar"].is_null()); | ||
| 335 | + assert_eq!(blobs_holding(bytes), 0, "the blob left disk too"); | ||
| 336 | +} | ||
| 337 | + | ||
| 338 | +/// The self alias reads the caller's own picture. `/me/avatar` is a static | ||
| 339 | +/// segment, so it beats `/{id}/avatar` in the router: without an explicit `GET` | ||
| 340 | +/// the obvious route answers a bodyless `405` and a client is forced to learn | ||
| 341 | +/// its own id first. | ||
| 342 | +#[tokio::test] | ||
| 343 | +async fn the_caller_reads_their_own_avatar_without_knowing_their_id() { | ||
| 344 | + let (app, _db) = app_and_db().await; | ||
| 345 | + let ada = login(&app, "ada").await; | ||
| 346 | + let bytes = b"SELFALIAS-\x89PNG"; | ||
| 347 | + | ||
| 348 | + let (status, _, _) = common::send_raw( | ||
| 349 | + &app, | ||
| 350 | + "GET", | ||
| 351 | + "/users/me/avatar", | ||
| 352 | + Some(&ada), | ||
| 353 | + None, | ||
| 354 | + Vec::new(), | ||
| 355 | + ) | ||
| 356 | + .await; | ||
| 357 | + assert_eq!(status, StatusCode::NOT_FOUND, "no picture yet, not a 405"); | ||
| 358 | + | ||
| 359 | + let (status, body) = upload_avatar(&app, &ada, "image/png", bytes).await; | ||
| 360 | + assert_eq!(status, StatusCode::CREATED, "{body}"); | ||
| 361 | + | ||
| 362 | + let (status, headers, served) = common::send_raw( | ||
| 363 | + &app, | ||
| 364 | + "GET", | ||
| 365 | + "/users/me/avatar", | ||
| 366 | + Some(&ada), | ||
| 367 | + None, | ||
| 368 | + Vec::new(), | ||
| 369 | + ) | ||
| 370 | + .await; | ||
| 371 | + assert_eq!(status, StatusCode::OK); | ||
| 372 | + assert_eq!(headers["content-type"], "image/png"); | ||
| 373 | + assert_eq!(served, bytes, "the exact bytes, same as the id route"); | ||
| 374 | +} | ||
| 375 | + | ||
| 376 | +/// SVG is not a raster: it scripts, and an avatar renders inline to the whole | ||
| 377 | +/// school. The allowlist keeps it out. | ||
| 378 | +#[tokio::test] | ||
| 379 | +async fn an_svg_avatar_is_rejected() { | ||
| 380 | + let (app, _db) = app_and_db().await; | ||
| 381 | + let ada = login(&app, "ada").await; | ||
| 382 | + let svg = b"SVGREJECT<svg xmlns=\"http://www.w3.org/2000/svg\"><script/></svg>"; | ||
| 383 | + | ||
| 384 | + let (status, body) = upload_avatar(&app, &ada, "image/svg+xml", svg).await; | ||
| 385 | + assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); | ||
| 386 | + | ||
| 387 | + let mine = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; | ||
| 388 | + assert!(mine.body["avatar"].is_null(), "{}", mine.body); | ||
| 389 | + assert_eq!(blobs_holding(svg), 0, "nothing reached disk"); | ||
| 390 | +} | ||
| 391 | + | ||
| 392 | +/// Deleting someone else's picture is moderation, so it is admin-only; the | ||
| 393 | +/// admin's delete succeeding is what proves the 403 is the role gate and not a | ||
| 394 | +/// broken route. | ||
| 395 | +#[tokio::test] | ||
| 396 | +async fn only_an_admin_deletes_someone_elses_avatar() { | ||
| 397 | + let (app, db) = app_and_db().await; | ||
| 398 | + let admin = login_as(&app, &db, "boss", "admin").await; | ||
| 399 | + let teacher = login_as(&app, &db, "teach", "teacher").await; | ||
| 400 | + let ada = login(&app, "ada").await; | ||
| 401 | + let ada_id = me_id(&app, &ada).await; | ||
| 402 | + let bytes = b"MODERATION-\x89PNG"; | ||
| 403 | + | ||
| 404 | + let (status, body) = upload_avatar(&app, &ada, "image/png", bytes).await; | ||
| 405 | + assert_eq!(status, StatusCode::CREATED, "{body}"); | ||
| 406 | + | ||
| 407 | + for (who, label) in [(&teacher, "teacher"), (&ada, "the owner via /{id}")] { | ||
| 408 | + let (status, _, _) = common::send_raw( | ||
| 409 | + &app, | ||
| 410 | + "DELETE", | ||
| 411 | + &format!("/users/{ada_id}/avatar"), | ||
| 412 | + Some(who), | ||
| 413 | + None, | ||
| 414 | + Vec::new(), | ||
| 415 | + ) | ||
| 416 | + .await; | ||
| 417 | + assert_eq!(status, StatusCode::FORBIDDEN, "{label} is not an admin"); | ||
| 418 | + } | ||
| 419 | + | ||
| 420 | + let (status, _, _) = common::send_raw( | ||
| 421 | + &app, | ||
| 422 | + "DELETE", | ||
| 423 | + &format!("/users/{ada_id}/avatar"), | ||
| 424 | + Some(&admin), | ||
| 425 | + None, | ||
| 426 | + Vec::new(), | ||
| 427 | + ) | ||
| 428 | + .await; | ||
| 429 | + assert_eq!(status, StatusCode::NO_CONTENT); | ||
| 430 | + let mine = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; | ||
| 431 | + assert!(mine.body["avatar"].is_null(), "{}", mine.body); | ||
| 432 | + assert_eq!(blobs_holding(bytes), 0); | ||
| 433 | +} | ||
| 434 | + | ||
| 435 | +/// Replacing an avatar takes the old blob off disk. No route deletes a user, so | ||
| 436 | +/// a blob stranded here is stranded forever β this counts what is actually on | ||
| 437 | +/// disk, not what the API claims. | ||
| 438 | +#[tokio::test] | ||
| 439 | +async fn replacing_an_avatar_leaves_exactly_one_blob() { | ||
| 440 | + let (app, _db) = app_and_db().await; | ||
| 441 | + let ada = login(&app, "ada").await; | ||
| 442 | + let first = b"HYGIENE-FIRST-BLOB"; | ||
| 443 | + let second = b"HYGIENE-SECOND-BLOB"; | ||
| 444 | + | ||
| 445 | + let (status, body) = upload_avatar(&app, &ada, "image/png", first).await; | ||
| 446 | + assert_eq!(status, StatusCode::CREATED, "{body}"); | ||
| 447 | + assert_eq!(blobs_holding(first), 1, "the first picture is on disk"); | ||
| 448 | + | ||
| 449 | + let (status, body) = upload_avatar(&app, &ada, "image/jpeg", second).await; | ||
| 450 | + assert_eq!(status, StatusCode::CREATED, "{body}"); | ||
| 451 | + assert_eq!( | ||
| 452 | + blobs_holding(first), | ||
| 453 | + 0, | ||
| 454 | + "the replaced picture must leave disk β nothing ever collects it" | ||
| 455 | + ); | ||
| 456 | + assert_eq!(blobs_holding(second), 1, "and exactly one replaces it"); | ||
| 457 | + | ||
| 458 | + let mine = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; | ||
| 459 | + assert_eq!(mine.body["avatar"]["content_type"], "image/jpeg"); | ||
| 460 | + assert_eq!(mine.body["avatar"]["size"], second.len()); | ||
| 461 | +} | ||
| 462 | + | ||
| 463 | +/// The course block follows the owner's **live** role, not the `creator` / | ||
| 464 | +/// `teachers` columns: those are historical and no demotion sweeps them, so a | ||
| 465 | +/// demoted ex-teacher lists what they are enrolled in, like any other student. | ||
| 466 | +#[tokio::test] | ||
| 467 | +async fn a_demoted_teacher_lists_enrolled_courses_not_created_ones() { | ||
| 468 | + let (app, db) = app_and_db().await; | ||
| 469 | + let admin = login_as(&app, &db, "boss", "admin").await; | ||
| 470 | + let ex = login_as(&app, &db, "exteach", "teacher").await; | ||
| 471 | + let staff = login_as(&app, &db, "coach", "teacher").await; | ||
| 472 | + let ex_id = me_id(&app, &ex).await; | ||
| 473 | + | ||
| 474 | + create_course(&app, &ex, "Owned").await; | ||
| 475 | + let joined = create_course(&app, &staff, "Joined").await; | ||
| 476 | + | ||
| 477 | + let as_teacher = send(&app, "GET", "/users/me/profile", Some(&ex), None).await; | ||
| 478 | + assert_eq!(as_teacher.body["courses"][0]["title"], "Owned"); | ||
| 479 | + assert_eq!(as_teacher.body["stats"]["courses"], 1); | ||
| 480 | + | ||
| 481 | + set_role(&db, "exteach", "student").await; | ||
| 482 | + enroll(&app, &staff, &joined, &ex_id).await; | ||
| 483 | + | ||
| 484 | + let after = profile(&app, &admin, &ex_id).await; | ||
| 485 | + assert_eq!(after.status, StatusCode::OK, "{}", after.body); | ||
| 486 | + let titles: Vec<&str> = after.body["courses"] | ||
| 487 | + .as_array() | ||
| 488 | + .expect("courses array") | ||
| 489 | + .iter() | ||
| 490 | + .map(|course| course["title"].as_str().expect("title")) | ||
| 491 | + .collect(); | ||
| 492 | + assert_eq!(titles, ["Joined"], "the course they created is not theirs"); | ||
| 493 | + assert_eq!(after.body["stats"]["courses"], 1); | ||
| 494 | + assert_eq!(after.body["role"], "student"); | ||
| 495 | +} | ||
| 496 | + | ||
| 497 | +/// `""` clears either public field; both are length-bounded, and the bound is | ||
| 498 | +/// the one `GET /limits` publishes. | ||
| 499 | +#[tokio::test] | ||
| 500 | +async fn display_name_and_bio_clear_on_blank_and_are_bounded() { | ||
| 501 | + let (app, _db) = app_and_db().await; | ||
| 502 | + let ada = login(&app, "ada").await; | ||
| 503 | + | ||
| 504 | + let res = send( | ||
| 505 | + &app, | ||
| 506 | + "PATCH", | ||
| 507 | + "/users/me", | ||
| 508 | + Some(&ada), | ||
| 509 | + Some(json!({ "display_name": "Countess", "bio": "hi" })), | ||
| 510 | + ) | ||
| 511 | + .await; | ||
| 512 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 513 | + // The same pair rides every user-shaped response, not just the profile. | ||
| 514 | + assert_eq!(res.body["display_name"], "Countess"); | ||
| 515 | + assert_eq!(res.body["bio"], "hi"); | ||
| 516 | + | ||
| 517 | + let res = send( | ||
| 518 | + &app, | ||
| 519 | + "PATCH", | ||
| 520 | + "/users/me", | ||
| 521 | + Some(&ada), | ||
| 522 | + Some(json!({ "display_name": "", "bio": "" })), | ||
| 523 | + ) | ||
| 524 | + .await; | ||
| 525 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 526 | + let mine = send(&app, "GET", "/users/me/profile", Some(&ada), None).await; | ||
| 527 | + assert!(mine.body["display_name"].is_null(), "{}", mine.body); | ||
| 528 | + assert!(mine.body["bio"].is_null(), "{}", mine.body); | ||
| 529 | + | ||
| 530 | + let over = send( | ||
| 531 | + &app, | ||
| 532 | + "PATCH", | ||
| 533 | + "/users/me", | ||
| 534 | + Some(&ada), | ||
| 535 | + Some(json!({ "display_name": "x".repeat(MAX_DISPLAY_NAME_LEN + 1) })), | ||
| 536 | + ) | ||
| 537 | + .await; | ||
| 538 | + assert_eq!(over.status, StatusCode::BAD_REQUEST, "{}", over.body); | ||
| 539 | + | ||
| 540 | + let over = send( | ||
| 541 | + &app, | ||
| 542 | + "PATCH", | ||
| 543 | + "/users/me", | ||
| 544 | + Some(&ada), | ||
| 545 | + Some(json!({ "bio": "x".repeat(MAX_BIO_LEN + 1) })), | ||
| 546 | + ) | ||
| 547 | + .await; | ||
| 548 | + assert_eq!(over.status, StatusCode::BAD_REQUEST, "{}", over.body); | ||
| 549 | + | ||
| 550 | + // The bound holds exactly at the limit, so the reject above is the bound | ||
| 551 | + // and not an off-by-one that also refuses a legal value. | ||
| 552 | + let ok = send( | ||
| 553 | + &app, | ||
| 554 | + "PATCH", | ||
| 555 | + "/users/me", | ||
| 556 | + Some(&ada), | ||
| 557 | + Some(json!({ "display_name": "x".repeat(MAX_DISPLAY_NAME_LEN) })), | ||
| 558 | + ) | ||
| 559 | + .await; | ||
| 560 | + assert_eq!(ok.status, StatusCode::OK, "{}", ok.body); | ||
| 561 | +} | ||
| 562 | + | ||
| 563 | +/// A teacher who runs two courses, a student enrolled in one of them, a | ||
| 564 | +/// student enrolled in neither, and a manager β the cast every course-block | ||
| 565 | +/// test needs. | ||
| 566 | +struct School { | ||
| 567 | + app: Router, | ||
| 568 | + teacher: String, | ||
| 569 | + teacher_id: String, | ||
| 570 | + peer: String, | ||
| 571 | + stranger: String, | ||
| 572 | + manager: String, | ||
| 573 | + secret: String, | ||
| 574 | +} | ||
| 575 | + | ||
| 576 | +async fn school() -> School { | ||
| 577 | + let (app, db) = app_and_db().await; | ||
| 578 | + let manager = login_as(&app, &db, "boss", "manager").await; | ||
| 579 | + let teacher = login_as(&app, &db, "teach", "teacher").await; | ||
| 580 | + let teacher_id = me_id(&app, &teacher).await; | ||
| 581 | + let peer = login(&app, "peer").await; | ||
| 582 | + let peer_id = me_id(&app, &peer).await; | ||
| 583 | + let stranger = login(&app, "nosy").await; | ||
| 584 | + | ||
| 585 | + let secret = create_course(&app, &teacher, "Secret Club").await; | ||
| 586 | + let shared = create_course(&app, &teacher, "Shared Math").await; | ||
| 587 | + enroll(&app, &teacher, &shared, &peer_id).await; | ||
| 588 | + | ||
| 589 | + School { | ||
| 590 | + app, | ||
| 591 | + teacher, | ||
| 592 | + teacher_id, | ||
| 593 | + peer, | ||
| 594 | + stranger, | ||
| 595 | + manager, | ||
| 596 | + secret, | ||
| 597 | + } | ||
| 598 | +} | ||
| 599 | + | ||
| 600 | +/// The titles a profile's course block hands `cookie`. | ||
| 601 | +async fn course_titles(app: &Router, cookie: &str, id: &str) -> Vec<String> { | ||
| 602 | + let res = profile(app, cookie, id).await; | ||
| 603 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 604 | + res.body["courses"] | ||
| 605 | + .as_array() | ||
| 606 | + .expect("courses array") | ||
| 607 | + .iter() | ||
| 608 | + .map(|course| course["title"].as_str().expect("title").to_string()) | ||
| 609 | + .collect() | ||
| 610 | +} | ||
| 611 | + | ||
| 612 | +/// The leak this filter closes: a course a reader is 403'd from at | ||
| 613 | +/// `GET /courses/{id}` used to arrive, title and all, off any teacher's | ||
| 614 | +/// profile. The 403 is asserted in the same test so the two answers cannot | ||
| 615 | +/// drift apart unnoticed. | ||
| 616 | +#[tokio::test] | ||
| 617 | +async fn a_profile_never_names_a_course_the_reader_is_403d_from() { | ||
| 618 | + let s = school().await; | ||
| 619 | + | ||
| 620 | + let direct = send( | ||
| 621 | + &s.app, | ||
| 622 | + "GET", | ||
| 623 | + &format!("/courses/{}", s.secret), | ||
| 624 | + Some(&s.stranger), | ||
| 625 | + None, | ||
| 626 | + ) | ||
| 627 | + .await; | ||
| 628 | + assert_eq!(direct.status, StatusCode::FORBIDDEN, "{}", direct.body); | ||
| 629 | + | ||
| 630 | + let seen = profile(&s.app, &s.stranger, &s.teacher_id).await; | ||
| 631 | + assert_eq!(seen.status, StatusCode::OK, "{}", seen.body); | ||
| 632 | + assert_eq!(seen.body["courses"], json!([])); | ||
| 633 | + assert!( | ||
| 634 | + !seen.body.to_string().contains("Secret Club"), | ||
| 635 | + "the profile leaked a course title the reader cannot read: {}", | ||
| 636 | + seen.body | ||
| 637 | + ); | ||
| 638 | +} | ||
| 639 | + | ||
| 640 | +/// The intersection is per course, not all-or-nothing: sharing one course | ||
| 641 | +/// reveals that one and nothing else. | ||
| 642 | +#[tokio::test] | ||
| 643 | +async fn a_peer_sees_only_the_course_they_share() { | ||
| 644 | + let s = school().await; | ||
| 645 | + assert_eq!( | ||
| 646 | + course_titles(&s.app, &s.peer, &s.teacher_id).await, | ||
| 647 | + ["Shared Math"] | ||
| 648 | + ); | ||
| 649 | +} | ||
| 650 | + | ||
| 651 | +/// Manager+ reads any course directly, so the filter has nothing to withhold. | ||
| 652 | +#[tokio::test] | ||
| 653 | +async fn a_manager_reads_the_course_block_unfiltered() { | ||
| 654 | + let s = school().await; | ||
| 655 | + let mut titles = course_titles(&s.app, &s.manager, &s.teacher_id).await; | ||
| 656 | + titles.sort(); | ||
| 657 | + assert_eq!(titles, ["Secret Club", "Shared Math"]); | ||
| 658 | +} | ||
| 659 | + | ||
| 660 | +/// Your own profile is never cut β both routes onto it. | ||
| 661 | +#[tokio::test] | ||
| 662 | +async fn your_own_profile_shows_your_whole_course_list() { | ||
| 663 | + let s = school().await; | ||
| 664 | + let mut titles = course_titles(&s.app, &s.teacher, &s.teacher_id).await; | ||
| 665 | + titles.sort(); | ||
| 666 | + assert_eq!(titles, ["Secret Club", "Shared Math"]); | ||
| 667 | + | ||
| 668 | + let mine = send(&s.app, "GET", "/users/me/profile", Some(&s.teacher), None).await; | ||
| 669 | + assert_eq!(mine.body["courses"].as_array().expect("courses").len(), 2); | ||
| 670 | +} | ||
| 671 | + | ||
| 672 | +/// `stats.courses` is the owner's true total, deliberately *not* the length of | ||
| 673 | +/// the filtered block: it is the motivational counter, and a per-reader number | ||
| 674 | +/// would be meaningless. A magnitude names no course. | ||
| 675 | +#[tokio::test] | ||
| 676 | +async fn stats_courses_stays_the_owners_true_total() { | ||
| 677 | + let s = school().await; | ||
| 678 | + | ||
| 679 | + let stranger = profile(&s.app, &s.stranger, &s.teacher_id).await; | ||
| 680 | + assert_eq!(stranger.body["courses"], json!([])); | ||
| 681 | + assert_eq!(stranger.body["stats"]["courses"], 2); | ||
| 682 | + | ||
| 683 | + let peer = profile(&s.app, &s.peer, &s.teacher_id).await; | ||
| 684 | + assert_eq!(peer.body["courses"].as_array().expect("courses").len(), 1); | ||
| 685 | + assert_eq!(peer.body["stats"]["courses"], 2); | ||
| 686 | +} | ||
| 687 | + | ||
| 688 | +/// A profile that was never there is a 404, at any role β the id is not an | ||
| 689 | +/// existence oracle wearing a 403. | ||
| 690 | +#[tokio::test] | ||
| 691 | +async fn an_unknown_user_profile_is_a_404() { | ||
| 692 | + let (app, db) = app_and_db().await; | ||
| 693 | + let teacher = login_as(&app, &db, "teach", "teacher").await; | ||
| 694 | + | ||
| 695 | + let gone = profile(&app, &teacher, "01J8XZ0K3Q8G7X2M4N5P6R7S8T").await; | ||
| 696 | + assert_eq!(gone.status, StatusCode::NOT_FOUND, "{}", gone.body); | ||
| 697 | +} | ||
tests/spec_bounds.rsmodified+8 -1
| @@ -86,6 +86,13 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { | |||
| 86 | ("UpdateProfile", "name", "maxLength", MAX_NAME_LEN as i64), | 86 | ("UpdateProfile", "name", "maxLength", MAX_NAME_LEN as i64), |
| 87 | ("UpdateProfile", "surname", "maxLength", MAX_NAME_LEN as i64), | 87 | ("UpdateProfile", "surname", "maxLength", MAX_NAME_LEN as i64), |
| 88 | ("UpdateProfile", "email", "maxLength", MAX_EMAIL_LEN as i64), | 88 | ("UpdateProfile", "email", "maxLength", MAX_EMAIL_LEN as i64), |
| 89 | + ( | ||
| 90 | + "UpdateProfile", | ||
| 91 | + "display_name", | ||
| 92 | + "maxLength", | ||
| 93 | + MAX_DISPLAY_NAME_LEN as i64, | ||
| 94 | + ), | ||
| 95 | + ("UpdateProfile", "bio", "maxLength", MAX_BIO_LEN as i64), | ||
| 89 | ( | 96 | ( |
| 90 | "CreateNote", | 97 | "CreateNote", |
| 91 | "title", | 98 | "title", |
| @@ -1070,7 +1077,7 @@ async fn the_image_meta_bodies_stay_the_same_shape() { | |||
| 1070 | }; | 1077 | }; |
| 1071 | 1078 | ||
| 1072 | let want = shape("ImageMetaResponse"); | 1079 | let want = shape("ImageMetaResponse"); |
| 1073 | - for other in ["BankImageMeta", "PoolImageMeta"] { | 1080 | + for other in ["BankImageMeta", "PoolImageMeta", "ProfileAvatar"] { |
| 1074 | assert_eq!( | 1081 | assert_eq!( |
| 1075 | want, | 1082 | want, |
| 1076 | shape(other), | 1083 | shape(other), |