diff --git a/.sqlx/query-eb5fb3b8d7b2b7e6f199b036ae94637a4485b71ab52385a3016c9bdad24bd712.json b/.sqlx/query-0887ff018a2ecdc9bf29472dd59b5e7f76610c2a39de92e7b30ad8be5a5966f8.json similarity index 71% rename from .sqlx/query-eb5fb3b8d7b2b7e6f199b036ae94637a4485b71ab52385a3016c9bdad24bd712.json rename to .sqlx/query-0887ff018a2ecdc9bf29472dd59b5e7f76610c2a39de92e7b30ad8be5a5966f8.json index 5b6725a..6b95b71 100644 --- a/.sqlx/query-eb5fb3b8d7b2b7e6f199b036ae94637a4485b71ab52385a3016c9bdad24bd712.json +++ b/.sqlx/query-0887ff018a2ecdc9bf29472dd59b5e7f76610c2a39de92e7b30ad8be5a5966f8.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE app_user SET role = $2\n WHERE id = $1\n AND NOT (role = 'admin'\n AND $2 <> 'admin'\n AND (SELECT count(*) FROM app_user\n WHERE role = 'admin' AND id <> $1) = 0)\n RETURNING id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size", + "query": "UPDATE app_user\n SET role = $2,\n student_number = CASE WHEN $2 = 'student' THEN student_number ELSE NULL END\n WHERE id = $1\n AND NOT (role = 'admin'\n AND $2 <> 'admin'\n AND (SELECT count(*) FROM app_user\n WHERE role = 'admin' AND id <> $1) = 0)\n RETURNING id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n student_number AS \"student_number: StudentNumber\",\n avatar_size", "describe": { "columns": [ { @@ -192,6 +192,17 @@ }, { "ordinal": 17, + "name": "student_number: StudentNumber", + "type_info": "Text", + "origin": { + "Table": { + "table": "app_user", + "name": "student_number" + } + } + }, + { + "ordinal": 18, "name": "avatar_size", "type_info": "Int8", "origin": { @@ -226,8 +237,9 @@ true, true, true, + true, true ] }, - "hash": "eb5fb3b8d7b2b7e6f199b036ae94637a4485b71ab52385a3016c9bdad24bd712" + "hash": "0887ff018a2ecdc9bf29472dd59b5e7f76610c2a39de92e7b30ad8be5a5966f8" } diff --git a/.sqlx/query-ea2f28046b3ef41ed15703197135e3be14d9568d9795278a8afbc14dd52e448f.json b/.sqlx/query-09f4fca0c1cf695324fd71baec63fd30baa3cfff04429798e9e8784ffb611ede.json similarity index 91% rename from .sqlx/query-ea2f28046b3ef41ed15703197135e3be14d9568d9795278a8afbc14dd52e448f.json rename to .sqlx/query-09f4fca0c1cf695324fd71baec63fd30baa3cfff04429798e9e8784ffb611ede.json index e18e8bb..a2b3b07 100644 --- a/.sqlx/query-ea2f28046b3ef41ed15703197135e3be14d9568d9795278a8afbc14dd52e448f.json +++ b/.sqlx/query-09f4fca0c1cf695324fd71baec63fd30baa3cfff04429798e9e8784ffb611ede.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size\n FROM app_user WHERE id = ANY($1)", + "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n student_number AS \"student_number: StudentNumber\",\n avatar_size\n FROM app_user WHERE id = ANY($1)", "describe": { "columns": [ { @@ -192,6 +192,17 @@ }, { "ordinal": 17, + "name": "student_number: StudentNumber", + "type_info": "Text", + "origin": { + "Table": { + "table": "app_user", + "name": "student_number" + } + } + }, + { + "ordinal": 18, "name": "avatar_size", "type_info": "Int8", "origin": { @@ -225,8 +236,9 @@ true, true, true, + true, true ] }, - "hash": "ea2f28046b3ef41ed15703197135e3be14d9568d9795278a8afbc14dd52e448f" + "hash": "09f4fca0c1cf695324fd71baec63fd30baa3cfff04429798e9e8784ffb611ede" } diff --git a/.sqlx/query-85c6837e943dbff5b411062672966a15f9eaa9da3501ac6ab774842587b3158f.json b/.sqlx/query-7496e13f38da77b1fc311a687f1996651f4d8ce46c0ee401f63d2a5f80334ab2.json similarity index 90% rename from .sqlx/query-85c6837e943dbff5b411062672966a15f9eaa9da3501ac6ab774842587b3158f.json rename to .sqlx/query-7496e13f38da77b1fc311a687f1996651f4d8ce46c0ee401f63d2a5f80334ab2.json index fc7463a..68ce1fc 100644 --- a/.sqlx/query-85c6837e943dbff5b411062672966a15f9eaa9da3501ac6ab774842587b3158f.json +++ b/.sqlx/query-7496e13f38da77b1fc311a687f1996651f4d8ce46c0ee401f63d2a5f80334ab2.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size\n FROM app_user WHERE id = $1 FOR UPDATE", + "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n student_number AS \"student_number: StudentNumber\",\n avatar_size\n FROM app_user WHERE id = $1 FOR UPDATE", "describe": { "columns": [ { @@ -192,6 +192,17 @@ }, { "ordinal": 17, + "name": "student_number: StudentNumber", + "type_info": "Text", + "origin": { + "Table": { + "table": "app_user", + "name": "student_number" + } + } + }, + { + "ordinal": 18, "name": "avatar_size", "type_info": "Int8", "origin": { @@ -225,8 +236,9 @@ true, true, true, + true, true ] }, - "hash": "85c6837e943dbff5b411062672966a15f9eaa9da3501ac6ab774842587b3158f" + "hash": "7496e13f38da77b1fc311a687f1996651f4d8ce46c0ee401f63d2a5f80334ab2" } diff --git a/.sqlx/query-8fb4f8d22b9aca20a9cfa7de35bd4bac5ce3a0bfdbd4059a08b0b27d25b62537.json b/.sqlx/query-ac0befbd1b4398d79d2bbe2d8923bde69dfbe93bbb60dadc632ce93bbe18f8a6.json similarity index 91% rename from .sqlx/query-8fb4f8d22b9aca20a9cfa7de35bd4bac5ce3a0bfdbd4059a08b0b27d25b62537.json rename to .sqlx/query-ac0befbd1b4398d79d2bbe2d8923bde69dfbe93bbb60dadc632ce93bbe18f8a6.json index 7ce8f53..1375e38 100644 --- a/.sqlx/query-8fb4f8d22b9aca20a9cfa7de35bd4bac5ce3a0bfdbd4059a08b0b27d25b62537.json +++ b/.sqlx/query-ac0befbd1b4398d79d2bbe2d8923bde69dfbe93bbb60dadc632ce93bbe18f8a6.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size\n FROM app_user WHERE id = $1", + "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n student_number AS \"student_number: StudentNumber\",\n avatar_size\n FROM app_user WHERE id = $1", "describe": { "columns": [ { @@ -192,6 +192,17 @@ }, { "ordinal": 17, + "name": "student_number: StudentNumber", + "type_info": "Text", + "origin": { + "Table": { + "table": "app_user", + "name": "student_number" + } + } + }, + { + "ordinal": 18, "name": "avatar_size", "type_info": "Int8", "origin": { @@ -225,8 +236,9 @@ true, true, true, + true, true ] }, - "hash": "8fb4f8d22b9aca20a9cfa7de35bd4bac5ce3a0bfdbd4059a08b0b27d25b62537" + "hash": "ac0befbd1b4398d79d2bbe2d8923bde69dfbe93bbb60dadc632ce93bbe18f8a6" } diff --git a/.sqlx/query-46be1d9c474028739e57a52bbf0ea26a101bbed607e14890aa6349fd767ec701.json b/.sqlx/query-c8eeec6b17943f913ed919e8663e44fc9d0e85ac9eaa6a7f2c9b012237381d5c.json similarity index 90% rename from .sqlx/query-46be1d9c474028739e57a52bbf0ea26a101bbed607e14890aa6349fd767ec701.json rename to .sqlx/query-c8eeec6b17943f913ed919e8663e44fc9d0e85ac9eaa6a7f2c9b012237381d5c.json index 31547a4..1a664c4 100644 --- a/.sqlx/query-46be1d9c474028739e57a52bbf0ea26a101bbed607e14890aa6349fd767ec701.json +++ b/.sqlx/query-c8eeec6b17943f913ed919e8663e44fc9d0e85ac9eaa6a7f2c9b012237381d5c.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size\n FROM app_user WHERE username = $1", + "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n student_number AS \"student_number: StudentNumber\",\n avatar_size\n FROM app_user WHERE role = $1 ORDER BY id DESC", "describe": { "columns": [ { @@ -192,6 +192,17 @@ }, { "ordinal": 17, + "name": "student_number: StudentNumber", + "type_info": "Text", + "origin": { + "Table": { + "table": "app_user", + "name": "student_number" + } + } + }, + { + "ordinal": 18, "name": "avatar_size", "type_info": "Int8", "origin": { @@ -225,8 +236,9 @@ true, true, true, + true, true ] }, - "hash": "46be1d9c474028739e57a52bbf0ea26a101bbed607e14890aa6349fd767ec701" + "hash": "c8eeec6b17943f913ed919e8663e44fc9d0e85ac9eaa6a7f2c9b012237381d5c" } diff --git a/.sqlx/query-22d8652b21f633600d075ca3aff634ad2ae34dfbc87907a1f41229365726763f.json b/.sqlx/query-e30a05b019f2834851c819abde37d928f6a02f051e99bc877168f48d142bff8b.json similarity index 75% rename from .sqlx/query-22d8652b21f633600d075ca3aff634ad2ae34dfbc87907a1f41229365726763f.json rename to .sqlx/query-e30a05b019f2834851c819abde37d928f6a02f051e99bc877168f48d142bff8b.json index e9bc201..b240ffc 100644 --- a/.sqlx/query-22d8652b21f633600d075ca3aff634ad2ae34dfbc87907a1f41229365726763f.json +++ b/.sqlx/query-e30a05b019f2834851c819abde37d928f6a02f051e99bc877168f48d142bff8b.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "INSERT INTO app_user (id, username, person, role, created_at)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size", + "query": "INSERT INTO app_user (id, username, person, role, student_number, created_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n student_number AS \"student_number: StudentNumber\",\n avatar_size", "describe": { "columns": [ { @@ -192,6 +192,17 @@ }, { "ordinal": 17, + "name": "student_number: StudentNumber", + "type_info": "Text", + "origin": { + "Table": { + "table": "app_user", + "name": "student_number" + } + } + }, + { + "ordinal": 18, "name": "avatar_size", "type_info": "Int8", "origin": { @@ -208,6 +219,7 @@ "Text", "Uuid", "Text", + "Text", "Int8" ] }, @@ -229,8 +241,9 @@ true, true, true, + true, true ] }, - "hash": "22d8652b21f633600d075ca3aff634ad2ae34dfbc87907a1f41229365726763f" + "hash": "e30a05b019f2834851c819abde37d928f6a02f051e99bc877168f48d142bff8b" } diff --git a/.sqlx/query-1a258b398d6023dbb6e42c7e3f3df270d77dc6d69959d376df8be1c170e74e88.json b/.sqlx/query-fb4bc5f405406b6b5f6a41705b65ceb78cd496905d3da3669ab659e57b0ed7fc.json similarity index 91% rename from .sqlx/query-1a258b398d6023dbb6e42c7e3f3df270d77dc6d69959d376df8be1c170e74e88.json rename to .sqlx/query-fb4bc5f405406b6b5f6a41705b65ceb78cd496905d3da3669ab659e57b0ed7fc.json index 8d877a2..e7a830f 100644 --- a/.sqlx/query-1a258b398d6023dbb6e42c7e3f3df270d77dc6d69959d376df8be1c170e74e88.json +++ b/.sqlx/query-fb4bc5f405406b6b5f6a41705b65ceb78cd496905d3da3669ab659e57b0ed7fc.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n avatar_size\n FROM app_user WHERE role = $1 ORDER BY id DESC", + "query": "SELECT id AS \"id: UserId\",\n username AS \"username: Username\",\n person AS \"person: PersonId\",\n role AS \"role: Role\",\n name AS \"name: PersonName\",\n surname AS \"surname: PersonName\",\n email AS \"email: Email\",\n phone AS \"phone: Phone\",\n birth_date AS \"birth_date: BirthDate\",\n theme AS \"theme: Theme\",\n language AS \"language: Language\",\n palette_color AS \"palette_color: PaletteColor\",\n display_name AS \"display_name: DisplayName\",\n bio AS \"bio: Bio\",\n avatar_file,\n avatar_content_type AS \"avatar_content_type: FileContentType\",\n branch,\n student_number AS \"student_number: StudentNumber\",\n avatar_size\n FROM app_user WHERE username = $1", "describe": { "columns": [ { @@ -192,6 +192,17 @@ }, { "ordinal": 17, + "name": "student_number: StudentNumber", + "type_info": "Text", + "origin": { + "Table": { + "table": "app_user", + "name": "student_number" + } + } + }, + { + "ordinal": 18, "name": "avatar_size", "type_info": "Int8", "origin": { @@ -225,8 +236,9 @@ true, true, true, + true, true ] }, - "hash": "1a258b398d6023dbb6e42c7e3f3df270d77dc6d69959d376df8be1c170e74e88" + "hash": "fb4bc5f405406b6b5f6a41705b65ceb78cd496905d3da3669ab659e57b0ed7fc" } diff --git a/README.md b/README.md index 75f4e8e..9ed44d1 100644 --- a/README.md +++ b/README.md @@ -720,7 +720,7 @@ drift from it**, which is enforced rather than asked for: and fails unless each one is either referenced by `src/web/limits.rs` or listed as a deliberate exclusion *with a reason*. A new constant breaks the suite until someone decides, consciously, whether clients need it. -- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 222 published +- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 224 published bounds back out of the emitted JSON, and asserts each equals its constant. This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal only** — a `const` there does not compile — so the annotations are @@ -1478,22 +1478,22 @@ window filtering, before paging; negative values are a `400` naming the field. | POST | `/terms/{id}/unarchive` | manager | Re-open an archived term. Requires manager+. Idempotent the same way as archiving: an already-open term answers `200`. | | GET | `/time` | no | Server clock: `{now}` UTC unix-millis, for a frontend to sync against. | | 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. | -| 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. | -| 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. | +| 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. `student_number` numbers a new student at mint time — a `409` when another student in this school already holds it, a `400` on a non-student role. 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. | +| 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. `student_number` follows the same merge semantics, with two refusals of its own: naming one while the account is not a `student` is a `400`, and a number another student in this school already holds is a `409` (`code: student_number_taken`). | | 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. | | 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. | | DELETE | `/users/me/avatar` | student | Remove the caller's own avatar. | | PATCH | `/users/me/preferences` | student | Update the caller's own UI preferences: `theme` (`light`/`dark`), `language` (`tr`/`en`), and `palette_color` (accent color as `#rrggbb`). Any authenticated role. Omitted fields stay as they are; an empty string clears one back to "never chose" (the client then follows the device preference). Read them back on any user response, e.g. `GET /auth/me`. | | GET | `/users/me/profile` | student | The caller's own public profile — what everyone else sees of them. | | GET | `/users/me/students` | parent | The students the calling parent observes, sorted by username. Requires the `parent` role. Each entry's reports live at `GET /marks/{user}`, `GET /attendance/{user}`, and `GET /pomodoro/{user}`. Paged via `?limit=&offset=`. | -| GET | `/users/search` | student | Find users by username or name — backs the pickers (enroll, grade, mark attendance) and, for a student or parent, the one way to find the staff member they are allowed to message. Any authenticated user may ask; a caller below teacher only ever sees the roles they may message (teacher, manager, admin), in the items *and* in `total`. A blank or omitted `q` lists everyone the caller may see — what the pickers open with; `role` narrows to one role (e.g. `role=student` for an enroll picker), and a student or parent naming a role they may not message is refused. Paged via `?limit=&offset=` like the other lists (omit `limit` for every match); returns a `{items, total, limit, offset}` envelope carrying only id/username/display name — no contact details. | +| GET | `/users/search` | student | Find users by username or name — backs the pickers (enroll, grade, mark attendance) and, for a student or parent, the one way to find the staff member they are allowed to message. Any authenticated user may ask; a caller below teacher only ever sees the roles they may message (teacher, manager, admin), in the items *and* in `total`. A blank or omitted `q` lists everyone the caller may see — what the pickers open with; `role` narrows to one role (e.g. `role=student` for an enroll picker), and a student or parent naming a role they may not message is refused. Paged via `?limit=&offset=` like the other lists (omit `limit` for every match); returns a `{items, total, limit, offset}` envelope carrying only id/username/display name and the student number — no contact details. | | GET | `/users/{id}` | admin | Fetch one user with their role and personal info. Admin only. | | GET | `/users/{id}/avatar` | student | The avatar bytes. Same reach as the profile itself: every authenticated account, except a parent, who is limited to their own and their linked students'. | | DELETE | `/users/{id}/avatar` | admin | Remove any user's avatar. Admin only — the moderation path: an offensive picture is a school problem, and no route deletes the account it hangs on. | | PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences. Admin only — everyone else manages their own through `PATCH /users/me/preferences`, which this mirrors field for field. | | GET | `/users/{id}/profile` | student | One user's public profile: display name, bio, avatar meta, their class and course blocks, the badges they have earned, and the motivational counters. Badges carry an id and the instant they were first earned; their labels and icons come from the `badges` catalog at `GET /limits`. Readable by every authenticated account — except a parent, who reads only their own and their linked students'. Never carries email, phone, or birth date; those stay on `GET /users/{id}` (admin) and `GET /auth/me`. The embedded blocks are capped at `max_profile_classes` / `max_profile_courses` (see `GET /limits`) — the full paged lists are `GET /classes/me` and `GET /courses/me`. The course block is also cut to what the *reader* may already see: only courses they would pass `GET /courses/{id}` on. The class block holds the same bar as `GET /classes/user/{id}` — teacher+, a parent linked to this student, or the owner themselves; every other reader gets an empty `classes` array rather than a 403. Every number in `stats` stays the owner's true total either way, including the ones whose underlying reports are gated (`/pomodoro/{id}`, `/marks/user/{id}`, `/attendance/user/{id}`): they are motivational counters, and a magnitude names no course, class, lesson or exam. | -| PATCH | `/users/{id}/profile` | admin | Update any user's personal info. Admin only — the school-office path for maintaining records on behalf of students and staff. Same field semantics as `PATCH /users/me`. | -| PATCH | `/users/{id}/role` | admin | Set a user's role. Admin only. An admin cannot change their own role, and the school's **last** admin cannot be demoted by anyone (`409`) — together those keep role management from locking everyone out, including when two admins demote each other at the same instant (the floor is a predicate on the role write itself, so the racing demotions serialize on row locks). A school that has already lost its admins is recovered by hand against the database, since the seed never promotes. Setting any non-`student` role also drops the user's course enrollments — only students enroll, so a promoted user leaves every roster. Demoting below `teacher` drops their course teaching assignments for the mirror reason, and withdraws their published appointment slots, cancelling the live bookings on them: nothing could reach either afterwards — a slot is listed only on its own teacher's calendar and deleted only by a teacher+, and a booking on one is decided only by a teacher+ and cancelled only by its requester, who is refused once the window opens. The requester keeps the booking as `cancelled`, naming the ex-teacher and the reason. Demoting to `parent` additionally gives back the seats they hold on still-open event signup lists: a parent can no longer free them, and nobody else may. Seats on lists that have already closed stay as they are — that roster is history. It also takes the account off every whiteboard roster and **closes every board it created** — permanently read-only, nothing deleted. A demoted creator is a `404` on their own board, the four commands that could end it are the creator's alone, and no route lists a board the caller is not on, so the room would otherwise be commandable by nobody while its participants kept drawing on it. Closed, they keep reading the board, its history and its epochs; only writes are refused. | +| PATCH | `/users/{id}/profile` | admin | Update any user's personal info. Admin only — the school-office path for maintaining records on behalf of students and staff. Same field semantics as `PATCH /users/me`, `student_number` included: the number belongs to the student identity the office maintains, so this is the door that issues it — a `400` when the target is not a `student`, a `409` (`code: student_number_taken`) when another student in this school already holds it. A role change away from `student` clears it on its own (`PATCH /users/{id}/role`), which is also the answer to "this account is no longer a student". | +| PATCH | `/users/{id}/role` | admin | Set a user's role. Admin only. An admin cannot change their own role, and the school's **last** admin cannot be demoted by anyone (`409`) — together those keep role management from locking everyone out, including when two admins demote each other at the same instant (the floor is a predicate on the role write itself, so the racing demotions serialize on row locks). A school that has already lost its admins is recovered by hand against the database, since the seed never promotes. Setting any non-`student` role also drops the user's course enrollments — only students enroll, so a promoted user leaves every roster — and clears the account's student number in the same transaction: the number names a student of this school, so no window exists where a promoted account still holds one. Demoting below `teacher` drops their course teaching assignments for the mirror reason, and withdraws their published appointment slots, cancelling the live bookings on them: nothing could reach either afterwards — a slot is listed only on its own teacher's calendar and deleted only by a teacher+, and a booking on one is decided only by a teacher+ and cancelled only by its requester, who is refused once the window opens. The requester keeps the booking as `cancelled`, naming the ex-teacher and the reason. Demoting to `parent` additionally gives back the seats they hold on still-open event signup lists: a parent can no longer free them, and nobody else may. Seats on lists that have already closed stay as they are — that roster is history. It also takes the account off every whiteboard roster and **closes every board it created** — permanently read-only, nothing deleted. A demoted creator is a `404` on their own board, the four commands that could end it are the creator's alone, and no route lists a board the caller is not on, so the room would otherwise be commandable by nobody while its participants kept drawing on it. Closed, they keep reading the board, its history and its epochs; only writes are refused. | | GET | `/users/{id}/students` | admin | List the students tied to a parent account, sorted by username. Admin only — parents read their own list at `GET /users/me/students`. Paged via `?limit=&offset=` like the other lists. | | POST | `/users/{id}/students` | admin | Tie a student to a parent account. Admin only — family ties are school-office records, like roles. `{id}` must hold the `parent` role and `user_id` the `student` role; a parent may observe any number of students. Idempotent: linking the same pair again keeps the one tie (the `linked_by` stamp moves to the latest linker, like re-enrolling). The tie grants the parent read access to the student's marks, attendance, and pomodoro reports — nothing else, and never any write. | | DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent account. Admin only. The student's data is untouched — only the parent's read grant goes away. | diff --git a/migrations/school/20260920000001_student_number.sql b/migrations/school/20260920000001_student_number.sql new file mode 100644 index 0000000..0530ef5 --- /dev/null +++ b/migrations/school/20260920000001_student_number.sql @@ -0,0 +1,39 @@ +-- The student number: the school's own identifier for a student ("1234", +-- "9-B/17"), carried on the account row. +-- +-- WHERE THIS FILE BELONGS: `migrations/school/` in the backend repo. APPEND-ONLY +-- relative to the existing school migrations: it touches no other table. +-- +-- WHY ON `app_user`: the number belongs to the *account in this school*, not to +-- the global person — two schools may issue the same number to two different +-- students, and a person's membership in one school must not constrain another. +-- `NULL` on every account that holds none, which is every staff account and +-- every student registered before the school got round to issuing numbers. +-- +-- UNIQUENESS IS PER SCHOOL BY CONSTRUCTION: each school already lives in its own +-- database, so a plain partial unique index is the whole rule — no school column, +-- exactly like `app_user_username` and `app_user_person`. The partial predicate +-- (`WHERE student_number IS NOT NULL`) is what keeps unlimited accounts without +-- a number legal: in Postgres, NULLs in a plain UNIQUE index would be distinct +-- anyway, but the partial index also keeps the index off the rows that carry no +-- value. +-- +-- Only a student row may hold one. That rule has three enforcement points and +-- they are not redundant: the web layer refuses the request (a 400 with the +-- live role it read), the role cascade clears the column in the same statement +-- that leaves the student role, and the CHECK below is what holds when the two +-- race — a profile write carrying a number from a snapshot read while the role +-- write commits first would otherwise land a number on a promoted row, and the +-- handler-side gate cannot see that. A `CHECK` may reference other columns of +-- its own row (unlike a `UNIQUE`), so the row's own role is exactly the +-- predicate; the column is new and NULL on every existing row, so no row can +-- be in violation at creation time. A violation answers the same 400 the +-- web gate does (`crate::db::user` maps 23514 to it), never a 500. +ALTER TABLE app_user ADD COLUMN IF NOT EXISTS student_number TEXT NULL; + +ALTER TABLE app_user + ADD CONSTRAINT app_user_student_number_student + CHECK (student_number IS NULL OR role = 'student'); + +CREATE UNIQUE INDEX IF NOT EXISTS app_user_student_number + ON app_user (student_number) WHERE student_number IS NOT NULL; diff --git a/src/constant.rs b/src/constant.rs index 5d30b04..b8cc6c1 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -12,6 +12,13 @@ pub const MAX_SCHOOL_NAME_LEN: usize = 120; pub const MIN_USERNAME_LEN: usize = 3; pub const MAX_USERNAME_LEN: usize = 32; +/// A student's school-issued number. Free text rather than digits on purpose — +/// schools prefix, slash and hyphenate them ("9-B/17") — bounded like the other +/// short labels. Only students hold one (the write paths enforce the role, and +/// the role cascade clears it), and it is unique inside the school (the partial +/// unique index is the enforcement). +pub const MAX_STUDENT_NUMBER_LEN: usize = 32; + /// Separators allowed inside a username (never at the edges, never doubled). pub const USERNAME_SEPARATORS: [char; 3] = ['.', '_', '-']; diff --git a/src/database.rs b/src/database.rs index 3ca5871..d4b4d8a 100644 --- a/src/database.rs +++ b/src/database.rs @@ -463,6 +463,20 @@ pub fn exclusion_violation(err: &sqlx::Error) -> Option<&str> { } } +/// The violated `CHECK` constraint's name, when `err` is a check violation +/// (`23514`) — a row the statement would have written in a state its own DDL +/// forbids. Named like [`unique_violation`] so a call site can tell which rule +/// refused (`student_number IS NULL OR role = 'student'`) instead of answering +/// a generic 500 for a caller's mistake. +pub fn check_violation(err: &sqlx::Error) -> Option<&str> { + let db = err.as_database_error()?; + if db.code().as_deref() == Some("23514") { + db.constraint() + } else { + None + } +} + /// A foreign-key violation (`23503`): a parent row a statement names is gone. pub fn foreign_key_violation(err: &sqlx::Error) -> bool { err.as_database_error() diff --git a/src/db/user.rs b/src/db/user.rs index 45e1c2a..a2fb14d 100644 --- a/src/db/user.rs +++ b/src/db/user.rs @@ -4,11 +4,11 @@ //! the cascade lives in [`crate::service::user`]. //! //! The compile-time macros map columns by name and check each decoded type -//! against the prepare schema, so the seventeen user columns are spelled +//! against the prepare schema, so the eighteen user columns are spelled //! out — newtype overrides included — in every static statement below. The //! repetitions are the check. -use crate::database::{Database, tx_with_retry}; +use crate::database::{Database, check_violation, tx_with_retry, unique_violation}; use crate::db::field_update::FieldUpdate; use crate::db::page::{PagedList, Param}; use crate::domain::board::{Board, BoardId, BoardTitle}; @@ -19,9 +19,21 @@ use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Pho use crate::domain::role::Role; use crate::domain::text_fold::{search_fold, search_fold_sql}; use crate::domain::timestamp::Timestamp; -use crate::domain::user::{User, UserId, Username}; +use crate::domain::user::{StudentNumber, User, UserId, Username}; use crate::error::AppError; +/// The answer a duplicate `student_number` gets, from both write paths that +/// can raise one (the mint and the profile writer). One spelling so the two +/// cannot drift, and `ConflictCoded` because the frontend branches on the +/// cause — the number is refused by the partial unique index +/// (`app_user_student_number`), not by anything the message could name. +fn number_taken() -> AppError { + AppError::ConflictCoded { + code: "student_number_taken", + message: "student number already taken".to_owned(), + } +} + /// Register a new school account for the control-plane `person` whose /// credential login verifies — `person` is the join key, `None` only where the /// caller cannot know it yet (tests, the boot seed's row-first order — see @@ -33,7 +45,7 @@ pub async fn create( username: Username, person: Option, ) -> Result { - create_with_role(db, username, person, Role::Student).await + create_with_role(db, username, person, Role::Student, None).await } /// The one row-minting path. `role` is written *with* the row rather than @@ -50,18 +62,27 @@ pub async fn create( /// of a race gets the same 409 the sequential duplicate always got. /// /// The row carries its `created_at` mint stamp and, when the caller knows it, -/// the `person` id the credential lives on. +/// the `person` id the credential lives on. `student_number` binds as handed: +/// the *role* rule ("only a student may hold one") is the web layer's gate — +/// it is the layer that resolves the requested role — while the *uniqueness* +/// rule is the partial unique index, and its violation answers the same 409 +/// the duplicate username does. pub async fn create_with_role( db: &Database, username: Username, person: Option, role: Role, + student_number: Option, ) -> Result { + debug_assert!( + student_number.is_none() || role == Role::Student, + "only a student row may be born with a student number" + ); let id = UserId::generate(); match sqlx::query_as!( User, - r#"INSERT INTO app_user (id, username, person, role, created_at) - VALUES ($1, $2, $3, $4, $5) + r#"INSERT INTO app_user (id, username, person, role, student_number, created_at) + VALUES ($1, $2, $3, $4, $5, $6) RETURNING id AS "id: UserId", username AS "username: Username", person AS "person: PersonId", @@ -79,11 +100,13 @@ pub async fn create_with_role( avatar_file, avatar_content_type AS "avatar_content_type: FileContentType", branch, + student_number AS "student_number: StudentNumber", avatar_size"#, id.uuid(), username.as_str(), person.as_ref().map(PersonId::uuid), role.as_str(), + student_number.as_ref().map(StudentNumber::as_str), Timestamp::now().as_millis(), ) .fetch_one(db) @@ -96,9 +119,17 @@ pub async fn create_with_role( ); Ok(user) } - Err(err) if crate::database::unique_violation(&err) == Some("app_user_username") => { + Err(err) if unique_violation(&err) == Some("app_user_username") => { Err(AppError::Conflict("username already taken")) } + Err(err) if unique_violation(&err) == Some("app_user_student_number") => { + Err(number_taken()) + } + // The row's own CHECK: this path already debug-asserts the rule, and + // in a release build the database is what says no. + Err(err) if check_violation(&err) == Some("app_user_student_number_student") => { + Err(StudentNumber::non_student_refusal().into()) + } Err(err) => Err(err.into()), } } @@ -123,6 +154,7 @@ pub async fn read(db: &Database, id: &UserId) -> Result, AppError> avatar_file, avatar_content_type AS "avatar_content_type: FileContentType", branch, + student_number AS "student_number: StudentNumber", avatar_size FROM app_user WHERE id = $1"#, id.uuid() @@ -168,6 +200,7 @@ pub async fn list_by_ids(db: &Database, ids: &[UserId]) -> Result, App avatar_file, avatar_content_type AS "avatar_content_type: FileContentType", branch, + student_number AS "student_number: StudentNumber", avatar_size FROM app_user WHERE id = ANY($1)"#, &ids @@ -200,6 +233,7 @@ pub async fn list_by_role(db: &Database, role: Role) -> Result, AppErr avatar_file, avatar_content_type AS "avatar_content_type: FileContentType", branch, + student_number AS "student_number: StudentNumber", avatar_size FROM app_user WHERE role = $1 ORDER BY id DESC"#, role.as_str() @@ -285,11 +319,13 @@ pub async fn search( /// the floor that guards it and the arm-by-arm reasoning. What follows is /// the store side. /// -/// Writes *only* the `role` field of the user row (never the whole row): -/// the row mixes admin-owned (role) and self-service (profile, preferences) -/// fields, and each writer starts from a snapshot read at request start. A -/// whole-row write would carry the snapshot's copy of the *other* group back -/// over a concurrent edit — an in-flight profile save silently reverting an +/// Writes *only* the `role` field of the user row — plus `student_number`, +/// cleared in that same statement whenever the new role is not `student` +/// (see the statement's own note) — never the whole row: the row mixes +/// admin-owned (role) and self-service (profile, preferences) fields, and +/// each writer starts from a snapshot read at request start. A whole-row +/// write would carry the snapshot's copy of the *other* group back over a +/// concurrent edit — an in-flight profile save silently reverting an /// admin's demotion, or this write erasing a profile edit that raced it. /// [`set_profile`] and [`set_preferences`] are scoped for the same reason. /// @@ -396,10 +432,16 @@ pub async fn set_role_cascade( // The role write, floor guard included. `$2 <> 'admin'` arms the // guard only for a demotion: a promotion or a same-role rewrite can - // never orphan the admins. + // never orphan the admins. `student_number` rides the same statement: + // the number names a student of this school, so the write that stops + // being one is the write that drops it — a re-stated `student` keeps + // it, everything else clears it, and no window exists where a + // promoted account still holds one. let updated = sqlx::query_as!( User, - r#"UPDATE app_user SET role = $2 + r#"UPDATE app_user + SET role = $2, + student_number = CASE WHEN $2 = 'student' THEN student_number ELSE NULL END WHERE id = $1 AND NOT (role = 'admin' AND $2 <> 'admin' @@ -422,6 +464,7 @@ pub async fn set_role_cascade( avatar_file, avatar_content_type AS "avatar_content_type: FileContentType", branch, + student_number AS "student_number: StudentNumber", avatar_size"#, target.uuid(), role.as_str(), @@ -657,6 +700,14 @@ pub async fn set_role_cascade( /// for an omitted field would revert a concurrent PATCH of that field — /// two profile edits (a name and a phone) used to lose each other. See /// [`set_role_cascade`] for why no writer here touches the whole row. +/// +/// `student_number` is the one column here whose write can be *violated* +/// rather than merely refused: the partial unique index is its whole +/// availability check, so a duplicate the caller did not pre-check (and +/// could not — a pre-check races) comes back as the index's 23505 and is +/// mapped to the same 409 the duplicate-username path answers. The role +/// gate ("only a student holds one") stays at the web layer, which holds +/// the row it read. // One argument per nullable column is the point: folding them into a struct // would just re-spell the HTTP DTO here and cost the compiler's check that // every column was considered at the call site. @@ -672,6 +723,7 @@ pub async fn set_profile( display_name: Option>, bio: Option>, branch: Option>, + student_number: Option>, ) -> Result { // `Some(None)` must bind an explicit NULL and `Some(Some(v))` a value: // `Param::OptText` carries both shapes of one nullable TEXT column. @@ -718,8 +770,38 @@ pub async fn set_profile( "branch", text(branch.as_ref().map(|n| n.as_ref().map(String::as_str))), ) + .set( + "student_number", + text( + student_number + .as_ref() + .map(|n| n.as_ref().map(StudentNumber::as_str)), + ), + ) .run(db) .await + .map_err(|err| match err { + // The index's own refusal, named. A `SELECT`-then-write pre-check + // would race (two students claim the same number, both read free); + // the partial unique index is the serialization point, so this is + // the only place the collision is knowable. + AppError::Db(sqlx_err) + if unique_violation(&sqlx_err) == Some("app_user_student_number") => + { + number_taken() + } + // The other half of the rule, and the one only the database can + // hold: this write carried a number from a snapshot that said + // `student`, while the role write committed first. The CHECK sees + // the row as it is *now*, and the caller gets the same 400 the + // web pre-check answers. + AppError::Db(sqlx_err) + if check_violation(&sqlx_err) == Some("app_user_student_number_student") => + { + StudentNumber::non_student_refusal().into() + } + other => other, + }) } /// Point the row at a freshly uploaded avatar blob, returning the row *as @@ -766,6 +848,7 @@ pub async fn set_avatar( avatar_file, avatar_content_type AS "avatar_content_type: FileContentType", branch, + student_number AS "student_number: StudentNumber", avatar_size FROM app_user WHERE id = $1 FOR UPDATE"#, id.uuid() @@ -815,6 +898,7 @@ pub async fn clear_avatar(db: &Database, id: &UserId) -> Result, Ap avatar_file, avatar_content_type AS "avatar_content_type: FileContentType", branch, + student_number AS "student_number: StudentNumber", avatar_size FROM app_user WHERE id = $1 FOR UPDATE"#, id.uuid() @@ -878,6 +962,7 @@ pub async fn find_by_username(db: &Database, username: &str) -> Result { + assert_eq!(field, "student_number") + } + other => panic!("the database must refuse a number on a promoted row: {other:?}"), + } + let after = read(&db, user.get_id()).await.unwrap().unwrap(); + assert_eq!(after.get_role(), Role::Teacher); + assert_eq!( + after.get_student_number(), + None, + "a promoted row holds no number" + ); + } + #[tokio::test] async fn an_avatar_upload_cannot_revert_a_role_change() { let (db, _leases) = init_test_db().await; @@ -972,6 +1122,7 @@ mod tests { Some(Some(display_name.clone())), None, None, + None, ) .await .unwrap(); diff --git a/src/domain/user.rs b/src/domain/user.rs index 438c03a..9ad1444 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -9,7 +9,7 @@ use argon2::password_hash::phc::PasswordHash as PhcHash; use argon2::{Argon2, PasswordHasher, PasswordVerifier}; use uuid::Uuid; -use crate::constant::{AI_PRINCIPAL_KEY, DECOY_PASSWORD}; +use crate::constant::{AI_PRINCIPAL_KEY, DECOY_PASSWORD, MAX_STUDENT_NUMBER_LEN}; use crate::domain::monotonic_id::next_uuid; use crate::domain::note_file::FileContentType; use crate::domain::person::PersonId; @@ -17,7 +17,7 @@ use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; use crate::domain::role::Role; use crate::error::{AppError, ValidationError}; -use crate::validate::{validate_password, validate_username}; +use crate::validate::{validate_password, validate_required, validate_username}; /// Typed user row id. A UUIDv7 minted by the process-wide monotonic /// generator, so `id` order is mint order. @@ -75,6 +75,44 @@ impl Username { } } +/// A validated student number. Construction canonicalizes the value the way +/// [`Username`] does — the stored string is trimmed, because the partial unique +/// index keys on it and `"1234 "` must collide with `"1234"`, not sit beside it +/// as a second number the school never issued. +/// +/// Shape only: non-blank and within [`MAX_STUDENT_NUMBER_LEN`]. Uniqueness is +/// the index's, and *so is the role rule* — whether the holding account is a +/// student is the write path's check (it holds the row), never this type's, +/// which never sees a role. +#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] +#[sqlx(transparent)] +pub struct StudentNumber(String); + +impl StudentNumber { + pub fn try_new(value: &str) -> Result { + let trimmed = value.trim(); + validate_required("student_number", trimmed, MAX_STUDENT_NUMBER_LEN)?; + Ok(Self(trimmed.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + /// The refusal every write path answers when a number would land on a row + /// that is not a student. Spelled once because two layers must say the + /// same thing: the web layer's pre-check (against the role it read) and + /// the database's own `CHECK` on the row (against the role at write time, + /// which is what closes the read-then-write race) both answer a 400, and a + /// client must not have to tell two sentences apart for one rule. + pub fn non_student_refusal() -> ValidationError { + ValidationError::Invalid { + field: "student_number", + reason: "only a student account may hold a student number", + } + } +} + /// Bounds how many argon2 hashes run at once. `spawn_blocking` is unbounded — /// tokio grows the blocking pool to 512 threads — and argon2's default `m_cost` /// is 19 MiB, so an un-capped login flood claims gigabytes (measured: ~17 MB @@ -212,6 +250,12 @@ pub struct User { /// on rows minted before their person was known (boot seed order, tests). pub(crate) person: Option, pub(crate) role: Role, + /// The school-issued student number, unique inside the school. `None` on + /// every account that holds none — every staff account, and every student + /// its school has not numbered yet. Only a student row may carry one: + /// the write paths refuse a non-student, and the role cascade clears it in + /// the same transaction that leaves the student role. + pub(crate) student_number: Option, // Personal info, identical for every role. All optional: accounts are // created from bare credentials and filled in later, and rows from before // these fields existed simply read back as `None`. @@ -256,6 +300,7 @@ impl User { username: Username(AI_PRINCIPAL_KEY.to_string()), person: None, role: Role::Ai, + student_number: None, name: None, surname: None, email: None, @@ -288,6 +333,14 @@ impl User { self.role } + /// The school-issued student number, as stored. Never non-`None` on a + /// non-student row — the writes that could spell that are refused at the + /// web layer, and the role cascade clears it on the way out of the student + /// role. + pub fn get_student_number(&self) -> Option<&StudentNumber> { + self.student_number.as_ref() + } + pub fn get_name(&self) -> Option<&PersonName> { self.name.as_ref() } @@ -369,6 +422,17 @@ mod tests { assert_eq!(Username::try_new(" ali ").unwrap().as_str(), "ali"); } + #[tokio::test] + async fn student_number_newtype_validates_and_trims() { + // Trimmed like the username, because the unique index keys on the + // stored string: "1234 " and "1234" must be one number, not two. + assert_eq!(StudentNumber::try_new(" 1234 ").unwrap().as_str(), "1234"); + assert!(StudentNumber::try_new("").is_err()); + assert!(StudentNumber::try_new(" ").is_err()); + assert!(StudentNumber::try_new(&"9".repeat(MAX_STUDENT_NUMBER_LEN)).is_ok()); + assert!(StudentNumber::try_new(&"9".repeat(MAX_STUDENT_NUMBER_LEN + 1)).is_err()); + } + #[tokio::test] async fn short_password_rejected() { assert!(Password::try_new("123").is_err()); diff --git a/src/service/rag_scope.rs b/src/service/rag_scope.rs index 719b784..b43a63d 100644 --- a/src/service/rag_scope.rs +++ b/src/service/rag_scope.rs @@ -199,9 +199,15 @@ mod tests { /// row (and the membership and parent-link gates judge the exact role), so /// a fabricated id or the `fixture_user` default would not do. async fn person(db: &Database, username: &str, role: Role) -> User { - crate::db::user::create_with_role(db, Username::try_new(username).unwrap(), None, role) - .await - .unwrap() + crate::db::user::create_with_role( + db, + Username::try_new(username).unwrap(), + None, + role, + None, + ) + .await + .unwrap() } /// A class section carrying a grade label — the half of every instance diff --git a/src/service/user.rs b/src/service/user.rs index 0e5e456..3f71724 100644 --- a/src/service/user.rs +++ b/src/service/user.rs @@ -11,7 +11,7 @@ use crate::domain::person::PersonId; use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; use crate::domain::role::Role; -use crate::domain::user::{Password, User, UserId, Username}; +use crate::domain::user::{Password, StudentNumber, User, UserId, Username}; use crate::error::AppError; use crate::tenant::{Slug, Tenants}; @@ -58,7 +58,8 @@ pub async fn ensure_admin( // who registered the name first, so the hole cannot be healed // later; it has to be impossible to open. None => { - user::create_with_role(&db, username, Some(*person.get_id()), Role::Admin).await?; + user::create_with_role(&db, username, Some(*person.get_id()), Role::Admin, None) + .await?; // No `username` field: with OTLP on every event is exported as a // log record, so an account name here leaves the process. tracing::info!("seeded the admin account named by ADMIN_USERNAME"); @@ -110,14 +111,16 @@ pub async fn create( } /// Mint a row holding `role` outright — the school-creation path, whose -/// first account must be an admin from birth. +/// first account must be an admin from birth — optionally numbered +/// (`student_number`; only a `student` row may carry one, the caller's check). pub async fn create_with_role( db: &Database, username: Username, person: Option, role: Role, + student_number: Option, ) -> Result { - user::create_with_role(db, username, person, role).await + user::create_with_role(db, username, person, role, student_number).await } /// One user row, for callers that only inspect it — the web layer's reads go @@ -177,6 +180,10 @@ pub async fn set_profile( // school's `Settings::get_branches()` list is the caller's check, not this // one's. branch: Option>, + // The school-issued student number, clearable like `bio`; *being a + // student* is the caller's check (it holds the row), and uniqueness is + // the partial index's, mapped to a 409 in [`crate::db::user`]. + student_number: Option>, ) -> Result { user::set_profile( db, @@ -189,6 +196,7 @@ pub async fn set_profile( display_name, bio, branch, + student_number, ) .await } diff --git a/src/web/builder.rs b/src/web/builder.rs index 65e3f3d..4a4b4c5 100644 --- a/src/web/builder.rs +++ b/src/web/builder.rs @@ -379,8 +379,14 @@ async fn create_school( let id = SchoolId::generate(); let db = st.tenants.create(id, &slug, &name, modules).await?; let seeded = async { - crate::service::user::create_with_role(&db, username, Some(*person.get_id()), Role::Admin) - .await?; + crate::service::user::create_with_role( + &db, + username, + Some(*person.get_id()), + Role::Admin, + None, + ) + .await?; // The admin's person gets the membership the school row answers for — // idempotent, so a retried create after a torn pair completes it. service::person::link_school(&st.db, person.get_id(), &slug).await?; diff --git a/src/web/dto.rs b/src/web/dto.rs index a3c8222..1178426 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -83,6 +83,12 @@ pub struct PersonRef { /// `"Name Surname"` join, else `null`. #[schema(example = "Ada Lovelace")] pub display_name: Option, + /// The school-issued student number, `null` for every account that holds + /// none (every staff account included). Part of "who this is" the way a + /// username is, which is why it rides this ref rather than a route of its + /// own — a roster that names a student can name their number. + #[schema(example = "1234")] + pub student_number: Option, } impl PersonRef { @@ -103,6 +109,9 @@ impl PersonRef { .get_display_name() .map(|chosen| chosen.as_str().to_string()) .or_else(|| (!full.is_empty()).then(|| full.join(" "))), + student_number: user + .get_student_number() + .map(|number| number.as_str().to_string()), } } @@ -124,6 +133,7 @@ impl PersonRef { id: id.key().to_string(), username: id.key().to_string(), display_name: None, + student_number: None, }) } } @@ -156,6 +166,12 @@ pub struct UserResponse { #[schema(example = "ada")] pub username: String, pub role: Role, + /// The school-issued student number, unique inside the school. `null` + /// when the account holds none — every staff account, and any student the + /// office has not numbered yet. Only ever a value on a `student` row: a + /// role change away from `student` clears it. + #[schema(example = "1234")] + pub student_number: Option, #[schema(example = "Ada")] pub name: Option, #[schema(example = "Lovelace")] @@ -194,6 +210,9 @@ impl UserResponse { id: user.get_id().key().to_string(), username: user.get_username().as_str().to_string(), role: user.get_role().into(), + student_number: user + .get_student_number() + .map(|number| number.as_str().to_string()), name: user.get_name().map(|v| v.as_str().to_string()), surname: user.get_surname().map(|v| v.as_str().to_string()), email: user.get_email().map(|v| v.as_str().to_string()), diff --git a/src/web/limits.rs b/src/web/limits.rs index eb94103..909d2f6 100644 --- a/src/web/limits.rs +++ b/src/web/limits.rs @@ -55,6 +55,9 @@ struct UserLimits { max_display_name_len: usize, /// Free text under a profile's name. max_bio_len: usize, + /// A student number's length bound (free text; unique inside the school, + /// and only ever held by a `student` account). + max_student_number_len: usize, /// How many course references a profile read embeds — a cap on the /// response, not on membership. The full list stays at `/courses/me`. max_profile_courses: usize, @@ -546,6 +549,7 @@ impl LimitsResponse { max_name_len: MAX_NAME_LEN, max_display_name_len: MAX_DISPLAY_NAME_LEN, max_bio_len: MAX_BIO_LEN, + max_student_number_len: MAX_STUDENT_NUMBER_LEN, max_profile_courses: MAX_PROFILE_COURSES, max_profile_classes: MAX_PROFILE_CLASSES, max_email_len: MAX_EMAIL_LEN, diff --git a/src/web/messages.rs b/src/web/messages.rs index 81a378b..78e568c 100644 --- a/src/web/messages.rs +++ b/src/web/messages.rs @@ -129,6 +129,7 @@ impl MessageResponse { id: id.key().to_string(), username: id.key().to_string(), display_name: None, + student_number: None, }, None, ), diff --git a/src/web/users.rs b/src/web/users.rs index 8ee3d6b..3bf8757 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -20,7 +20,7 @@ use crate::domain::class_group::ClassGroupId; use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone, ProfileStats}; use crate::domain::role::Role; -use crate::domain::user::{Password, User, UserId, Username}; +use crate::domain::user::{Password, StudentNumber, User, UserId, Username}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::service::parent_link::ensure_can_observe; use crate::state::AppState; @@ -99,6 +99,13 @@ struct UpdateProfile { /// clear it (a school that lists no subjects stores none). #[schema(example = "Matematik", max_length = 50)] branch: Option, + /// The school-issued student number of the account being patched, unique + /// inside the school. Only a `student` account may hold one — naming one + /// for any other role, or naming a number another student already holds, + /// is refused. Omit to keep the current value; send `""` (or whitespace) + /// to clear it. + #[schema(example = "1234", max_length = 32)] + student_number: Option, } /// Partial UI-preference update. Same field semantics as [`UpdateProfile`]: @@ -158,10 +165,47 @@ fn merge_branch( } } +/// Resolve the `student_number` a request names. Same merge shape as +/// [`merge_field`] — absent (or `null`) is "keep", blank is an explicit +/// clear — plus the two checks a plain field does not carry: +/// +/// * **The role gate.** A number names a student of this school, so only a +/// `student` row may receive one; naming one for any other role is a 400, +/// not a silent write the next role change would clear. +/// * **The shape**, through [`StudentNumber`]: non-blank after trimming and +/// within the published bound. Blank is a *clear* rather than a parse +/// failure, so whitespace can never become a stored number — the same +/// reading every other patchable field has. +/// +/// `""` on a non-student stays a clear (a no-op: such a row never holds one), +/// and a value that collides with another student's is the unique index's +/// refusal — a 409 from the writer, never a pre-check that could race. +fn merge_student_number( + patch: Option<&str>, + role: Role, +) -> Result>, ValidationError> { + match patch { + None => Ok(None), + Some(raw) if raw.trim().is_empty() => Ok(Some(None)), + Some(raw) => { + if role != Role::Student { + return Err(StudentNumber::non_student_refusal()); + } + Ok(Some(Some(StudentNumber::try_new(raw)?))) + } + } +} + /// Validate and persist exactly the info fields `req` carried — nothing is /// merged from `user`'s snapshot, so a concurrent PATCH of another field is not /// reverted. Shared by the self-service and admin profile endpoints — they /// differ only in whose row they load and who may call them. +/// +/// `student_number` is resolved against the target's *live* role, read with the +/// row we hold — so the role gate cannot be raced by a role change landing in +/// between (a promotion that lands first makes this a 400; this write landing +/// first leaves nothing behind, because the role write clears the number in the +/// same statement). async fn apply_profile( user: User, req: &UpdateProfile, @@ -176,6 +220,7 @@ async fn apply_profile( let birth_date = merge_field(req.birth_date.as_deref(), BirthDate::try_new)?; let display_name = merge_field(req.display_name.as_deref(), DisplayName::try_new)?; let bio = merge_field(req.bio.as_deref(), Bio::try_new)?; + let student_number = merge_student_number(req.student_number.as_deref(), user.get_role())?; // Only a request that actually names a branch pays the settings read. let branch = match req.branch { Some(_) => { @@ -195,6 +240,7 @@ async fn apply_profile( display_name, bio, branch, + student_number, ) .await?; Ok(UserResponse::new(&updated)) @@ -245,7 +291,7 @@ struct SearchUsers { /// student or parent naming a role they may not message is refused. Paged /// via `?limit=&offset=` like the other lists (omit `limit` for every /// match); returns a `{items, total, limit, offset}` envelope carrying only -/// id/username/display name — no contact details. +/// id/username/display name and the student number — no contact details. #[utoipa::path( get, path = "/search", @@ -332,13 +378,21 @@ struct CreateUser { /// The role the account is born with. Omitted → `student`. #[schema(example = "teacher")] role: Option, + /// The school-issued student number, unique inside the school. Only a + /// `student` account may hold one — naming one while creating any other + /// role is a `400`, and a number another student already holds is a `409`. + /// Omit to create the account unnumbered; blank is the same as omitted. + #[schema(example = "1234", max_length = 32)] + student_number: Option, } /// 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 +/// a new teacher is never briefly a student. `student_number` numbers a new +/// student at mint time — a `409` when another student in this school already +/// holds it, a `400` on a non-student role. 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 @@ -353,10 +407,10 @@ struct CreateUser { request_body = CreateUser, responses( (status = 201, description = "Account created, holding the requested role", body = UserResponse), - (status = 400, description = "Invalid username or password (a reserved username included), or an unknown role", body = ErrorResponse), + (status = 400, description = "Invalid username or password (a reserved username included), an unknown role, or a student number on a non-student role", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires admin role", body = ErrorResponse), - (status = 409, description = "The username is taken in this school, or that person exists under a different password", body = ErrorResponse), + (status = 409, description = "The username is taken in this school, that person exists under a different password, or the student number is already taken (`code: student_number_taken`)", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -381,6 +435,10 @@ async fn create_user( Some(raw) => Role::try_from_str(raw)?, None => Role::Student, }; + // The number is validated against the role the row is being born with + // (the same gate the profile writer applies), then bound into the mint — + // one statement, so a refused number leaves no half-created account. + let student_number = merge_student_number(req.student_number.as_deref(), role)?.flatten(); let password = Password::try_new(&req.password)?; let password_hash = password.hash_async().await?; @@ -399,10 +457,16 @@ async fn create_user( // School half, born with its role: a fresh row holds no enrollments or // teaching assignments for a later promotion to sweep. A username already - // taken in this school refuses here, before the membership is written. - let user = - crate::service::user::create_with_role(&st.db, username, Some(*person.get_id()), role) - .await?; + // taken in this school refuses here, before the membership is written, and + // so does a student number another student already holds. + let user = crate::service::user::create_with_role( + &st.db, + username, + Some(*person.get_id()), + role, + student_number, + ) + .await?; crate::service::person::link_school(control, person.get_id(), &slug).await?; Ok((StatusCode::CREATED, Json(UserResponse::new(&user)))) } @@ -411,7 +475,10 @@ async fn create_user( /// 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. +/// a field. `student_number` follows the same merge semantics, with two +/// refusals of its own: naming one while the account is not a `student` is a +/// `400`, and a number another student in this school already holds is a `409` +/// (`code: student_number_taken`). #[utoipa::path( patch, path = "/me", @@ -420,8 +487,9 @@ async fn create_user( request_body = UpdateProfile, responses( (status = 200, description = "Updated user", body = UserResponse), - (status = 400, description = "Invalid field", body = ErrorResponse), + (status = 400, description = "Invalid field, or a student number on a non-student account", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 409, description = "The student number is already taken (`code: student_number_taken`)", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -487,7 +555,13 @@ async fn get_user( /// Update any user's personal info. Admin only — the school-office path for /// maintaining records on behalf of students and staff. Same field semantics -/// as `PATCH /users/me`. +/// as `PATCH /users/me`, `student_number` included: the number belongs to the +/// student identity the office maintains, so this is the door that issues it — +/// a `400` when the target is not a `student`, a `409` +/// (`code: student_number_taken`) when another student in this school already +/// holds it. A role change away from `student` clears it on its own +/// (`PATCH /users/{id}/role`), which is also the answer to "this account is no +/// longer a student". #[utoipa::path( patch, path = "/{id}/profile", @@ -497,10 +571,11 @@ async fn get_user( request_body = UpdateProfile, responses( (status = 200, description = "Updated user", body = UserResponse), - (status = 400, description = "Invalid field", body = ErrorResponse), + (status = 400, description = "Invalid field, or a student number on a non-student account", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires admin role", body = ErrorResponse), (status = 404, description = "User not found", body = ErrorResponse), + (status = 409, description = "The student number is already taken (`code: student_number_taken`)", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -555,7 +630,10 @@ async fn update_user_preferences( /// A school that has already lost its admins is recovered by hand against the /// database, since the seed never promotes. /// Setting any non-`student` role also drops the user's course enrollments — -/// only students enroll, so a promoted user leaves every roster. Demoting below +/// only students enroll, so a promoted user leaves every roster — and clears +/// the account's student number in the same transaction: the number names a +/// student of this school, so no window exists where a promoted account still +/// holds one. Demoting below /// `teacher` drops their course teaching assignments for the mirror reason, and /// withdraws their published appointment slots, cancelling the live bookings on /// them: nothing could reach either afterwards — a slot is listed only on its @@ -827,6 +905,14 @@ async fn my_students( // and the counters that motivate. Deliberately *not* `UserResponse` — that one // carries email, phone, and birth date, which keep exactly the gate they have // today (self, teacher+, admin). Nothing here widens where they are reachable. +// +// The student number is deliberately on `UserResponse` (and `PersonRef`) and +// *not* here: it is the school office's identifier for a student, readable +// wherever the reader is already looking at student identity — the admin user +// surfaces, the pickers, a parent's own children's roster — while this profile +// is readable by every authenticated account school-wide. A number is not a +// secret, but broadcasting one to the whole school is a widening nobody asked +// for. /// A user's public profile. Contact details are not part of it, at any role. #[derive(Serialize, ToSchema)] diff --git a/tests/integration.rs b/tests/integration.rs index 9230ca8..8caff72 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -5213,6 +5213,156 @@ async fn admin_creates_a_user() { ); } +/// `student_number` on the mint: a student may be born with one (stored +/// trimmed), a duplicate in the same school is the partial unique index's +/// refusal — a 409 carrying the `student_number_taken` code — and any +/// non-student role refuses the field outright. +#[tokio::test] +async fn student_numbers_are_minted_uniquely_and_only_for_students() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "boss", "admin").await; + + // The number is stored trimmed, exactly like a username: the unique index + // keys on the stored string, so padding must not mint a second number. + let created = send( + &app, + "POST", + "/users", + Some(&admin), + Some(json!({ + "username": "numarali", + "password": "secret1", + "student_number": " 1234 ", + })), + ) + .await; + assert_eq!(created.status, StatusCode::CREATED, "{}", created.body); + assert_eq!(created.body["student_number"], "1234", "{}", created.body); + let numbered_id = id_of(&created.body); + + // Read back off the row, not off the create echo. + let one = send( + &app, + "GET", + &format!("/users/{numbered_id}"), + Some(&admin), + None, + ) + .await; + assert_eq!(one.body["student_number"], "1234"); + + // A second student claiming the same number — padded or not — is the + // index's refusal, and the body names the cause for a client that + // branches on it. + for duplicate in ["1234", "1234 "] { + let res = send( + &app, + "POST", + "/users", + Some(&admin), + Some(json!({ + "username": "kopyaci", + "password": "secret1", + "student_number": duplicate, + })), + ) + .await; + assert_eq!( + res.status, + StatusCode::CONFLICT, + "{duplicate}: {}", + res.body + ); + assert_eq!(res.body["error"], "student number already taken"); + assert_eq!(res.body["code"], "student_number_taken"); + } + // The refused mint wrote nothing: the username is still free. + let retry = send( + &app, + "POST", + "/users", + Some(&admin), + Some(json!({ "username": "kopyaci", "password": "secret1" })), + ) + .await; + assert_eq!(retry.status, StatusCode::CREATED, "{}", retry.body); + assert!( + retry.body["student_number"].is_null(), + "an omitted number is null: {}", + retry.body + ); + + // A non-student role may not be born with a number — refused before + // anything is written, so the username stays free too. + assert_eq!( + send( + &app, + "POST", + "/users", + Some(&admin), + Some(json!({ + "username": "hoca", + "password": "secret1", + "role": "teacher", + "student_number": "5678", + })), + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + assert_eq!( + send( + &app, + "POST", + "/users", + Some(&admin), + Some(json!({ "username": "hoca", "password": "secret1", "role": "teacher" })), + ) + .await + .status, + StatusCode::CREATED + ); + + // Bound: 32 characters fit, 33 do not. + assert_eq!( + send( + &app, + "POST", + "/users", + Some(&admin), + Some(json!({ + "username": "uzun", + "password": "secret1", + "student_number": "9".repeat(33), + })), + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + + // Blank is the same as omitted, never a stored empty string. + let blank = send( + &app, + "POST", + "/users", + Some(&admin), + Some(json!({ + "username": "bosluk", + "password": "secret1", + "student_number": " ", + })), + ) + .await; + assert_eq!(blank.status, StatusCode::CREATED, "{}", blank.body); + assert!( + blank.body["student_number"].is_null(), + "whitespace is absent, not a number: {}", + blank.body + ); +} + /// The AI service principal must never be mintable, storable, or filterable /// over HTTP: it is the QUIC bridge's own identity, not an account anybody can /// hold. `Role` carries no `serde` derive (`src/domain/role.rs:21`), so no @@ -5538,6 +5688,257 @@ async fn admin_reads_and_edits_any_profile_with_guards() { ); } +/// `student_number` through the profile doors: the office numbers a student, +/// the number rides every surface that shows student identity, a duplicate is +/// a coded 409, blank clears (on any role — a clear is not a set), only a +/// student may hold one, and a role change away from `student` clears it. +#[tokio::test] +async fn student_number_patches_follow_the_student_role() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "boss", "admin").await; + let alice = login(&app, "alice").await; + let alice_id = me_id(&app, &alice).await; + let bob = login(&app, "bob").await; + let bob_id = me_id(&app, &bob).await; + + // The office numbers alice. + let res = send( + &app, + "PATCH", + &format!("/users/{alice_id}/profile"), + Some(&admin), + Some(json!({ "student_number": " 9-B/17 " })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["student_number"], "9-B/17", "stored trimmed"); + + // Every reader that shows student identity carries it: the admin's single + // read, the admin listing, the picker ref, and alice's own session. + let one = send( + &app, + "GET", + &format!("/users/{alice_id}"), + Some(&admin), + None, + ) + .await; + assert_eq!(one.body["student_number"], "9-B/17"); + let list = send(&app, "GET", "/users", Some(&admin), None).await; + let listed = common::items(&list.body) + .iter() + .find(|u| u["username"] == "alice") + .expect("alice listed") + .clone(); + assert_eq!(listed["student_number"], "9-B/17"); + let search = send( + &app, + "GET", + "/users/search?q=alice&role=student", + Some(&admin), + None, + ) + .await; + let found = common::items(&search.body) + .iter() + .find(|u| u["username"] == "alice") + .expect("alice found") + .clone(); + assert_eq!(found["student_number"], "9-B/17"); + let me = send(&app, "GET", "/auth/me", Some(&alice), None).await; + assert_eq!(me.body["student_number"], "9-B/17"); + + // A student owns the number on their own row: the self door takes it too, + // under the same rules. An unrelated patch leaves it standing. + let res = send( + &app, + "PATCH", + "/users/me", + Some(&alice), + Some(json!({ "student_number": "9-B/18" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["student_number"], "9-B/18"); + let res = send( + &app, + "PATCH", + "/users/me", + Some(&alice), + Some(json!({ "name": "Alice" })), + ) + .await; + assert_eq!(res.body["student_number"], "9-B/18", "omitted = untouched"); + + // Bound: 33 characters are refused through this door too. + assert_eq!( + send( + &app, + "PATCH", + "/users/me", + Some(&alice), + Some(json!({ "student_number": "9".repeat(33) })), + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + + // bob takes one of his own; alice claiming it is the index's refusal, and + // the refused patch left her number exactly as it stood. + assert_eq!( + send( + &app, + "PATCH", + &format!("/users/{bob_id}/profile"), + Some(&admin), + Some(json!({ "student_number": "1234" })), + ) + .await + .status, + StatusCode::OK + ); + let clash = send( + &app, + "PATCH", + &format!("/users/{alice_id}/profile"), + Some(&admin), + Some(json!({ "student_number": "1234" })), + ) + .await; + assert_eq!(clash.status, StatusCode::CONFLICT, "{}", clash.body); + assert_eq!(clash.body["error"], "student number already taken"); + assert_eq!(clash.body["code"], "student_number_taken"); + let one = send( + &app, + "GET", + &format!("/users/{alice_id}"), + Some(&admin), + None, + ) + .await; + assert_eq!(one.body["student_number"], "9-B/18"); + + // Only students hold one. A teacher target refuses a value outright... + let teacher = send( + &app, + "POST", + "/users", + Some(&admin), + Some(json!({ "username": "hoca", "password": "secret1", "role": "teacher" })), + ) + .await; + assert_eq!(teacher.status, StatusCode::CREATED, "{}", teacher.body); + let teacher_id = id_of(&teacher.body); + let refused = send( + &app, + "PATCH", + &format!("/users/{teacher_id}/profile"), + Some(&admin), + Some(json!({ "student_number": "5678" })), + ) + .await; + assert_eq!(refused.status, StatusCode::BAD_REQUEST, "{}", refused.body); + assert_eq!( + refused.body["error"], + "student_number: only a student account may hold a student number" + ); + // ...and so does the admin's own row through the self door. + assert_eq!( + send( + &app, + "PATCH", + "/users/me", + Some(&admin), + Some(json!({ "student_number": "9999" })), + ) + .await + .status, + StatusCode::BAD_REQUEST + ); + // A *clear* is not a set: blank on a non-student is the same no-op the + // omitted field is, never a refusal. + assert_eq!( + send( + &app, + "PATCH", + "/users/me", + Some(&admin), + Some(json!({ "student_number": "" })), + ) + .await + .status, + StatusCode::OK + ); + + // Blank (and whitespace) clears a student's number rather than storing an + // empty string. + let cleared = send( + &app, + "PATCH", + "/users/me", + Some(&alice), + Some(json!({ "student_number": " " })), + ) + .await; + assert_eq!(cleared.status, StatusCode::OK, "{}", cleared.body); + assert!(cleared.body["student_number"].is_null(), "{}", cleared.body); + + // The role cascade is the other half of the rule: a promotion out of + // `student` clears the number in the same transaction, and a later + // demotion back to `student` does not restore it — the number is set, not + // remembered. + assert_eq!( + send( + &app, + "PATCH", + &format!("/users/{alice_id}/profile"), + Some(&admin), + Some(json!({ "student_number": "9-B/17" })), + ) + .await + .status, + StatusCode::OK + ); + let promoted = send( + &app, + "PATCH", + &format!("/users/{alice_id}/role"), + Some(&admin), + Some(json!({ "role": "teacher" })), + ) + .await; + assert_eq!(promoted.status, StatusCode::OK, "{}", promoted.body); + assert!( + promoted.body["student_number"].is_null(), + "the promotion clears the number: {}", + promoted.body + ); + let one = send( + &app, + "GET", + &format!("/users/{alice_id}"), + Some(&admin), + None, + ) + .await; + assert!(one.body["student_number"].is_null(), "{}", one.body); + let demoted = send( + &app, + "PATCH", + &format!("/users/{alice_id}/role"), + Some(&admin), + Some(json!({ "role": "student" })), + ) + .await; + assert_eq!(demoted.status, StatusCode::OK, "{}", demoted.body); + assert!( + demoted.body["student_number"].is_null(), + "a role change to student leaves it unset: {}", + demoted.body + ); +} + // --- users: UI preferences (theme, language, palette color) ------------------------------ #[tokio::test] diff --git a/tests/spec_bounds.rs b/tests/spec_bounds.rs index 9297d18..0f94be1 100644 --- a/tests/spec_bounds.rs +++ b/tests/spec_bounds.rs @@ -244,6 +244,12 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { "maxLength", MAX_PASSWORD_LEN as i64, ), + ( + "CreateUser", + "student_number", + "maxLength", + MAX_STUDENT_NUMBER_LEN as i64, + ), ("SelectSchool", "school", "minLength", MIN_SLUG_LEN as i64), ("SelectSchool", "school", "maxLength", MAX_SLUG_LEN as i64), ("UpdateProfile", "name", "maxLength", MAX_NAME_LEN as i64), @@ -264,6 +270,12 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { "maxLength", MAX_SETTINGS_ITEM_LEN as i64, ), + ( + "UpdateProfile", + "student_number", + "maxLength", + MAX_STUDENT_NUMBER_LEN as i64, + ), ( "CreateNote", "title",