forge
Explore
Log in

Don't you dare go Hollow

Give students a school-issued student number

Browse files at this commit

777c7dffb1716923ad27e427dd0a6d8c1fe0cafbAhmet Kaan GümüşParent: 0b1c289
  • feat
    • give students a school-issued student number
Show full message
✨ feat(users): give students a school-issued student number

Every school numbers its students its own way ("1234", "9-B/17"), and the
account carried no field for it: the office kept the mapping outside the
product. The number is now a first-class optional field on the user row,
unique inside the school (per-school uniqueness is the per-school database)
and held by students only.

- migrations/school/20260920000001_student_number.sql: `app_user
  .student_number TEXT NULL`, the partial unique index over its non-NULL
  values, and a CHECK (student_number IS NULL OR role = 'student'). The boot
  sweep applies the file to already-provisioned schools like every other
  school migration.
- domain: `StudentNumber`, a validated newtype (trimmed, non-blank, at most
  MAX_STUDENT_NUMBER_LEN = 32) in the shape of `Username`, plus the one
  spelling of the non-student refusal both the web gate and the database map
  answer; `User` carries `Option<StudentNumber>`.
- db: `create_with_role` binds it into the mint; `set_profile` writes it and
  maps the index's 23505 to the coded 409 and the row's 23514 to the same 400
  the handler gate answers; `set_role_cascade` clears it in the same statement
  that leaves the `student` role. The CHECK is what closes the read-then-write
  race the handler-side gate cannot see: a profile save carrying a number from
  a `student` snapshot while a promotion commits first is refused by the row
  itself, and a test pins exactly that (it writes a teacher holding a number
  without the CHECK).
- web: `POST /users` and both profile doors (`PATCH /users/me`,
  `PATCH /users/{id}/profile`) accept it under the merge semantics the other
  patchable fields have (omitted = keep, blank = clear), with the role gate as
  a 400 and a duplicate as a 409 carrying `code: student_number_taken`.
  `UserResponse` (admin reads, create/patch echoes, `/auth/me`) and `PersonRef`
  (pickers, students lists) carry it; the school-wide public profile
  deliberately does not — an office identifier is not broadcast school-wide.
- /limits publishes `max_student_number_len`; spec_bounds pins both new
  `max_length` annotations and the README's bound count moves to 224.
- tests: the mint and both patch doors — trimmed storage, 33 chars a 400,
  whitespace read as absent, a duplicate a coded 409 on both paths, a
  non-student a 400, blank clearing, a promotion clearing with the role change
  (and a demotion back not restoring it), and the stale-snapshot race at the
  db layer.

Evidence: the partial index refuses a duplicate (23505 naming
app_user_student_number) and admits both rows once dropped inside a
rolled-back transaction; with the 409 mapping removed both write paths answer
500 and the tests fail; with the CHECK removed the race test writes the
forbidden row (role: Teacher, student_number: Some(...)) and fails.
Local-Gate: 2c10aae51c575b7f4207fa310d8938070c0fbb80 (1509 passed, 572s)
.sqlx/query-eb5fb3b8d7b2b7e6f199b036ae94637a4485b71ab52385a3016c9bdad24bd712.json → .sqlx/query-0887ff018a2ecdc9bf29472dd59b5e7f76610c2a39de92e7b30ad8be5a5966f8.jsonrenamed+14 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "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",
3+ "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",
44 "describe": {
55 "columns": [
66 {
@@ -192,6 +192,17 @@
192192 },
193193 {
194194 "ordinal": 17,
195+ "name": "student_number: StudentNumber",
196+ "type_info": "Text",
197+ "origin": {
198+ "Table": {
199+ "table": "app_user",
200+ "name": "student_number"
201+ }
202+ }
203+ },
204+ {
205+ "ordinal": 18,
195206 "name": "avatar_size",
196207 "type_info": "Int8",
197208 "origin": {
@@ -226,8 +237,9 @@
226237 true,
227238 true,
228239 true,
240+ true,
229241 true
230242 ]
231243 },
232- "hash": "eb5fb3b8d7b2b7e6f199b036ae94637a4485b71ab52385a3016c9bdad24bd712"
244+ "hash": "0887ff018a2ecdc9bf29472dd59b5e7f76610c2a39de92e7b30ad8be5a5966f8"
233245 }
.sqlx/query-ea2f28046b3ef41ed15703197135e3be14d9568d9795278a8afbc14dd52e448f.json → .sqlx/query-09f4fca0c1cf695324fd71baec63fd30baa3cfff04429798e9e8784ffb611ede.jsonrenamed+14 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "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)",
3+ "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)",
44 "describe": {
55 "columns": [
66 {
@@ -192,6 +192,17 @@
192192 },
193193 {
194194 "ordinal": 17,
195+ "name": "student_number: StudentNumber",
196+ "type_info": "Text",
197+ "origin": {
198+ "Table": {
199+ "table": "app_user",
200+ "name": "student_number"
201+ }
202+ }
203+ },
204+ {
205+ "ordinal": 18,
195206 "name": "avatar_size",
196207 "type_info": "Int8",
197208 "origin": {
@@ -225,8 +236,9 @@
225236 true,
226237 true,
227238 true,
239+ true,
228240 true
229241 ]
230242 },
231- "hash": "ea2f28046b3ef41ed15703197135e3be14d9568d9795278a8afbc14dd52e448f"
243+ "hash": "09f4fca0c1cf695324fd71baec63fd30baa3cfff04429798e9e8784ffb611ede"
232244 }
.sqlx/query-85c6837e943dbff5b411062672966a15f9eaa9da3501ac6ab774842587b3158f.json → .sqlx/query-7496e13f38da77b1fc311a687f1996651f4d8ce46c0ee401f63d2a5f80334ab2.jsonrenamed+14 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "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",
3+ "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",
44 "describe": {
55 "columns": [
66 {
@@ -192,6 +192,17 @@
192192 },
193193 {
194194 "ordinal": 17,
195+ "name": "student_number: StudentNumber",
196+ "type_info": "Text",
197+ "origin": {
198+ "Table": {
199+ "table": "app_user",
200+ "name": "student_number"
201+ }
202+ }
203+ },
204+ {
205+ "ordinal": 18,
195206 "name": "avatar_size",
196207 "type_info": "Int8",
197208 "origin": {
@@ -225,8 +236,9 @@
225236 true,
226237 true,
227238 true,
239+ true,
228240 true
229241 ]
230242 },
231- "hash": "85c6837e943dbff5b411062672966a15f9eaa9da3501ac6ab774842587b3158f"
243+ "hash": "7496e13f38da77b1fc311a687f1996651f4d8ce46c0ee401f63d2a5f80334ab2"
232244 }
.sqlx/query-8fb4f8d22b9aca20a9cfa7de35bd4bac5ce3a0bfdbd4059a08b0b27d25b62537.json → .sqlx/query-ac0befbd1b4398d79d2bbe2d8923bde69dfbe93bbb60dadc632ce93bbe18f8a6.jsonrenamed+14 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "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",
3+ "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",
44 "describe": {
55 "columns": [
66 {
@@ -192,6 +192,17 @@
192192 },
193193 {
194194 "ordinal": 17,
195+ "name": "student_number: StudentNumber",
196+ "type_info": "Text",
197+ "origin": {
198+ "Table": {
199+ "table": "app_user",
200+ "name": "student_number"
201+ }
202+ }
203+ },
204+ {
205+ "ordinal": 18,
195206 "name": "avatar_size",
196207 "type_info": "Int8",
197208 "origin": {
@@ -225,8 +236,9 @@
225236 true,
226237 true,
227238 true,
239+ true,
228240 true
229241 ]
230242 },
231- "hash": "8fb4f8d22b9aca20a9cfa7de35bd4bac5ce3a0bfdbd4059a08b0b27d25b62537"
243+ "hash": "ac0befbd1b4398d79d2bbe2d8923bde69dfbe93bbb60dadc632ce93bbe18f8a6"
232244 }
.sqlx/query-46be1d9c474028739e57a52bbf0ea26a101bbed607e14890aa6349fd767ec701.json → .sqlx/query-c8eeec6b17943f913ed919e8663e44fc9d0e85ac9eaa6a7f2c9b012237381d5c.jsonrenamed+14 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "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",
3+ "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",
44 "describe": {
55 "columns": [
66 {
@@ -192,6 +192,17 @@
192192 },
193193 {
194194 "ordinal": 17,
195+ "name": "student_number: StudentNumber",
196+ "type_info": "Text",
197+ "origin": {
198+ "Table": {
199+ "table": "app_user",
200+ "name": "student_number"
201+ }
202+ }
203+ },
204+ {
205+ "ordinal": 18,
195206 "name": "avatar_size",
196207 "type_info": "Int8",
197208 "origin": {
@@ -225,8 +236,9 @@
225236 true,
226237 true,
227238 true,
239+ true,
228240 true
229241 ]
230242 },
231- "hash": "46be1d9c474028739e57a52bbf0ea26a101bbed607e14890aa6349fd767ec701"
243+ "hash": "c8eeec6b17943f913ed919e8663e44fc9d0e85ac9eaa6a7f2c9b012237381d5c"
232244 }
.sqlx/query-22d8652b21f633600d075ca3aff634ad2ae34dfbc87907a1f41229365726763f.json → .sqlx/query-e30a05b019f2834851c819abde37d928f6a02f051e99bc877168f48d142bff8b.jsonrenamed+15 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "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",
3+ "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",
44 "describe": {
55 "columns": [
66 {
@@ -192,6 +192,17 @@
192192 },
193193 {
194194 "ordinal": 17,
195+ "name": "student_number: StudentNumber",
196+ "type_info": "Text",
197+ "origin": {
198+ "Table": {
199+ "table": "app_user",
200+ "name": "student_number"
201+ }
202+ }
203+ },
204+ {
205+ "ordinal": 18,
195206 "name": "avatar_size",
196207 "type_info": "Int8",
197208 "origin": {
@@ -208,6 +219,7 @@
208219 "Text",
209220 "Uuid",
210221 "Text",
222+ "Text",
211223 "Int8"
212224 ]
213225 },
@@ -229,8 +241,9 @@
229241 true,
230242 true,
231243 true,
244+ true,
232245 true
233246 ]
234247 },
235- "hash": "22d8652b21f633600d075ca3aff634ad2ae34dfbc87907a1f41229365726763f"
248+ "hash": "e30a05b019f2834851c819abde37d928f6a02f051e99bc877168f48d142bff8b"
236249 }
.sqlx/query-1a258b398d6023dbb6e42c7e3f3df270d77dc6d69959d376df8be1c170e74e88.json → .sqlx/query-fb4bc5f405406b6b5f6a41705b65ceb78cd496905d3da3669ab659e57b0ed7fc.jsonrenamed+14 -2
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "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",
3+ "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",
44 "describe": {
55 "columns": [
66 {
@@ -192,6 +192,17 @@
192192 },
193193 {
194194 "ordinal": 17,
195+ "name": "student_number: StudentNumber",
196+ "type_info": "Text",
197+ "origin": {
198+ "Table": {
199+ "table": "app_user",
200+ "name": "student_number"
201+ }
202+ }
203+ },
204+ {
205+ "ordinal": 18,
195206 "name": "avatar_size",
196207 "type_info": "Int8",
197208 "origin": {
@@ -225,8 +236,9 @@
225236 true,
226237 true,
227238 true,
239+ true,
228240 true
229241 ]
230242 },
231- "hash": "1a258b398d6023dbb6e42c7e3f3df270d77dc6d69959d376df8be1c170e74e88"
243+ "hash": "fb4bc5f405406b6b5f6a41705b65ceb78cd496905d3da3669ab659e57b0ed7fc"
232244 }
README.mdmodified+6 -6
@@ -720,7 +720,7 @@ drift from it**, which is enforced rather than asked for:
720720 and fails unless each one is either referenced by `src/web/limits.rs` or
721721 listed as a deliberate exclusion *with a reason*. A new constant breaks the
722722 suite until someone decides, consciously, whether clients need it.
723-- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 222 published
723+- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 224 published
724724 bounds back out of the emitted JSON, and asserts each equals its constant.
725725 This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal
726726 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.
14781478 | POST | `/terms/{id}/unarchive` | manager | Re-open an archived term. Requires manager+. Idempotent the same way as archiving: an already-open term answers `200`. |
14791479 | GET | `/time` | no | Server clock: `{now}` UTC unix-millis, for a frontend to sync against. |
14801480 | 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. |
1481-| 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. |
1482-| 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. |
1481+| 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. |
1482+| 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`). |
14831483 | 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. |
14841484 | 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. |
14851485 | DELETE | `/users/me/avatar` | student | Remove the caller's own avatar. |
14861486 | 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`. |
14871487 | GET | `/users/me/profile` | student | The caller's own public profile — what everyone else sees of them. |
14881488 | 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=`. |
1489-| 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. |
1489+| 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. |
14901490 | GET | `/users/{id}` | admin | Fetch one user with their role and personal info. Admin only. |
14911491 | 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'. |
14921492 | 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. |
14931493 | 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. |
14941494 | 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. |
1495-| 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`. |
1496-| 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. |
1495+| 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". |
1496+| 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. |
14971497 | 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. |
14981498 | 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. |
14991499 | 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. |
migrations/school/20260920000001_student_number.sqladded+39 -0
@@ -0,0 +1,39 @@
1+-- The student number: the school's own identifier for a student ("1234",
2+-- "9-B/17"), carried on the account row.
3+--
4+-- WHERE THIS FILE BELONGS: `migrations/school/` in the backend repo. APPEND-ONLY
5+-- relative to the existing school migrations: it touches no other table.
6+--
7+-- WHY ON `app_user`: the number belongs to the *account in this school*, not to
8+-- the global person — two schools may issue the same number to two different
9+-- students, and a person's membership in one school must not constrain another.
10+-- `NULL` on every account that holds none, which is every staff account and
11+-- every student registered before the school got round to issuing numbers.
12+--
13+-- UNIQUENESS IS PER SCHOOL BY CONSTRUCTION: each school already lives in its own
14+-- database, so a plain partial unique index is the whole rule — no school column,
15+-- exactly like `app_user_username` and `app_user_person`. The partial predicate
16+-- (`WHERE student_number IS NOT NULL`) is what keeps unlimited accounts without
17+-- a number legal: in Postgres, NULLs in a plain UNIQUE index would be distinct
18+-- anyway, but the partial index also keeps the index off the rows that carry no
19+-- value.
20+--
21+-- Only a student row may hold one. That rule has three enforcement points and
22+-- they are not redundant: the web layer refuses the request (a 400 with the
23+-- live role it read), the role cascade clears the column in the same statement
24+-- that leaves the student role, and the CHECK below is what holds when the two
25+-- race — a profile write carrying a number from a snapshot read while the role
26+-- write commits first would otherwise land a number on a promoted row, and the
27+-- handler-side gate cannot see that. A `CHECK` may reference other columns of
28+-- its own row (unlike a `UNIQUE`), so the row's own role is exactly the
29+-- predicate; the column is new and NULL on every existing row, so no row can
30+-- be in violation at creation time. A violation answers the same 400 the
31+-- web gate does (`crate::db::user` maps 23514 to it), never a 500.
32+ALTER TABLE app_user ADD COLUMN IF NOT EXISTS student_number TEXT NULL;
33+
34+ALTER TABLE app_user
35+ ADD CONSTRAINT app_user_student_number_student
36+ CHECK (student_number IS NULL OR role = 'student');
37+
38+CREATE UNIQUE INDEX IF NOT EXISTS app_user_student_number
39+ ON app_user (student_number) WHERE student_number IS NOT NULL;
src/constant.rsmodified+7 -0
@@ -12,6 +12,13 @@ pub const MAX_SCHOOL_NAME_LEN: usize = 120;
1212 pub const MIN_USERNAME_LEN: usize = 3;
1313 pub const MAX_USERNAME_LEN: usize = 32;
1414
15+/// A student's school-issued number. Free text rather than digits on purpose —
16+/// schools prefix, slash and hyphenate them ("9-B/17") — bounded like the other
17+/// short labels. Only students hold one (the write paths enforce the role, and
18+/// the role cascade clears it), and it is unique inside the school (the partial
19+/// unique index is the enforcement).
20+pub const MAX_STUDENT_NUMBER_LEN: usize = 32;
21+
1522 /// Separators allowed inside a username (never at the edges, never doubled).
1623 pub const USERNAME_SEPARATORS: [char; 3] = ['.', '_', '-'];
1724
src/database.rsmodified+14 -0
@@ -463,6 +463,20 @@ pub fn exclusion_violation(err: &sqlx::Error) -> Option<&str> {
463463 }
464464 }
465465
466+/// The violated `CHECK` constraint's name, when `err` is a check violation
467+/// (`23514`) — a row the statement would have written in a state its own DDL
468+/// forbids. Named like [`unique_violation`] so a call site can tell which rule
469+/// refused (`student_number IS NULL OR role = 'student'`) instead of answering
470+/// a generic 500 for a caller's mistake.
471+pub fn check_violation(err: &sqlx::Error) -> Option<&str> {
472+ let db = err.as_database_error()?;
473+ if db.code().as_deref() == Some("23514") {
474+ db.constraint()
475+ } else {
476+ None
477+ }
478+}
479+
466480 /// A foreign-key violation (`23503`): a parent row a statement names is gone.
467481 pub fn foreign_key_violation(err: &sqlx::Error) -> bool {
468482 err.as_database_error()
src/db/user.rsmodified+166 -15
@@ -4,11 +4,11 @@
44 //! the cascade lives in [`crate::service::user`].
55 //!
66 //! The compile-time macros map columns by name and check each decoded type
7-//! against the prepare schema, so the seventeen user columns are spelled
7+//! against the prepare schema, so the eighteen user columns are spelled
88 //! out — newtype overrides included — in every static statement below. The
99 //! repetitions are the check.
1010
11-use crate::database::{Database, tx_with_retry};
11+use crate::database::{Database, check_violation, tx_with_retry, unique_violation};
1212 use crate::db::field_update::FieldUpdate;
1313 use crate::db::page::{PagedList, Param};
1414 use crate::domain::board::{Board, BoardId, BoardTitle};
@@ -19,9 +19,21 @@ use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Pho
1919 use crate::domain::role::Role;
2020 use crate::domain::text_fold::{search_fold, search_fold_sql};
2121 use crate::domain::timestamp::Timestamp;
22-use crate::domain::user::{User, UserId, Username};
22+use crate::domain::user::{StudentNumber, User, UserId, Username};
2323 use crate::error::AppError;
2424
25+/// The answer a duplicate `student_number` gets, from both write paths that
26+/// can raise one (the mint and the profile writer). One spelling so the two
27+/// cannot drift, and `ConflictCoded` because the frontend branches on the
28+/// cause — the number is refused by the partial unique index
29+/// (`app_user_student_number`), not by anything the message could name.
30+fn number_taken() -> AppError {
31+ AppError::ConflictCoded {
32+ code: "student_number_taken",
33+ message: "student number already taken".to_owned(),
34+ }
35+}
36+
2537 /// Register a new school account for the control-plane `person` whose
2638 /// credential login verifies — `person` is the join key, `None` only where the
2739 /// caller cannot know it yet (tests, the boot seed's row-first order — see
@@ -33,7 +45,7 @@ pub async fn create(
3345 username: Username,
3446 person: Option<PersonId>,
3547 ) -> Result<User, AppError> {
36- create_with_role(db, username, person, Role::Student).await
48+ create_with_role(db, username, person, Role::Student, None).await
3749 }
3850
3951 /// The one row-minting path. `role` is written *with* the row rather than
@@ -50,18 +62,27 @@ pub async fn create(
5062 /// of a race gets the same 409 the sequential duplicate always got.
5163 ///
5264 /// The row carries its `created_at` mint stamp and, when the caller knows it,
53-/// the `person` id the credential lives on.
65+/// the `person` id the credential lives on. `student_number` binds as handed:
66+/// the *role* rule ("only a student may hold one") is the web layer's gate —
67+/// it is the layer that resolves the requested role — while the *uniqueness*
68+/// rule is the partial unique index, and its violation answers the same 409
69+/// the duplicate username does.
5470 pub async fn create_with_role(
5571 db: &Database,
5672 username: Username,
5773 person: Option<PersonId>,
5874 role: Role,
75+ student_number: Option<StudentNumber>,
5976 ) -> Result<User, AppError> {
77+ debug_assert!(
78+ student_number.is_none() || role == Role::Student,
79+ "only a student row may be born with a student number"
80+ );
6081 let id = UserId::generate();
6182 match sqlx::query_as!(
6283 User,
63- r#"INSERT INTO app_user (id, username, person, role, created_at)
64- VALUES ($1, $2, $3, $4, $5)
84+ r#"INSERT INTO app_user (id, username, person, role, student_number, created_at)
85+ VALUES ($1, $2, $3, $4, $5, $6)
6586 RETURNING id AS "id: UserId",
6687 username AS "username: Username",
6788 person AS "person: PersonId",
@@ -79,11 +100,13 @@ pub async fn create_with_role(
79100 avatar_file,
80101 avatar_content_type AS "avatar_content_type: FileContentType",
81102 branch,
103+ student_number AS "student_number: StudentNumber",
82104 avatar_size"#,
83105 id.uuid(),
84106 username.as_str(),
85107 person.as_ref().map(PersonId::uuid),
86108 role.as_str(),
109+ student_number.as_ref().map(StudentNumber::as_str),
87110 Timestamp::now().as_millis(),
88111 )
89112 .fetch_one(db)
@@ -96,9 +119,17 @@ pub async fn create_with_role(
96119 );
97120 Ok(user)
98121 }
99- Err(err) if crate::database::unique_violation(&err) == Some("app_user_username") => {
122+ Err(err) if unique_violation(&err) == Some("app_user_username") => {
100123 Err(AppError::Conflict("username already taken"))
101124 }
125+ Err(err) if unique_violation(&err) == Some("app_user_student_number") => {
126+ Err(number_taken())
127+ }
128+ // The row's own CHECK: this path already debug-asserts the rule, and
129+ // in a release build the database is what says no.
130+ Err(err) if check_violation(&err) == Some("app_user_student_number_student") => {
131+ Err(StudentNumber::non_student_refusal().into())
132+ }
102133 Err(err) => Err(err.into()),
103134 }
104135 }
@@ -123,6 +154,7 @@ pub async fn read(db: &Database, id: &UserId) -> Result<Option<User>, AppError>
123154 avatar_file,
124155 avatar_content_type AS "avatar_content_type: FileContentType",
125156 branch,
157+ student_number AS "student_number: StudentNumber",
126158 avatar_size
127159 FROM app_user WHERE id = $1"#,
128160 id.uuid()
@@ -168,6 +200,7 @@ pub async fn list_by_ids(db: &Database, ids: &[UserId]) -> Result<Vec<User>, App
168200 avatar_file,
169201 avatar_content_type AS "avatar_content_type: FileContentType",
170202 branch,
203+ student_number AS "student_number: StudentNumber",
171204 avatar_size
172205 FROM app_user WHERE id = ANY($1)"#,
173206 &ids
@@ -200,6 +233,7 @@ pub async fn list_by_role(db: &Database, role: Role) -> Result<Vec<User>, AppErr
200233 avatar_file,
201234 avatar_content_type AS "avatar_content_type: FileContentType",
202235 branch,
236+ student_number AS "student_number: StudentNumber",
203237 avatar_size
204238 FROM app_user WHERE role = $1 ORDER BY id DESC"#,
205239 role.as_str()
@@ -285,11 +319,13 @@ pub async fn search(
285319 /// the floor that guards it and the arm-by-arm reasoning. What follows is
286320 /// the store side.
287321 ///
288-/// Writes *only* the `role` field of the user row (never the whole row):
289-/// the row mixes admin-owned (role) and self-service (profile, preferences)
290-/// fields, and each writer starts from a snapshot read at request start. A
291-/// whole-row write would carry the snapshot's copy of the *other* group back
292-/// over a concurrent edit — an in-flight profile save silently reverting an
322+/// Writes *only* the `role` field of the user row — plus `student_number`,
323+/// cleared in that same statement whenever the new role is not `student`
324+/// (see the statement's own note) — never the whole row: the row mixes
325+/// admin-owned (role) and self-service (profile, preferences) fields, and
326+/// each writer starts from a snapshot read at request start. A whole-row
327+/// write would carry the snapshot's copy of the *other* group back over a
328+/// concurrent edit — an in-flight profile save silently reverting an
293329 /// admin's demotion, or this write erasing a profile edit that raced it.
294330 /// [`set_profile`] and [`set_preferences`] are scoped for the same reason.
295331 ///
@@ -396,10 +432,16 @@ pub async fn set_role_cascade(
396432
397433 // The role write, floor guard included. `$2 <> 'admin'` arms the
398434 // guard only for a demotion: a promotion or a same-role rewrite can
399- // never orphan the admins.
435+ // never orphan the admins. `student_number` rides the same statement:
436+ // the number names a student of this school, so the write that stops
437+ // being one is the write that drops it — a re-stated `student` keeps
438+ // it, everything else clears it, and no window exists where a
439+ // promoted account still holds one.
400440 let updated = sqlx::query_as!(
401441 User,
402- r#"UPDATE app_user SET role = $2
442+ r#"UPDATE app_user
443+ SET role = $2,
444+ student_number = CASE WHEN $2 = 'student' THEN student_number ELSE NULL END
403445 WHERE id = $1
404446 AND NOT (role = 'admin'
405447 AND $2 <> 'admin'
@@ -422,6 +464,7 @@ pub async fn set_role_cascade(
422464 avatar_file,
423465 avatar_content_type AS "avatar_content_type: FileContentType",
424466 branch,
467+ student_number AS "student_number: StudentNumber",
425468 avatar_size"#,
426469 target.uuid(),
427470 role.as_str(),
@@ -657,6 +700,14 @@ pub async fn set_role_cascade(
657700 /// for an omitted field would revert a concurrent PATCH of that field —
658701 /// two profile edits (a name and a phone) used to lose each other. See
659702 /// [`set_role_cascade`] for why no writer here touches the whole row.
703+///
704+/// `student_number` is the one column here whose write can be *violated*
705+/// rather than merely refused: the partial unique index is its whole
706+/// availability check, so a duplicate the caller did not pre-check (and
707+/// could not — a pre-check races) comes back as the index's 23505 and is
708+/// mapped to the same 409 the duplicate-username path answers. The role
709+/// gate ("only a student holds one") stays at the web layer, which holds
710+/// the row it read.
660711 // One argument per nullable column is the point: folding them into a struct
661712 // would just re-spell the HTTP DTO here and cost the compiler's check that
662713 // every column was considered at the call site.
@@ -672,6 +723,7 @@ pub async fn set_profile(
672723 display_name: Option<Option<DisplayName>>,
673724 bio: Option<Option<Bio>>,
674725 branch: Option<Option<String>>,
726+ student_number: Option<Option<StudentNumber>>,
675727 ) -> Result<User, AppError> {
676728 // `Some(None)` must bind an explicit NULL and `Some(Some(v))` a value:
677729 // `Param::OptText` carries both shapes of one nullable TEXT column.
@@ -718,8 +770,38 @@ pub async fn set_profile(
718770 "branch",
719771 text(branch.as_ref().map(|n| n.as_ref().map(String::as_str))),
720772 )
773+ .set(
774+ "student_number",
775+ text(
776+ student_number
777+ .as_ref()
778+ .map(|n| n.as_ref().map(StudentNumber::as_str)),
779+ ),
780+ )
721781 .run(db)
722782 .await
783+ .map_err(|err| match err {
784+ // The index's own refusal, named. A `SELECT`-then-write pre-check
785+ // would race (two students claim the same number, both read free);
786+ // the partial unique index is the serialization point, so this is
787+ // the only place the collision is knowable.
788+ AppError::Db(sqlx_err)
789+ if unique_violation(&sqlx_err) == Some("app_user_student_number") =>
790+ {
791+ number_taken()
792+ }
793+ // The other half of the rule, and the one only the database can
794+ // hold: this write carried a number from a snapshot that said
795+ // `student`, while the role write committed first. The CHECK sees
796+ // the row as it is *now*, and the caller gets the same 400 the
797+ // web pre-check answers.
798+ AppError::Db(sqlx_err)
799+ if check_violation(&sqlx_err) == Some("app_user_student_number_student") =>
800+ {
801+ StudentNumber::non_student_refusal().into()
802+ }
803+ other => other,
804+ })
723805 }
724806
725807 /// Point the row at a freshly uploaded avatar blob, returning the row *as
@@ -766,6 +848,7 @@ pub async fn set_avatar(
766848 avatar_file,
767849 avatar_content_type AS "avatar_content_type: FileContentType",
768850 branch,
851+ student_number AS "student_number: StudentNumber",
769852 avatar_size
770853 FROM app_user WHERE id = $1 FOR UPDATE"#,
771854 id.uuid()
@@ -815,6 +898,7 @@ pub async fn clear_avatar(db: &Database, id: &UserId) -> Result<Option<User>, Ap
815898 avatar_file,
816899 avatar_content_type AS "avatar_content_type: FileContentType",
817900 branch,
901+ student_number AS "student_number: StudentNumber",
818902 avatar_size
819903 FROM app_user WHERE id = $1 FOR UPDATE"#,
820904 id.uuid()
@@ -878,6 +962,7 @@ pub async fn find_by_username(db: &Database, username: &str) -> Result<Option<Us
878962 avatar_file,
879963 avatar_content_type AS "avatar_content_type: FileContentType",
880964 branch,
965+ student_number AS "student_number: StudentNumber",
881966 avatar_size
882967 FROM app_user WHERE username = $1"#,
883968 username
@@ -930,6 +1015,7 @@ mod tests {
9301015 None,
9311016 None,
9321017 None,
1018+ None,
9331019 )
9341020 .await
9351021 .unwrap();
@@ -947,6 +1033,70 @@ mod tests {
9471033 );
9481034 }
9491035
1036+ /// The role rule is the *database's*, not only the handler's: a profile
1037+ /// write carrying a number read from a `student` snapshot must be refused
1038+ /// when a promotion committed in between — exactly as the web pre-check
1039+ /// would have refused it a moment earlier. Without the row's own `CHECK`
1040+ /// this write lands and leaves a teacher holding a student number, which
1041+ /// every later read would serve.
1042+ #[tokio::test]
1043+ async fn a_stale_number_write_cannot_outrun_a_promotion() {
1044+ let (db, _leases) = init_test_db().await;
1045+ let user = a_user("selin", &db).await;
1046+ let number = StudentNumber::try_new("9-B/17").unwrap();
1047+ // Numbered while a student.
1048+ set_profile(
1049+ &db,
1050+ user.get_id(),
1051+ None,
1052+ None,
1053+ None,
1054+ None,
1055+ None,
1056+ None,
1057+ None,
1058+ None,
1059+ Some(Some(number.clone())),
1060+ )
1061+ .await
1062+ .unwrap();
1063+
1064+ // The handler reads its snapshot (role = student, number set)...
1065+ let stale = read(&db, user.get_id()).await.unwrap().unwrap();
1066+ // ...the promotion commits, clearing the number...
1067+ crate::service::user::set_role(&db, user.get_id(), Role::Teacher)
1068+ .await
1069+ .unwrap();
1070+ // ...and the in-flight save lands from the stale snapshot.
1071+ let refused = set_profile(
1072+ &db,
1073+ stale.get_id(),
1074+ None,
1075+ None,
1076+ None,
1077+ None,
1078+ None,
1079+ None,
1080+ None,
1081+ None,
1082+ Some(Some(number)),
1083+ )
1084+ .await;
1085+ match refused {
1086+ Err(AppError::Validation(crate::error::ValidationError::Invalid { field, .. })) => {
1087+ assert_eq!(field, "student_number")
1088+ }
1089+ other => panic!("the database must refuse a number on a promoted row: {other:?}"),
1090+ }
1091+ let after = read(&db, user.get_id()).await.unwrap().unwrap();
1092+ assert_eq!(after.get_role(), Role::Teacher);
1093+ assert_eq!(
1094+ after.get_student_number(),
1095+ None,
1096+ "a promoted row holds no number"
1097+ );
1098+ }
1099+
9501100 #[tokio::test]
9511101 async fn an_avatar_upload_cannot_revert_a_role_change() {
9521102 let (db, _leases) = init_test_db().await;
@@ -972,6 +1122,7 @@ mod tests {
9721122 Some(Some(display_name.clone())),
9731123 None,
9741124 None,
1125+ None,
9751126 )
9761127 .await
9771128 .unwrap();
src/domain/user.rsmodified+66 -2
@@ -9,7 +9,7 @@ use argon2::password_hash::phc::PasswordHash as PhcHash;
99 use argon2::{Argon2, PasswordHasher, PasswordVerifier};
1010 use uuid::Uuid;
1111
12-use crate::constant::{AI_PRINCIPAL_KEY, DECOY_PASSWORD};
12+use crate::constant::{AI_PRINCIPAL_KEY, DECOY_PASSWORD, MAX_STUDENT_NUMBER_LEN};
1313 use crate::domain::monotonic_id::next_uuid;
1414 use crate::domain::note_file::FileContentType;
1515 use crate::domain::person::PersonId;
@@ -17,7 +17,7 @@ use crate::domain::preferences::{Language, PaletteColor, Theme};
1717 use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone};
1818 use crate::domain::role::Role;
1919 use crate::error::{AppError, ValidationError};
20-use crate::validate::{validate_password, validate_username};
20+use crate::validate::{validate_password, validate_required, validate_username};
2121
2222 /// Typed user row id. A UUIDv7 minted by the process-wide monotonic
2323 /// generator, so `id` order is mint order.
@@ -75,6 +75,44 @@ impl Username {
7575 }
7676 }
7777
78+/// A validated student number. Construction canonicalizes the value the way
79+/// [`Username`] does — the stored string is trimmed, because the partial unique
80+/// index keys on it and `"1234 "` must collide with `"1234"`, not sit beside it
81+/// as a second number the school never issued.
82+///
83+/// Shape only: non-blank and within [`MAX_STUDENT_NUMBER_LEN`]. Uniqueness is
84+/// the index's, and *so is the role rule* — whether the holding account is a
85+/// student is the write path's check (it holds the row), never this type's,
86+/// which never sees a role.
87+#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
88+#[sqlx(transparent)]
89+pub struct StudentNumber(String);
90+
91+impl StudentNumber {
92+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
93+ let trimmed = value.trim();
94+ validate_required("student_number", trimmed, MAX_STUDENT_NUMBER_LEN)?;
95+ Ok(Self(trimmed.to_string()))
96+ }
97+
98+ pub fn as_str(&self) -> &str {
99+ &self.0
100+ }
101+
102+ /// The refusal every write path answers when a number would land on a row
103+ /// that is not a student. Spelled once because two layers must say the
104+ /// same thing: the web layer's pre-check (against the role it read) and
105+ /// the database's own `CHECK` on the row (against the role at write time,
106+ /// which is what closes the read-then-write race) both answer a 400, and a
107+ /// client must not have to tell two sentences apart for one rule.
108+ pub fn non_student_refusal() -> ValidationError {
109+ ValidationError::Invalid {
110+ field: "student_number",
111+ reason: "only a student account may hold a student number",
112+ }
113+ }
114+}
115+
78116 /// Bounds how many argon2 hashes run at once. `spawn_blocking` is unbounded —
79117 /// tokio grows the blocking pool to 512 threads — and argon2's default `m_cost`
80118 /// is 19 MiB, so an un-capped login flood claims gigabytes (measured: ~17 MB
@@ -212,6 +250,12 @@ pub struct User {
212250 /// on rows minted before their person was known (boot seed order, tests).
213251 pub(crate) person: Option<PersonId>,
214252 pub(crate) role: Role,
253+ /// The school-issued student number, unique inside the school. `None` on
254+ /// every account that holds none — every staff account, and every student
255+ /// its school has not numbered yet. Only a student row may carry one:
256+ /// the write paths refuse a non-student, and the role cascade clears it in
257+ /// the same transaction that leaves the student role.
258+ pub(crate) student_number: Option<StudentNumber>,
215259 // Personal info, identical for every role. All optional: accounts are
216260 // created from bare credentials and filled in later, and rows from before
217261 // these fields existed simply read back as `None`.
@@ -256,6 +300,7 @@ impl User {
256300 username: Username(AI_PRINCIPAL_KEY.to_string()),
257301 person: None,
258302 role: Role::Ai,
303+ student_number: None,
259304 name: None,
260305 surname: None,
261306 email: None,
@@ -288,6 +333,14 @@ impl User {
288333 self.role
289334 }
290335
336+ /// The school-issued student number, as stored. Never non-`None` on a
337+ /// non-student row — the writes that could spell that are refused at the
338+ /// web layer, and the role cascade clears it on the way out of the student
339+ /// role.
340+ pub fn get_student_number(&self) -> Option<&StudentNumber> {
341+ self.student_number.as_ref()
342+ }
343+
291344 pub fn get_name(&self) -> Option<&PersonName> {
292345 self.name.as_ref()
293346 }
@@ -369,6 +422,17 @@ mod tests {
369422 assert_eq!(Username::try_new(" ali ").unwrap().as_str(), "ali");
370423 }
371424
425+ #[tokio::test]
426+ async fn student_number_newtype_validates_and_trims() {
427+ // Trimmed like the username, because the unique index keys on the
428+ // stored string: "1234 " and "1234" must be one number, not two.
429+ assert_eq!(StudentNumber::try_new(" 1234 ").unwrap().as_str(), "1234");
430+ assert!(StudentNumber::try_new("").is_err());
431+ assert!(StudentNumber::try_new(" ").is_err());
432+ assert!(StudentNumber::try_new(&"9".repeat(MAX_STUDENT_NUMBER_LEN)).is_ok());
433+ assert!(StudentNumber::try_new(&"9".repeat(MAX_STUDENT_NUMBER_LEN + 1)).is_err());
434+ }
435+
372436 #[tokio::test]
373437 async fn short_password_rejected() {
374438 assert!(Password::try_new("123").is_err());
src/service/rag_scope.rsmodified+9 -3
@@ -199,9 +199,15 @@ mod tests {
199199 /// row (and the membership and parent-link gates judge the exact role), so
200200 /// a fabricated id or the `fixture_user` default would not do.
201201 async fn person(db: &Database, username: &str, role: Role) -> User {
202- crate::db::user::create_with_role(db, Username::try_new(username).unwrap(), None, role)
203- .await
204- .unwrap()
202+ crate::db::user::create_with_role(
203+ db,
204+ Username::try_new(username).unwrap(),
205+ None,
206+ role,
207+ None,
208+ )
209+ .await
210+ .unwrap()
205211 }
206212
207213 /// A class section carrying a grade label — the half of every instance
src/service/user.rsmodified+12 -4
@@ -11,7 +11,7 @@ use crate::domain::person::PersonId;
1111 use crate::domain::preferences::{Language, PaletteColor, Theme};
1212 use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone};
1313 use crate::domain::role::Role;
14-use crate::domain::user::{Password, User, UserId, Username};
14+use crate::domain::user::{Password, StudentNumber, User, UserId, Username};
1515 use crate::error::AppError;
1616 use crate::tenant::{Slug, Tenants};
1717
@@ -58,7 +58,8 @@ pub async fn ensure_admin(
5858 // who registered the name first, so the hole cannot be healed
5959 // later; it has to be impossible to open.
6060 None => {
61- user::create_with_role(&db, username, Some(*person.get_id()), Role::Admin).await?;
61+ user::create_with_role(&db, username, Some(*person.get_id()), Role::Admin, None)
62+ .await?;
6263 // No `username` field: with OTLP on every event is exported as a
6364 // log record, so an account name here leaves the process.
6465 tracing::info!("seeded the admin account named by ADMIN_USERNAME");
@@ -110,14 +111,16 @@ pub async fn create(
110111 }
111112
112113 /// Mint a row holding `role` outright — the school-creation path, whose
113-/// first account must be an admin from birth.
114+/// first account must be an admin from birth — optionally numbered
115+/// (`student_number`; only a `student` row may carry one, the caller's check).
114116 pub async fn create_with_role(
115117 db: &Database,
116118 username: Username,
117119 person: Option<PersonId>,
118120 role: Role,
121+ student_number: Option<StudentNumber>,
119122 ) -> Result<User, AppError> {
120- user::create_with_role(db, username, person, role).await
123+ user::create_with_role(db, username, person, role, student_number).await
121124 }
122125
123126 /// One user row, for callers that only inspect it — the web layer's reads go
@@ -177,6 +180,10 @@ pub async fn set_profile(
177180 // school's `Settings::get_branches()` list is the caller's check, not this
178181 // one's.
179182 branch: Option<Option<String>>,
183+ // The school-issued student number, clearable like `bio`; *being a
184+ // student* is the caller's check (it holds the row), and uniqueness is
185+ // the partial index's, mapped to a 409 in [`crate::db::user`].
186+ student_number: Option<Option<StudentNumber>>,
180187 ) -> Result<User, AppError> {
181188 user::set_profile(
182189 db,
@@ -189,6 +196,7 @@ pub async fn set_profile(
189196 display_name,
190197 bio,
191198 branch,
199+ student_number,
192200 )
193201 .await
194202 }
src/web/builder.rsmodified+8 -2
@@ -379,8 +379,14 @@ async fn create_school(
379379 let id = SchoolId::generate();
380380 let db = st.tenants.create(id, &slug, &name, modules).await?;
381381 let seeded = async {
382- crate::service::user::create_with_role(&db, username, Some(*person.get_id()), Role::Admin)
383- .await?;
382+ crate::service::user::create_with_role(
383+ &db,
384+ username,
385+ Some(*person.get_id()),
386+ Role::Admin,
387+ None,
388+ )
389+ .await?;
384390 // The admin's person gets the membership the school row answers for —
385391 // idempotent, so a retried create after a torn pair completes it.
386392 service::person::link_school(&st.db, person.get_id(), &slug).await?;
src/web/dto.rsmodified+19 -0
@@ -83,6 +83,12 @@ pub struct PersonRef {
8383 /// `"Name Surname"` join, else `null`.
8484 #[schema(example = "Ada Lovelace")]
8585 pub display_name: Option<String>,
86+ /// The school-issued student number, `null` for every account that holds
87+ /// none (every staff account included). Part of "who this is" the way a
88+ /// username is, which is why it rides this ref rather than a route of its
89+ /// own — a roster that names a student can name their number.
90+ #[schema(example = "1234")]
91+ pub student_number: Option<String>,
8692 }
8793
8894 impl PersonRef {
@@ -103,6 +109,9 @@ impl PersonRef {
103109 .get_display_name()
104110 .map(|chosen| chosen.as_str().to_string())
105111 .or_else(|| (!full.is_empty()).then(|| full.join(" "))),
112+ student_number: user
113+ .get_student_number()
114+ .map(|number| number.as_str().to_string()),
106115 }
107116 }
108117
@@ -124,6 +133,7 @@ impl PersonRef {
124133 id: id.key().to_string(),
125134 username: id.key().to_string(),
126135 display_name: None,
136+ student_number: None,
127137 })
128138 }
129139 }
@@ -156,6 +166,12 @@ pub struct UserResponse {
156166 #[schema(example = "ada")]
157167 pub username: String,
158168 pub role: Role,
169+ /// The school-issued student number, unique inside the school. `null`
170+ /// when the account holds none — every staff account, and any student the
171+ /// office has not numbered yet. Only ever a value on a `student` row: a
172+ /// role change away from `student` clears it.
173+ #[schema(example = "1234")]
174+ pub student_number: Option<String>,
159175 #[schema(example = "Ada")]
160176 pub name: Option<String>,
161177 #[schema(example = "Lovelace")]
@@ -194,6 +210,9 @@ impl UserResponse {
194210 id: user.get_id().key().to_string(),
195211 username: user.get_username().as_str().to_string(),
196212 role: user.get_role().into(),
213+ student_number: user
214+ .get_student_number()
215+ .map(|number| number.as_str().to_string()),
197216 name: user.get_name().map(|v| v.as_str().to_string()),
198217 surname: user.get_surname().map(|v| v.as_str().to_string()),
199218 email: user.get_email().map(|v| v.as_str().to_string()),
src/web/limits.rsmodified+4 -0
@@ -55,6 +55,9 @@ struct UserLimits {
5555 max_display_name_len: usize,
5656 /// Free text under a profile's name.
5757 max_bio_len: usize,
58+ /// A student number's length bound (free text; unique inside the school,
59+ /// and only ever held by a `student` account).
60+ max_student_number_len: usize,
5861 /// How many course references a profile read embeds — a cap on the
5962 /// response, not on membership. The full list stays at `/courses/me`.
6063 max_profile_courses: usize,
@@ -546,6 +549,7 @@ impl LimitsResponse {
546549 max_name_len: MAX_NAME_LEN,
547550 max_display_name_len: MAX_DISPLAY_NAME_LEN,
548551 max_bio_len: MAX_BIO_LEN,
552+ max_student_number_len: MAX_STUDENT_NUMBER_LEN,
549553 max_profile_courses: MAX_PROFILE_COURSES,
550554 max_profile_classes: MAX_PROFILE_CLASSES,
551555 max_email_len: MAX_EMAIL_LEN,
src/web/messages.rsmodified+1 -0
@@ -129,6 +129,7 @@ impl MessageResponse {
129129 id: id.key().to_string(),
130130 username: id.key().to_string(),
131131 display_name: None,
132+ student_number: None,
132133 },
133134 None,
134135 ),
src/web/users.rsmodified+100 -14
@@ -20,7 +20,7 @@ use crate::domain::class_group::ClassGroupId;
2020 use crate::domain::preferences::{Language, PaletteColor, Theme};
2121 use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone, ProfileStats};
2222 use crate::domain::role::Role;
23-use crate::domain::user::{Password, User, UserId, Username};
23+use crate::domain::user::{Password, StudentNumber, User, UserId, Username};
2424 use crate::error::{AppError, ErrorResponse, ValidationError};
2525 use crate::service::parent_link::ensure_can_observe;
2626 use crate::state::AppState;
@@ -99,6 +99,13 @@ struct UpdateProfile {
9999 /// clear it (a school that lists no subjects stores none).
100100 #[schema(example = "Matematik", max_length = 50)]
101101 branch: Option<String>,
102+ /// The school-issued student number of the account being patched, unique
103+ /// inside the school. Only a `student` account may hold one — naming one
104+ /// for any other role, or naming a number another student already holds,
105+ /// is refused. Omit to keep the current value; send `""` (or whitespace)
106+ /// to clear it.
107+ #[schema(example = "1234", max_length = 32)]
108+ student_number: Option<String>,
102109 }
103110
104111 /// Partial UI-preference update. Same field semantics as [`UpdateProfile`]:
@@ -158,10 +165,47 @@ fn merge_branch(
158165 }
159166 }
160167
168+/// Resolve the `student_number` a request names. Same merge shape as
169+/// [`merge_field`] — absent (or `null`) is "keep", blank is an explicit
170+/// clear — plus the two checks a plain field does not carry:
171+///
172+/// * **The role gate.** A number names a student of this school, so only a
173+/// `student` row may receive one; naming one for any other role is a 400,
174+/// not a silent write the next role change would clear.
175+/// * **The shape**, through [`StudentNumber`]: non-blank after trimming and
176+/// within the published bound. Blank is a *clear* rather than a parse
177+/// failure, so whitespace can never become a stored number — the same
178+/// reading every other patchable field has.
179+///
180+/// `""` on a non-student stays a clear (a no-op: such a row never holds one),
181+/// and a value that collides with another student's is the unique index's
182+/// refusal — a 409 from the writer, never a pre-check that could race.
183+fn merge_student_number(
184+ patch: Option<&str>,
185+ role: Role,
186+) -> Result<Option<Option<StudentNumber>>, ValidationError> {
187+ match patch {
188+ None => Ok(None),
189+ Some(raw) if raw.trim().is_empty() => Ok(Some(None)),
190+ Some(raw) => {
191+ if role != Role::Student {
192+ return Err(StudentNumber::non_student_refusal());
193+ }
194+ Ok(Some(Some(StudentNumber::try_new(raw)?)))
195+ }
196+ }
197+}
198+
161199 /// Validate and persist exactly the info fields `req` carried — nothing is
162200 /// merged from `user`'s snapshot, so a concurrent PATCH of another field is not
163201 /// reverted. Shared by the self-service and admin profile endpoints — they
164202 /// differ only in whose row they load and who may call them.
203+///
204+/// `student_number` is resolved against the target's *live* role, read with the
205+/// row we hold — so the role gate cannot be raced by a role change landing in
206+/// between (a promotion that lands first makes this a 400; this write landing
207+/// first leaves nothing behind, because the role write clears the number in the
208+/// same statement).
165209 async fn apply_profile(
166210 user: User,
167211 req: &UpdateProfile,
@@ -176,6 +220,7 @@ async fn apply_profile(
176220 let birth_date = merge_field(req.birth_date.as_deref(), BirthDate::try_new)?;
177221 let display_name = merge_field(req.display_name.as_deref(), DisplayName::try_new)?;
178222 let bio = merge_field(req.bio.as_deref(), Bio::try_new)?;
223+ let student_number = merge_student_number(req.student_number.as_deref(), user.get_role())?;
179224 // Only a request that actually names a branch pays the settings read.
180225 let branch = match req.branch {
181226 Some(_) => {
@@ -195,6 +240,7 @@ async fn apply_profile(
195240 display_name,
196241 bio,
197242 branch,
243+ student_number,
198244 )
199245 .await?;
200246 Ok(UserResponse::new(&updated))
@@ -245,7 +291,7 @@ struct SearchUsers {
245291 /// student or parent naming a role they may not message is refused. Paged
246292 /// via `?limit=&offset=` like the other lists (omit `limit` for every
247293 /// match); returns a `{items, total, limit, offset}` envelope carrying only
248-/// id/username/display name — no contact details.
294+/// id/username/display name and the student number — no contact details.
249295 #[utoipa::path(
250296 get,
251297 path = "/search",
@@ -332,13 +378,21 @@ struct CreateUser {
332378 /// The role the account is born with. Omitted → `student`.
333379 #[schema(example = "teacher")]
334380 role: Option<String>,
381+ /// The school-issued student number, unique inside the school. Only a
382+ /// `student` account may hold one — naming one while creating any other
383+ /// role is a `400`, and a number another student already holds is a `409`.
384+ /// Omit to create the account unnumbered; blank is the same as omitted.
385+ #[schema(example = "1234", max_length = 32)]
386+ student_number: Option<String>,
335387 }
336388
337389 /// Create a school account directly — the school-office path for adding a
338390 /// student or a staff member with no self-registration and no invite. Admin
339391 /// only. `{username, password}` are required and `role` is optional (omitted →
340392 /// `student`); the row is born with its role rather than promoted into it, so
341-/// a new teacher is never briefly a student. The username is a global
393+/// a new teacher is never briefly a student. `student_number` numbers a new
394+/// student at mint time — a `409` when another student in this school already
395+/// holds it, a `400` on a non-student role. The username is a global
342396 /// **person** credential exactly as at `POST /auth/register`: a name new
343397 /// everywhere creates the person and this school's `app_user`, while a person
344398 /// who already exists is attached to this school only when the password
@@ -353,10 +407,10 @@ struct CreateUser {
353407 request_body = CreateUser,
354408 responses(
355409 (status = 201, description = "Account created, holding the requested role", body = UserResponse),
356- (status = 400, description = "Invalid username or password (a reserved username included), or an unknown role", body = ErrorResponse),
410+ (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),
357411 (status = 401, description = "Not authenticated", body = ErrorResponse),
358412 (status = 403, description = "Requires admin role", body = ErrorResponse),
359- (status = 409, description = "The username is taken in this school, or that person exists under a different password", body = ErrorResponse),
413+ (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),
360414 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
361415 ),
362416 )]
@@ -381,6 +435,10 @@ async fn create_user(
381435 Some(raw) => Role::try_from_str(raw)?,
382436 None => Role::Student,
383437 };
438+ // The number is validated against the role the row is being born with
439+ // (the same gate the profile writer applies), then bound into the mint —
440+ // one statement, so a refused number leaves no half-created account.
441+ let student_number = merge_student_number(req.student_number.as_deref(), role)?.flatten();
384442 let password = Password::try_new(&req.password)?;
385443 let password_hash = password.hash_async().await?;
386444
@@ -399,10 +457,16 @@ async fn create_user(
399457
400458 // School half, born with its role: a fresh row holds no enrollments or
401459 // teaching assignments for a later promotion to sweep. A username already
402- // taken in this school refuses here, before the membership is written.
403- let user =
404- crate::service::user::create_with_role(&st.db, username, Some(*person.get_id()), role)
405- .await?;
460+ // taken in this school refuses here, before the membership is written, and
461+ // so does a student number another student already holds.
462+ let user = crate::service::user::create_with_role(
463+ &st.db,
464+ username,
465+ Some(*person.get_id()),
466+ role,
467+ student_number,
468+ )
469+ .await?;
406470 crate::service::person::link_school(control, person.get_id(), &slug).await?;
407471 Ok((StatusCode::CREATED, Json(UserResponse::new(&user))))
408472 }
@@ -411,7 +475,10 @@ async fn create_user(
411475 /// date, plus the public-profile pair `display_name` and `bio` (both readable
412476 /// school-wide at `GET /users/{id}/profile`, unlike the contact fields). Any
413477 /// authenticated role. Omitted fields stay as they are; an empty string clears
414-/// a field.
478+/// a field. `student_number` follows the same merge semantics, with two
479+/// refusals of its own: naming one while the account is not a `student` is a
480+/// `400`, and a number another student in this school already holds is a `409`
481+/// (`code: student_number_taken`).
415482 #[utoipa::path(
416483 patch,
417484 path = "/me",
@@ -420,8 +487,9 @@ async fn create_user(
420487 request_body = UpdateProfile,
421488 responses(
422489 (status = 200, description = "Updated user", body = UserResponse),
423- (status = 400, description = "Invalid field", body = ErrorResponse),
490+ (status = 400, description = "Invalid field, or a student number on a non-student account", body = ErrorResponse),
424491 (status = 401, description = "Not authenticated", body = ErrorResponse),
492+ (status = 409, description = "The student number is already taken (`code: student_number_taken`)", body = ErrorResponse),
425493 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
426494 ),
427495 )]
@@ -487,7 +555,13 @@ async fn get_user(
487555
488556 /// Update any user's personal info. Admin only — the school-office path for
489557 /// maintaining records on behalf of students and staff. Same field semantics
490-/// as `PATCH /users/me`.
558+/// as `PATCH /users/me`, `student_number` included: the number belongs to the
559+/// student identity the office maintains, so this is the door that issues it —
560+/// a `400` when the target is not a `student`, a `409`
561+/// (`code: student_number_taken`) when another student in this school already
562+/// holds it. A role change away from `student` clears it on its own
563+/// (`PATCH /users/{id}/role`), which is also the answer to "this account is no
564+/// longer a student".
491565 #[utoipa::path(
492566 patch,
493567 path = "/{id}/profile",
@@ -497,10 +571,11 @@ async fn get_user(
497571 request_body = UpdateProfile,
498572 responses(
499573 (status = 200, description = "Updated user", body = UserResponse),
500- (status = 400, description = "Invalid field", body = ErrorResponse),
574+ (status = 400, description = "Invalid field, or a student number on a non-student account", body = ErrorResponse),
501575 (status = 401, description = "Not authenticated", body = ErrorResponse),
502576 (status = 403, description = "Requires admin role", body = ErrorResponse),
503577 (status = 404, description = "User not found", body = ErrorResponse),
578+ (status = 409, description = "The student number is already taken (`code: student_number_taken`)", body = ErrorResponse),
504579 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
505580 ),
506581 )]
@@ -555,7 +630,10 @@ async fn update_user_preferences(
555630 /// A school that has already lost its admins is recovered by hand against the
556631 /// database, since the seed never promotes.
557632 /// Setting any non-`student` role also drops the user's course enrollments —
558-/// only students enroll, so a promoted user leaves every roster. Demoting below
633+/// only students enroll, so a promoted user leaves every roster — and clears
634+/// the account's student number in the same transaction: the number names a
635+/// student of this school, so no window exists where a promoted account still
636+/// holds one. Demoting below
559637 /// `teacher` drops their course teaching assignments for the mirror reason, and
560638 /// withdraws their published appointment slots, cancelling the live bookings on
561639 /// them: nothing could reach either afterwards — a slot is listed only on its
@@ -827,6 +905,14 @@ async fn my_students(
827905 // and the counters that motivate. Deliberately *not* `UserResponse` — that one
828906 // carries email, phone, and birth date, which keep exactly the gate they have
829907 // today (self, teacher+, admin). Nothing here widens where they are reachable.
908+//
909+// The student number is deliberately on `UserResponse` (and `PersonRef`) and
910+// *not* here: it is the school office's identifier for a student, readable
911+// wherever the reader is already looking at student identity — the admin user
912+// surfaces, the pickers, a parent's own children's roster — while this profile
913+// is readable by every authenticated account school-wide. A number is not a
914+// secret, but broadcasting one to the whole school is a widening nobody asked
915+// for.
830916
831917 /// A user's public profile. Contact details are not part of it, at any role.
832918 #[derive(Serialize, ToSchema)]
tests/integration.rsmodified+401 -0
@@ -5213,6 +5213,156 @@ async fn admin_creates_a_user() {
52135213 );
52145214 }
52155215
5216+/// `student_number` on the mint: a student may be born with one (stored
5217+/// trimmed), a duplicate in the same school is the partial unique index's
5218+/// refusal — a 409 carrying the `student_number_taken` code — and any
5219+/// non-student role refuses the field outright.
5220+#[tokio::test]
5221+async fn student_numbers_are_minted_uniquely_and_only_for_students() {
5222+ let (app, db) = app_and_db().await;
5223+ let admin = login_as(&app, &db, "boss", "admin").await;
5224+
5225+ // The number is stored trimmed, exactly like a username: the unique index
5226+ // keys on the stored string, so padding must not mint a second number.
5227+ let created = send(
5228+ &app,
5229+ "POST",
5230+ "/users",
5231+ Some(&admin),
5232+ Some(json!({
5233+ "username": "numarali",
5234+ "password": "secret1",
5235+ "student_number": " 1234 ",
5236+ })),
5237+ )
5238+ .await;
5239+ assert_eq!(created.status, StatusCode::CREATED, "{}", created.body);
5240+ assert_eq!(created.body["student_number"], "1234", "{}", created.body);
5241+ let numbered_id = id_of(&created.body);
5242+
5243+ // Read back off the row, not off the create echo.
5244+ let one = send(
5245+ &app,
5246+ "GET",
5247+ &format!("/users/{numbered_id}"),
5248+ Some(&admin),
5249+ None,
5250+ )
5251+ .await;
5252+ assert_eq!(one.body["student_number"], "1234");
5253+
5254+ // A second student claiming the same number — padded or not — is the
5255+ // index's refusal, and the body names the cause for a client that
5256+ // branches on it.
5257+ for duplicate in ["1234", "1234 "] {
5258+ let res = send(
5259+ &app,
5260+ "POST",
5261+ "/users",
5262+ Some(&admin),
5263+ Some(json!({
5264+ "username": "kopyaci",
5265+ "password": "secret1",
5266+ "student_number": duplicate,
5267+ })),
5268+ )
5269+ .await;
5270+ assert_eq!(
5271+ res.status,
5272+ StatusCode::CONFLICT,
5273+ "{duplicate}: {}",
5274+ res.body
5275+ );
5276+ assert_eq!(res.body["error"], "student number already taken");
5277+ assert_eq!(res.body["code"], "student_number_taken");
5278+ }
5279+ // The refused mint wrote nothing: the username is still free.
5280+ let retry = send(
5281+ &app,
5282+ "POST",
5283+ "/users",
5284+ Some(&admin),
5285+ Some(json!({ "username": "kopyaci", "password": "secret1" })),
5286+ )
5287+ .await;
5288+ assert_eq!(retry.status, StatusCode::CREATED, "{}", retry.body);
5289+ assert!(
5290+ retry.body["student_number"].is_null(),
5291+ "an omitted number is null: {}",
5292+ retry.body
5293+ );
5294+
5295+ // A non-student role may not be born with a number — refused before
5296+ // anything is written, so the username stays free too.
5297+ assert_eq!(
5298+ send(
5299+ &app,
5300+ "POST",
5301+ "/users",
5302+ Some(&admin),
5303+ Some(json!({
5304+ "username": "hoca",
5305+ "password": "secret1",
5306+ "role": "teacher",
5307+ "student_number": "5678",
5308+ })),
5309+ )
5310+ .await
5311+ .status,
5312+ StatusCode::BAD_REQUEST
5313+ );
5314+ assert_eq!(
5315+ send(
5316+ &app,
5317+ "POST",
5318+ "/users",
5319+ Some(&admin),
5320+ Some(json!({ "username": "hoca", "password": "secret1", "role": "teacher" })),
5321+ )
5322+ .await
5323+ .status,
5324+ StatusCode::CREATED
5325+ );
5326+
5327+ // Bound: 32 characters fit, 33 do not.
5328+ assert_eq!(
5329+ send(
5330+ &app,
5331+ "POST",
5332+ "/users",
5333+ Some(&admin),
5334+ Some(json!({
5335+ "username": "uzun",
5336+ "password": "secret1",
5337+ "student_number": "9".repeat(33),
5338+ })),
5339+ )
5340+ .await
5341+ .status,
5342+ StatusCode::BAD_REQUEST
5343+ );
5344+
5345+ // Blank is the same as omitted, never a stored empty string.
5346+ let blank = send(
5347+ &app,
5348+ "POST",
5349+ "/users",
5350+ Some(&admin),
5351+ Some(json!({
5352+ "username": "bosluk",
5353+ "password": "secret1",
5354+ "student_number": " ",
5355+ })),
5356+ )
5357+ .await;
5358+ assert_eq!(blank.status, StatusCode::CREATED, "{}", blank.body);
5359+ assert!(
5360+ blank.body["student_number"].is_null(),
5361+ "whitespace is absent, not a number: {}",
5362+ blank.body
5363+ );
5364+}
5365+
52165366 /// The AI service principal must never be mintable, storable, or filterable
52175367 /// over HTTP: it is the QUIC bridge's own identity, not an account anybody can
52185368 /// 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() {
55385688 );
55395689 }
55405690
5691+/// `student_number` through the profile doors: the office numbers a student,
5692+/// the number rides every surface that shows student identity, a duplicate is
5693+/// a coded 409, blank clears (on any role — a clear is not a set), only a
5694+/// student may hold one, and a role change away from `student` clears it.
5695+#[tokio::test]
5696+async fn student_number_patches_follow_the_student_role() {
5697+ let (app, db) = app_and_db().await;
5698+ let admin = login_as(&app, &db, "boss", "admin").await;
5699+ let alice = login(&app, "alice").await;
5700+ let alice_id = me_id(&app, &alice).await;
5701+ let bob = login(&app, "bob").await;
5702+ let bob_id = me_id(&app, &bob).await;
5703+
5704+ // The office numbers alice.
5705+ let res = send(
5706+ &app,
5707+ "PATCH",
5708+ &format!("/users/{alice_id}/profile"),
5709+ Some(&admin),
5710+ Some(json!({ "student_number": " 9-B/17 " })),
5711+ )
5712+ .await;
5713+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
5714+ assert_eq!(res.body["student_number"], "9-B/17", "stored trimmed");
5715+
5716+ // Every reader that shows student identity carries it: the admin's single
5717+ // read, the admin listing, the picker ref, and alice's own session.
5718+ let one = send(
5719+ &app,
5720+ "GET",
5721+ &format!("/users/{alice_id}"),
5722+ Some(&admin),
5723+ None,
5724+ )
5725+ .await;
5726+ assert_eq!(one.body["student_number"], "9-B/17");
5727+ let list = send(&app, "GET", "/users", Some(&admin), None).await;
5728+ let listed = common::items(&list.body)
5729+ .iter()
5730+ .find(|u| u["username"] == "alice")
5731+ .expect("alice listed")
5732+ .clone();
5733+ assert_eq!(listed["student_number"], "9-B/17");
5734+ let search = send(
5735+ &app,
5736+ "GET",
5737+ "/users/search?q=alice&role=student",
5738+ Some(&admin),
5739+ None,
5740+ )
5741+ .await;
5742+ let found = common::items(&search.body)
5743+ .iter()
5744+ .find(|u| u["username"] == "alice")
5745+ .expect("alice found")
5746+ .clone();
5747+ assert_eq!(found["student_number"], "9-B/17");
5748+ let me = send(&app, "GET", "/auth/me", Some(&alice), None).await;
5749+ assert_eq!(me.body["student_number"], "9-B/17");
5750+
5751+ // A student owns the number on their own row: the self door takes it too,
5752+ // under the same rules. An unrelated patch leaves it standing.
5753+ let res = send(
5754+ &app,
5755+ "PATCH",
5756+ "/users/me",
5757+ Some(&alice),
5758+ Some(json!({ "student_number": "9-B/18" })),
5759+ )
5760+ .await;
5761+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
5762+ assert_eq!(res.body["student_number"], "9-B/18");
5763+ let res = send(
5764+ &app,
5765+ "PATCH",
5766+ "/users/me",
5767+ Some(&alice),
5768+ Some(json!({ "name": "Alice" })),
5769+ )
5770+ .await;
5771+ assert_eq!(res.body["student_number"], "9-B/18", "omitted = untouched");
5772+
5773+ // Bound: 33 characters are refused through this door too.
5774+ assert_eq!(
5775+ send(
5776+ &app,
5777+ "PATCH",
5778+ "/users/me",
5779+ Some(&alice),
5780+ Some(json!({ "student_number": "9".repeat(33) })),
5781+ )
5782+ .await
5783+ .status,
5784+ StatusCode::BAD_REQUEST
5785+ );
5786+
5787+ // bob takes one of his own; alice claiming it is the index's refusal, and
5788+ // the refused patch left her number exactly as it stood.
5789+ assert_eq!(
5790+ send(
5791+ &app,
5792+ "PATCH",
5793+ &format!("/users/{bob_id}/profile"),
5794+ Some(&admin),
5795+ Some(json!({ "student_number": "1234" })),
5796+ )
5797+ .await
5798+ .status,
5799+ StatusCode::OK
5800+ );
5801+ let clash = send(
5802+ &app,
5803+ "PATCH",
5804+ &format!("/users/{alice_id}/profile"),
5805+ Some(&admin),
5806+ Some(json!({ "student_number": "1234" })),
5807+ )
5808+ .await;
5809+ assert_eq!(clash.status, StatusCode::CONFLICT, "{}", clash.body);
5810+ assert_eq!(clash.body["error"], "student number already taken");
5811+ assert_eq!(clash.body["code"], "student_number_taken");
5812+ let one = send(
5813+ &app,
5814+ "GET",
5815+ &format!("/users/{alice_id}"),
5816+ Some(&admin),
5817+ None,
5818+ )
5819+ .await;
5820+ assert_eq!(one.body["student_number"], "9-B/18");
5821+
5822+ // Only students hold one. A teacher target refuses a value outright...
5823+ let teacher = send(
5824+ &app,
5825+ "POST",
5826+ "/users",
5827+ Some(&admin),
5828+ Some(json!({ "username": "hoca", "password": "secret1", "role": "teacher" })),
5829+ )
5830+ .await;
5831+ assert_eq!(teacher.status, StatusCode::CREATED, "{}", teacher.body);
5832+ let teacher_id = id_of(&teacher.body);
5833+ let refused = send(
5834+ &app,
5835+ "PATCH",
5836+ &format!("/users/{teacher_id}/profile"),
5837+ Some(&admin),
5838+ Some(json!({ "student_number": "5678" })),
5839+ )
5840+ .await;
5841+ assert_eq!(refused.status, StatusCode::BAD_REQUEST, "{}", refused.body);
5842+ assert_eq!(
5843+ refused.body["error"],
5844+ "student_number: only a student account may hold a student number"
5845+ );
5846+ // ...and so does the admin's own row through the self door.
5847+ assert_eq!(
5848+ send(
5849+ &app,
5850+ "PATCH",
5851+ "/users/me",
5852+ Some(&admin),
5853+ Some(json!({ "student_number": "9999" })),
5854+ )
5855+ .await
5856+ .status,
5857+ StatusCode::BAD_REQUEST
5858+ );
5859+ // A *clear* is not a set: blank on a non-student is the same no-op the
5860+ // omitted field is, never a refusal.
5861+ assert_eq!(
5862+ send(
5863+ &app,
5864+ "PATCH",
5865+ "/users/me",
5866+ Some(&admin),
5867+ Some(json!({ "student_number": "" })),
5868+ )
5869+ .await
5870+ .status,
5871+ StatusCode::OK
5872+ );
5873+
5874+ // Blank (and whitespace) clears a student's number rather than storing an
5875+ // empty string.
5876+ let cleared = send(
5877+ &app,
5878+ "PATCH",
5879+ "/users/me",
5880+ Some(&alice),
5881+ Some(json!({ "student_number": " " })),
5882+ )
5883+ .await;
5884+ assert_eq!(cleared.status, StatusCode::OK, "{}", cleared.body);
5885+ assert!(cleared.body["student_number"].is_null(), "{}", cleared.body);
5886+
5887+ // The role cascade is the other half of the rule: a promotion out of
5888+ // `student` clears the number in the same transaction, and a later
5889+ // demotion back to `student` does not restore it — the number is set, not
5890+ // remembered.
5891+ assert_eq!(
5892+ send(
5893+ &app,
5894+ "PATCH",
5895+ &format!("/users/{alice_id}/profile"),
5896+ Some(&admin),
5897+ Some(json!({ "student_number": "9-B/17" })),
5898+ )
5899+ .await
5900+ .status,
5901+ StatusCode::OK
5902+ );
5903+ let promoted = send(
5904+ &app,
5905+ "PATCH",
5906+ &format!("/users/{alice_id}/role"),
5907+ Some(&admin),
5908+ Some(json!({ "role": "teacher" })),
5909+ )
5910+ .await;
5911+ assert_eq!(promoted.status, StatusCode::OK, "{}", promoted.body);
5912+ assert!(
5913+ promoted.body["student_number"].is_null(),
5914+ "the promotion clears the number: {}",
5915+ promoted.body
5916+ );
5917+ let one = send(
5918+ &app,
5919+ "GET",
5920+ &format!("/users/{alice_id}"),
5921+ Some(&admin),
5922+ None,
5923+ )
5924+ .await;
5925+ assert!(one.body["student_number"].is_null(), "{}", one.body);
5926+ let demoted = send(
5927+ &app,
5928+ "PATCH",
5929+ &format!("/users/{alice_id}/role"),
5930+ Some(&admin),
5931+ Some(json!({ "role": "student" })),
5932+ )
5933+ .await;
5934+ assert_eq!(demoted.status, StatusCode::OK, "{}", demoted.body);
5935+ assert!(
5936+ demoted.body["student_number"].is_null(),
5937+ "a role change to student leaves it unset: {}",
5938+ demoted.body
5939+ );
5940+}
5941+
55415942 // --- users: UI preferences (theme, language, palette color) ------------------------------
55425943
55435944 #[tokio::test]
tests/spec_bounds.rsmodified+12 -0
@@ -244,6 +244,12 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> {
244244 "maxLength",
245245 MAX_PASSWORD_LEN as i64,
246246 ),
247+ (
248+ "CreateUser",
249+ "student_number",
250+ "maxLength",
251+ MAX_STUDENT_NUMBER_LEN as i64,
252+ ),
247253 ("SelectSchool", "school", "minLength", MIN_SLUG_LEN as i64),
248254 ("SelectSchool", "school", "maxLength", MAX_SLUG_LEN as i64),
249255 ("UpdateProfile", "name", "maxLength", MAX_NAME_LEN as i64),
@@ -264,6 +270,12 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> {
264270 "maxLength",
265271 MAX_SETTINGS_ITEM_LEN as i64,
266272 ),
273+ (
274+ "UpdateProfile",
275+ "student_number",
276+ "maxLength",
277+ MAX_STUDENT_NUMBER_LEN as i64,
278+ ),
267279 (
268280 "CreateNote",
269281 "title",