An admin mints a school account directly
Browse files at this commit57de5b3f22c046fe800bf8836513038e29559f2bParent: d40e4c9- feat
- an admin mints a school account directly
5 changed files +257 -12
- README.md +10 -4
- src/lib.rs +1 -1
- src/web/users.rs +91 -7
- tests/integration.rs +131 -0
- tests/spec_bounds.rs +24 -0
README.mdmodified+10 -4
| @@ -704,7 +704,7 @@ drift from it**, which is enforced rather than asked for: | ||
| 704 | 704 | and fails unless each one is either referenced by `src/web/limits.rs` or |
| 705 | 705 | listed as a deliberate exclusion *with a reason*. A new constant breaks the |
| 706 | 706 | suite until someone decides, consciously, whether clients need it. |
| 707 | -- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 200 published | |
| 707 | +- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 204 published | |
| 708 | 708 | bounds back out of the emitted JSON, and asserts each equals its constant. |
| 709 | 709 | This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal |
| 710 | 710 | only** — a `const` there does not compile — so the annotations are |
| @@ -854,8 +854,10 @@ parent < student < teacher < manager < admin | ||
| 854 | 854 | |
| 855 | 855 | The check is **hierarchical** — a higher role satisfies any lower requirement |
| 856 | 856 | (an admin can do anything a teacher can). New accounts always register as |
| 857 | -`student`; a role read is re-checked on every request, so a role change takes | |
| 858 | -effect on the user's very next call (no re-login). | |
| 857 | +`student`; an admin may also mint one outright at `POST /users`, optionally | |
| 858 | +born with the role it is named (`student` by default, so a new teacher never | |
| 859 | +passes through a student state). A role read is re-checked on every request, so | |
| 860 | +a role change takes effect on the user's very next call (no re-login). | |
| 859 | 861 | |
| 860 | 862 | `parent` is the read-only observer at the bottom of the ladder: an admin ties |
| 861 | 863 | any number of students to a parent account (`POST /users/{id}/students`), and |
| @@ -974,7 +976,7 @@ still left exactly as they stand. | ||
| 974 | 976 | | List **own** linked students | parent | Read-only: the list plus each student's mark/attendance/pomodoro/homework reports — a parent changes nothing, anywhere | |
| 975 | 977 | | Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar | |
| 976 | 978 | | 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 | |
| 977 | -| List users; look up one user; change a user's role; edit **any** user's personal info or UI preferences; tie/untie students to a `parent` account | admin | An admin cannot change **their own** role, and nobody can demote the school's **last** admin (`409`) | | |
| 979 | +| Create a user; list users; look up one user; change a user's role; edit **any** user's personal info or UI preferences; tie/untie students to a `parent` account | admin | An admin cannot change **their own** role, and nobody can demote the school's **last** admin (`409`) | | |
| 978 | 980 | |
| 979 | 981 | ### Bootstrapping the first admin |
| 980 | 982 | |
| @@ -997,6 +999,9 @@ startup. `compose.yaml` ships with the credentials above for local dev. See | ||
| 997 | 999 | "Multi-school (SaaS)" for the rest of the lifecycle. |
| 998 | 1000 | |
| 999 | 1001 | That admin can then promote everyone else through `PATCH /users/{id}/role`. |
| 1002 | +The same admin can also mint accounts directly with `POST /users` | |
| 1003 | +(`{username, password}`, optionally `role` — `student` by default), which is | |
| 1004 | +how staff are added without the register-then-promote two-step. | |
| 1000 | 1005 | |
| 1001 | 1006 | The admin set cannot be emptied through the API: an admin never changes their |
| 1002 | 1007 | own role, and a `PATCH /users/{id}/role` that would demote the last admin |
| @@ -1394,6 +1399,7 @@ window filtering, before paging; negative values are a `400` naming the field. | ||
| 1394 | 1399 | | POST | `/terms/{id}/unarchive` | manager | Re-open an archived term. Requires manager+. Idempotent the same way as archiving: an already-open term answers `200`. | |
| 1395 | 1400 | | GET | `/time` | no | Server clock: `{now}` UTC unix-millis, for a frontend to sync against. | |
| 1396 | 1401 | | GET | `/users` | admin | List every user with their role, newest first. Admin only. Paged: pass `?limit=&offset=` to take a window (omit `limit` for the whole list); the response is a `{items, total, limit, offset}` envelope where `total` counts every user. | |
| 1402 | +| POST | `/users` | admin | Create a school account directly — the school-office path for adding a student or a staff member with no self-registration and no invite. Admin only. `{username, password}` are required and `role` is optional (omitted → `student`); the row is born with its role rather than promoted into it, so a new teacher is never briefly a student. The username is a global **person** credential exactly as at `POST /auth/register`: a name new everywhere creates the person and this school's `app_user`, while a person who already exists is attached to this school only when the password matches the stored credential — a mismatch is a `409`. A username already taken in this school is a `409`, and the reserved staff-reading names (`admin`, `root`, …) are a `400`, the same policy registration holds. | | |
| 1397 | 1403 | | PATCH | `/users/me` | student | Update the caller's own personal info: name, surname, email, phone, birth date, plus the public-profile pair `display_name` and `bio` (both readable school-wide at `GET /users/{id}/profile`, unlike the contact fields). Any authenticated role. Omitted fields stay as they are; an empty string clears a field. | |
| 1398 | 1404 | | GET | `/users/me/avatar` | student | The caller's own avatar bytes. The self alias of `GET /{id}/avatar` — the static `/me/avatar` segment wins over `/{id}/avatar` in the router, so without this a client that never learned its own id gets a bodyless `405` on the obvious route. It serves the caller's own row and nothing else, so it asks no gate: the session already proves the reach. | |
| 1399 | 1405 | | POST | `/users/me/avatar` | student | Upload (or replace) the caller's own avatar. `multipart/form-data` with the image under a `file` field; the declared content type must be `image/png`, `image/jpeg`, `image/webp`, or `image/gif` (rasters only — no SVG), the bytes at most the school's `max_file_bytes` (settings). Replacing one drops the previous picture. | |
src/lib.rsmodified+1 -1
| @@ -56,7 +56,7 @@ use crate::web::module_gate::gate; | ||
| 56 | 56 | (name = "builder", description = "The vendor surface: one deployment, many schools. A **builder** is the operator who owns the deployment — not a user of any school, and holding no role in one. It logs in at `POST /builder/login` and gets a `session` cookie prefixed `builder.` instead of a school slug; that cookie works here and is `401` everywhere else, exactly as a school cookie is `401` here. `POST /schools` creates a school's database, schema and first admin in one call; the registry row reads `provisioning` until that schema is in place, so a boot cut short mid-create is finished by the next one instead of leaving a school that answers `500`; `PATCH /schools/{slug}` renames it or flips it between `active` and `suspended` (a suspension is immediate and total for that school's users — every request including login answers `403`, live session or not); `DELETE /schools/{slug}` destroys its data and its uploaded files for good. `POST /schools/{slug}/admin-password` is the lockout fix: it re-keys a named admin of that school and revokes every session that account held. `POST /schools/{slug}/enter` mints an ordinary school session for one of its admins (support access) — the only route here refused on a suspended school, so a suspension really does close every door into it. It is also where a school's **entitlements** are sold: `GET /schools/{slug}/modules` lists what it has and what is left, `POST`/`DELETE /schools/{slug}/modules/{module}` flips one (idempotently), and `PATCH /schools/{slug}/modules` re-sells the whole shelf in one atomic write — modules and packages, both directions, expanded into a single resulting set that is checked once, so a `409` names every broken dependency at once and nothing is written unless the request is accepted whole. A change lands on the school's very next request, live cookies included: a disabled module answers `403 {error, module}` on every route in its nest. The catalog itself (`GET /modules/catalog`) and a school user's own set (`GET /modules`) are on the `meta` tag."), |
| 57 | 57 | (name = "auth", description = "Registration, login, session lifecycle, and school selection. The account is a **person**: one global username + password in the control plane, able to hold memberships in many schools — the school is picked after login, never named by it. `POST /auth/register` is still aimed at a school (`{school, username, password}`): it creates the person plus the school's `app_user` (a `student`), or attaches an existing person to one more school when the password matches. It answers `201` with the byte-identical `{username, role}` body in every outcome — created, name already taken, or taken under a different password — and deliberately **no `id`**, since a distinguishable reply would let anyone unauthenticated enumerate accounts (an anti-enumeration measure; log in to learn who you are). `POST /auth/login` takes `{username, password}`: with exactly one active membership it enters that school directly — a `UserResponse` and a `session` cookie valued `<slug>.<token>` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.<token>` cookie, which `POST /auth/school` (`{school}`) exchanges for the chosen school's cookie and a `UserResponse` — the school must be one of the caller's memberships (`401` otherwise) and not suspended (`403`). Suspended schools never appear in the choice list, and a person whose every membership is suspended is `403` like the school's own doors. Login failures — unknown username, wrong password, no membership left to enter — are all the same `401`, and the unknown-username branch burns the same argon2 work a wrong-password check costs, so timing confirms nothing. `POST /auth/logout` revokes whichever session the cookie names — school, person, or builder — and stays idempotent `204` without one"), |
| 58 | 58 | (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 what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. 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"), |
| 59 | - (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 (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. 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`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; 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` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; 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), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. 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. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `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`"), | |
| 59 | + (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 (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. 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`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; 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` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; 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), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. 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. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `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`"), | |
| 60 | 60 | (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`). Every authenticated role keeps notes, `parent` included: a note is private own-scoped data with no other reader, and the routes carry **no role bar at all** — ownership is the whole authorization, so nobody but the owner ever reaches a note or its files (a stranger's id is a `404`, never a `403`). That is deliberate and it is the fix for a real defect: while these routes required `student`, a demotion to `parent` locked the owner out of their own notes for good, and since nothing else in the crate reads a note and no route cascades one, the rows and their on-disk blobs became unreachable and undeletable by everybody. Own-scoped personal data is not confiscated by a role change"), |
| 61 | 61 | (name = "messages", description = "One-to-one mail-style messages, upward only below staff: a student or parent writes to a teacher, manager or admin (parents included — messaging is the one place a parent writes) and never to another student or parent (`403`), while staff write to anyone, 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"), |
| 62 | 62 | (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 — and the bookable list is bounded on that same `starts_at`, so it never offers one — 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 demotion below `teacher` withdraws that account's whole calendar in the role change's own transaction and cancels the live bookings on it (nothing else could reach them afterwards — the requester keeps a `cancelled` row naming who dropped it and why); a slot an older build stranded is inert instead: it drops out of the bookable list and booking one is refused. The bookable list carries each slot's teacher identity (id, username, display name) to every caller, parents included — deliberate, since a conference cannot be booked from an anonymous calendar; it is the staff directory for booking, narrowed to whoever published bookable time, and the direct people routes stay closed to a parent"), |
src/web/users.rsmodified+91 -7
| @@ -10,7 +10,8 @@ use utoipa_axum::router::OpenApiRouter; | ||
| 10 | 10 | use utoipa_axum::routes; |
| 11 | 11 | |
| 12 | 12 | use crate::constant::{ |
| 13 | - MAX_MAX_FILE_BYTES, MAX_PROFILE_CLASSES, MAX_PROFILE_COURSES, UPLOAD_BODY_OVERHEAD_BYTES, | |
| 13 | + MAX_MAX_FILE_BYTES, MAX_PROFILE_CLASSES, MAX_PROFILE_COURSES, RESERVED_USERNAMES, | |
| 14 | + UPLOAD_BODY_OVERHEAD_BYTES, | |
| 14 | 15 | }; |
| 15 | 16 | use crate::database::Database; |
| 16 | 17 | use crate::domain::badge::{self, BadgeAward}; |
| @@ -19,7 +20,7 @@ use crate::domain::class_group::ClassGroupId; | ||
| 19 | 20 | use crate::domain::preferences::{Language, PaletteColor, Theme}; |
| 20 | 21 | use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone, ProfileStats}; |
| 21 | 22 | use crate::domain::role::Role; |
| 22 | -use crate::domain::user::{User, UserId}; | |
| 23 | +use crate::domain::user::{Password, User, UserId, Username}; | |
| 23 | 24 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 24 | 25 | use crate::service::parent_link::ensure_can_observe; |
| 25 | 26 | use crate::state::AppState; |
| @@ -34,7 +35,7 @@ use super::{ | ||
| 34 | 35 | |
| 35 | 36 | pub fn routes() -> OpenApiRouter<AppState> { |
| 36 | 37 | OpenApiRouter::new() |
| 37 | - .routes(routes!(list_users)) | |
| 38 | + .routes(routes!(list_users, create_user)) | |
| 38 | 39 | .routes(routes!(update_my_profile)) |
| 39 | 40 | .routes(routes!(update_my_preferences)) |
| 40 | 41 | .routes(routes!(my_students)) |
| @@ -279,6 +280,92 @@ async fn list_users( | ||
| 279 | 280 | Ok(Json(Page::new(items, total, limit, offset))) |
| 280 | 281 | } |
| 281 | 282 | |
| 283 | +#[derive(Deserialize, ToSchema)] | |
| 284 | +struct CreateUser { | |
| 285 | + /// The new account's username — a global credential, exactly as at | |
| 286 | + /// `POST /auth/register`. | |
| 287 | + #[schema(example = "ada", min_length = 3, max_length = 32)] | |
| 288 | + username: String, | |
| 289 | + #[schema(example = "correct horse battery", min_length = 6, max_length = 128)] | |
| 290 | + password: String, | |
| 291 | + /// The role the account is born with. Omitted → `student`. | |
| 292 | + #[schema(example = "teacher")] | |
| 293 | + role: Option<String>, | |
| 294 | +} | |
| 295 | + | |
| 296 | +/// Create a school account directly — the school-office path for adding a | |
| 297 | +/// student or a staff member with no self-registration and no invite. Admin | |
| 298 | +/// only. `{username, password}` are required and `role` is optional (omitted → | |
| 299 | +/// `student`); the row is born with its role rather than promoted into it, so | |
| 300 | +/// a new teacher is never briefly a student. The username is a global | |
| 301 | +/// **person** credential exactly as at `POST /auth/register`: a name new | |
| 302 | +/// everywhere creates the person and this school's `app_user`, while a person | |
| 303 | +/// who already exists is attached to this school only when the password | |
| 304 | +/// matches the stored credential — a mismatch is a `409`. A username already | |
| 305 | +/// taken in this school is a `409`, and the reserved staff-reading names | |
| 306 | +/// (`admin`, `root`, …) are a `400`, the same policy registration holds. | |
| 307 | +#[utoipa::path( | |
| 308 | + post, | |
| 309 | + path = "/", | |
| 310 | + tag = "users", | |
| 311 | + security(("session_cookie" = [])), | |
| 312 | + request_body = CreateUser, | |
| 313 | + responses( | |
| 314 | + (status = 201, description = "Account created, holding the requested role", body = UserResponse), | |
| 315 | + (status = 400, description = "Invalid username or password (a reserved username included), or an unknown role", body = ErrorResponse), | |
| 316 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 317 | + (status = 403, description = "Requires admin role", body = ErrorResponse), | |
| 318 | + (status = 409, description = "The username is taken in this school, or that person exists under a different password", body = ErrorResponse), | |
| 319 | + (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), | |
| 320 | + ), | |
| 321 | +)] | |
| 322 | +async fn create_user( | |
| 323 | + State(st): State<AppState>, | |
| 324 | + SchoolSlug(slug): SchoolSlug, | |
| 325 | + _admin: RequireAdmin, | |
| 326 | + Json(req): Json<CreateUser>, | |
| 327 | +) -> Result<(StatusCode, Json<UserResponse>), AppError> { | |
| 328 | + let username = Username::try_new(&req.username)?; | |
| 329 | + // The same policy `POST /auth/register` enforces: these names read as | |
| 330 | + // staff and invite impersonation, so no minting route may claim them. The | |
| 331 | + // `ADMIN_USERNAME` bootstrap does not come through here. | |
| 332 | + if RESERVED_USERNAMES.contains(&username.as_str()) { | |
| 333 | + return Err(ValidationError::Invalid { | |
| 334 | + field: "username", | |
| 335 | + reason: "this username is reserved", | |
| 336 | + } | |
| 337 | + .into()); | |
| 338 | + } | |
| 339 | + let role = match req.role.as_deref() { | |
| 340 | + Some(raw) => Role::try_from_str(raw)?, | |
| 341 | + None => Role::Student, | |
| 342 | + }; | |
| 343 | + let password = Password::try_new(&req.password)?; | |
| 344 | + let password_hash = password.hash_async().await?; | |
| 345 | + | |
| 346 | + // Person half (control database): create the global account, or meet the | |
| 347 | + // one already standing — the credential login verifies, exactly as the | |
| 348 | + // register and school-create paths treat it. The stored hash is never | |
| 349 | + // rewritten here; the caller must prove they know it below. | |
| 350 | + let control = st.tenants.control(); | |
| 351 | + let person = | |
| 352 | + crate::service::person::create_or_load(control, username.clone(), password_hash).await?; | |
| 353 | + if !person.get_password_hash().verify_async(&password).await { | |
| 354 | + return Err(AppError::Conflict( | |
| 355 | + "an account with that username exists under a different password", | |
| 356 | + )); | |
| 357 | + } | |
| 358 | + | |
| 359 | + // School half, born with its role: a fresh row holds no enrollments or | |
| 360 | + // teaching assignments for a later promotion to sweep. A username already | |
| 361 | + // taken in this school refuses here, before the membership is written. | |
| 362 | + let user = | |
| 363 | + crate::service::user::create_with_role(&st.db, username, Some(*person.get_id()), role) | |
| 364 | + .await?; | |
| 365 | + crate::service::person::link_school(control, person.get_id(), &slug).await?; | |
| 366 | + Ok((StatusCode::CREATED, Json(UserResponse::new(&user)))) | |
| 367 | +} | |
| 368 | + | |
| 282 | 369 | /// Update the caller's own personal info: name, surname, email, phone, birth |
| 283 | 370 | /// date, plus the public-profile pair `display_name` and `bio` (both readable |
| 284 | 371 | /// school-wide at `GET /users/{id}/profile`, unlike the contact fields). Any |
| @@ -537,10 +624,7 @@ async fn students_page( | ||
| 537 | 624 | ) -> Result<Page<PersonRef>, AppError> { |
| 538 | 625 | let (limit, offset) = page.resolve()?; |
| 539 | 626 | let links = crate::service::parent_link::list_for_parent(db, parent).await?; |
| 540 | - let ids: Vec<UserId> = links | |
| 541 | - .iter() | |
| 542 | - .map(|link| *link.get_student()) | |
| 543 | - .collect(); | |
| 627 | + let ids: Vec<UserId> = links.iter().map(|link| *link.get_student()).collect(); | |
| 544 | 628 | let mut students = crate::service::user::list_by_ids(db, &ids).await?; |
| 545 | 629 | // The link row alone is not the grant, exactly as [`ensure_can_observe`] |
| 546 | 630 | // says: a link whose student side changed role (a sweep lost a race with |
tests/integration.rsmodified+131 -0
| @@ -5218,6 +5218,137 @@ async fn admin_manages_roles_with_guards() { | ||
| 5218 | 5218 | ); |
| 5219 | 5219 | } |
| 5220 | 5220 | |
| 5221 | +/// `POST /users` is the school-office path: an admin mints a school account | |
| 5222 | +/// outright, born with the role named (default `student`), with the username | |
| 5223 | +/// a global person credential exactly as at `POST /auth/register`. A username | |
| 5224 | +/// taken in this school, or an existing person under a different password, is | |
| 5225 | +/// a `409`; the reserved staff-reading names are a `400`. | |
| 5226 | +#[tokio::test] | |
| 5227 | +async fn admin_creates_a_user() { | |
| 5228 | + let (app, db) = app_and_db().await; | |
| 5229 | + let admin = login_as(&app, &db, "boss", "admin").await; | |
| 5230 | + | |
| 5231 | + // A student may not mint accounts. | |
| 5232 | + let student = login(&app, "kid").await; | |
| 5233 | + assert_eq!( | |
| 5234 | + send( | |
| 5235 | + &app, | |
| 5236 | + "POST", | |
| 5237 | + "/users", | |
| 5238 | + Some(&student), | |
| 5239 | + Some(json!({"username": "nope", "password": "secret1"})) | |
| 5240 | + ) | |
| 5241 | + .await | |
| 5242 | + .status, | |
| 5243 | + StatusCode::FORBIDDEN | |
| 5244 | + ); | |
| 5245 | + | |
| 5246 | + // The admin mints a teacher directly — the row is born with the role. | |
| 5247 | + let res = send( | |
| 5248 | + &app, | |
| 5249 | + "POST", | |
| 5250 | + "/users", | |
| 5251 | + Some(&admin), | |
| 5252 | + Some(json!({"username": "ayse", "password": "secret1", "role": "teacher"})), | |
| 5253 | + ) | |
| 5254 | + .await; | |
| 5255 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 5256 | + assert_eq!(res.body["username"], "ayse"); | |
| 5257 | + assert_eq!(res.body["role"], "teacher"); | |
| 5258 | + assert!( | |
| 5259 | + res.body["name"].is_null(), | |
| 5260 | + "a fresh account holds no profile" | |
| 5261 | + ); | |
| 5262 | + let ayse_id = id_of(&res.body); | |
| 5263 | + | |
| 5264 | + // The account is real: it logs in with the password the admin chose, and | |
| 5265 | + // that session carries the role. | |
| 5266 | + let login = send( | |
| 5267 | + &app, | |
| 5268 | + "POST", | |
| 5269 | + "/auth/login", | |
| 5270 | + None, | |
| 5271 | + Some(json!({"username": "ayse", "password": "secret1"})), | |
| 5272 | + ) | |
| 5273 | + .await; | |
| 5274 | + assert_eq!(login.status, StatusCode::OK, "{}", login.body); | |
| 5275 | + assert_eq!(login.body["role"], "teacher"); | |
| 5276 | + assert_eq!(login.body["id"], ayse_id); | |
| 5277 | + let ayse = login.cookie.expect("session cookie set on login"); | |
| 5278 | + let me = send(&app, "GET", "/auth/me", Some(&ayse), None).await; | |
| 5279 | + assert_eq!(me.status, StatusCode::OK, "{}", me.body); | |
| 5280 | + assert_eq!(me.body["role"], "teacher"); | |
| 5281 | + | |
| 5282 | + // Omitted role -> student. | |
| 5283 | + let res = send( | |
| 5284 | + &app, | |
| 5285 | + "POST", | |
| 5286 | + "/users", | |
| 5287 | + Some(&admin), | |
| 5288 | + Some(json!({"username": "veli", "password": "secret1"})), | |
| 5289 | + ) | |
| 5290 | + .await; | |
| 5291 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 5292 | + assert_eq!(res.body["role"], "student"); | |
| 5293 | + | |
| 5294 | + // A username already taken in this school is a 409. | |
| 5295 | + assert_eq!( | |
| 5296 | + send( | |
| 5297 | + &app, | |
| 5298 | + "POST", | |
| 5299 | + "/users", | |
| 5300 | + Some(&admin), | |
| 5301 | + Some(json!({"username": "ayse", "password": "secret1"})) | |
| 5302 | + ) | |
| 5303 | + .await | |
| 5304 | + .status, | |
| 5305 | + StatusCode::CONFLICT | |
| 5306 | + ); | |
| 5307 | + // The same name under a different password is a 409 too — the person | |
| 5308 | + // already stands under a credential this caller has not proven. | |
| 5309 | + assert_eq!( | |
| 5310 | + send( | |
| 5311 | + &app, | |
| 5312 | + "POST", | |
| 5313 | + "/users", | |
| 5314 | + Some(&admin), | |
| 5315 | + Some(json!({"username": "ayse", "password": "different1"})) | |
| 5316 | + ) | |
| 5317 | + .await | |
| 5318 | + .status, | |
| 5319 | + StatusCode::CONFLICT | |
| 5320 | + ); | |
| 5321 | + | |
| 5322 | + // Refused before anything is written: a reserved name, an unknown role, | |
| 5323 | + // and a password under the floor. | |
| 5324 | + for body in [ | |
| 5325 | + json!({"username": "root", "password": "secret1"}), | |
| 5326 | + json!({"username": "zey", "password": "secret1", "role": "wizard"}), | |
| 5327 | + json!({"username": "zey", "password": "x"}), | |
| 5328 | + ] { | |
| 5329 | + let res = send(&app, "POST", "/users", Some(&admin), Some(body.clone())).await; | |
| 5330 | + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{body}: {}", res.body); | |
| 5331 | + } | |
| 5332 | + | |
| 5333 | + // The created student is really in the roster: the new teacher finds them. | |
| 5334 | + let found = send( | |
| 5335 | + &app, | |
| 5336 | + "GET", | |
| 5337 | + "/users/search?q=veli&role=student", | |
| 5338 | + Some(&ayse), | |
| 5339 | + None, | |
| 5340 | + ) | |
| 5341 | + .await; | |
| 5342 | + assert_eq!(found.status, StatusCode::OK, "{}", found.body); | |
| 5343 | + assert!( | |
| 5344 | + common::items(&found.body) | |
| 5345 | + .iter() | |
| 5346 | + .any(|item| item["username"] == "veli"), | |
| 5347 | + "the minted student is searchable: {}", | |
| 5348 | + found.body | |
| 5349 | + ); | |
| 5350 | +} | |
| 5351 | + | |
| 5221 | 5352 | /// The AI service principal must never be mintable, storable, or filterable |
| 5222 | 5353 | /// over HTTP: it is the QUIC bridge's own identity, not an account anybody can |
| 5223 | 5354 | /// hold. `Role` carries no `serde` derive (`src/domain/role.rs:21`), so no |
tests/spec_bounds.rsmodified+24 -0
| @@ -219,6 +219,30 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { | ||
| 219 | 219 | "maxLength", |
| 220 | 220 | MAX_PASSWORD_LEN as i64, |
| 221 | 221 | ), |
| 222 | + ( | |
| 223 | + "CreateUser", | |
| 224 | + "username", | |
| 225 | + "minLength", | |
| 226 | + MIN_USERNAME_LEN as i64, | |
| 227 | + ), | |
| 228 | + ( | |
| 229 | + "CreateUser", | |
| 230 | + "username", | |
| 231 | + "maxLength", | |
| 232 | + MAX_USERNAME_LEN as i64, | |
| 233 | + ), | |
| 234 | + ( | |
| 235 | + "CreateUser", | |
| 236 | + "password", | |
| 237 | + "minLength", | |
| 238 | + MIN_PASSWORD_LEN as i64, | |
| 239 | + ), | |
| 240 | + ( | |
| 241 | + "CreateUser", | |
| 242 | + "password", | |
| 243 | + "maxLength", | |
| 244 | + MAX_PASSWORD_LEN as i64, | |
| 245 | + ), | |
| 222 | 246 | ("SelectSchool", "school", "minLength", MIN_SLUG_LEN as i64), |
| 223 | 247 | ("SelectSchool", "school", "maxLength", MAX_SLUG_LEN as i64), |
| 224 | 248 | ("UpdateProfile", "name", "maxLength", MAX_NAME_LEN as i64), |