forge
Explore
Log in

Don't you dare go Hollow

Read-only parent role with student ties

Browse files at this commit

ec44315e8f21d0cdfe6654a9d91249a4f3ccb474Ahmet Kaan GümüşParent: c996ce4
  • feat
    • read-only parent role with student ties
Show full message
✨ feat(users): read-only parent role with student ties

Parent sits below student in the hierarchy: clears no staff bar and
fails every exact student gate, so it can only observe. Admins tie
students to a parent under /users/{id}/students; the tie alone opens
the student's marks/attendance/pomodoro reports (full, unnarrowed)
plus the parent's own /users/me/students list. A role change off
either end of a tie sweeps it, mirroring the enrollment sweep.
README.mdmodified+33 -12
@@ -2,8 +2,10 @@
22
33 Note, attendance, course + weighted exam mark backend. **Rust (edition 2024) · axum · SurrealDB 3 (embedded surrealkv) · tokio.**
44
5-Session-cookie auth with four hierarchical roles (`student < teacher < manager
6-< admin`). Notes are per-user and carry **file attachments** (PDFs, documents,
5+Session-cookie auth with five hierarchical roles (`parent < student < teacher
6+< manager < admin`). A **`parent`** observes and changes nothing: admins tie
7+students to a parent account, and the parent reads those students' mark,
8+attendance, and pomodoro reports — that's the whole role. Notes are per-user and carry **file attachments** (PDFs, documents,
79 …): blobs live on disk next to the database, metadata in the database, and the
810 per-file size cap is school policy in settings (`max_file_bytes`, default
911 5 MiB). Attendance is event + attendees: create an event with an **audience**
@@ -176,10 +178,10 @@ cross-origin must therefore be allowlisted explicitly.
176178
177179 ## Roles & access control
178180
179-Every user has one of four roles, ranked lowest to highest:
181+Every user has one of five roles, ranked lowest to highest:
180182
181183 ```
182-student < teacher < manager < admin
184+parent < student < teacher < manager < admin
183185 ```
184186
185187 The check is **hierarchical** — a higher role satisfies any lower requirement
@@ -187,6 +189,17 @@ The check is **hierarchical** — a higher role satisfies any lower requirement
187189 `student`; a role read is re-checked on every request, so a role change takes
188190 effect on the user's very next call (no re-login).
189191
192+`parent` is the read-only observer at the bottom of the ladder: an admin ties
193+any number of students to a parent account (`POST /users/{id}/students`), and
194+the tie is the parent's whole power — they list their students
195+(`GET /users/me/students`) and read each one's mark, attendance, and pomodoro
196+reports in full. Student-only checks are exact (`role == student`), so a
197+parent can never enroll, sit an exam, be graded, or land on a roll call; and
198+sitting below every staff bar, they can't touch anything else either. A role
199+change off either end of a tie (the parent stops being a `parent`, the
200+student stops being a `student`) drops the tie, exactly like promotion drops
201+course enrollments.
202+
190203 | Action | Minimum role | Notes |
191204 |------------------------------------------|--------------|-----------------------------------------------|
192205 | Register / login / view own account | (any) | Registration always creates a `student` |
@@ -204,9 +217,9 @@ effect on the user's very next call (no re-login).
204217 | Work check-in / check-out; view **own** work log | teacher | Instants are server-stamped, never client-supplied |
205218 | View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries |
206219 | Start / finish a pomodoro focus session; view **own** pomodoro log | student | **Students only** start; instants server-stamped; starting discards a dangling unfinished session |
207-| View **any** user's pomodoro log | teacher | Study oversight — same shape as `/pomodoro/me`, incl. the unpaged `total_focus_ms` |
220+| View **any** user's pomodoro log | teacher | Study oversight — same shape as `/pomodoro/me`, incl. the unpaged `total_focus_ms`; a `parent` reads their linked students' |
208221 | Read **own** attendance report | student | |
209-| Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all |
222+| Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full |
210223 | View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created; `manager`+: all); exam **drafts** show only to the course's managers |
211224 | Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | **Students only** — staff never sit; must be enrolled; window (where one exists) and `max_attempts` enforced by the server |
212225 | Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off |
@@ -216,13 +229,14 @@ effect on the user's very next call (no re-login).
216229 | Create courses | teacher | The creator manages the course |
217230 | Manage inside a course: edit/delete it, enroll/unenroll **students**, add/edit/delete its exams and **subjects**, grade, remove results | teacher | Only the **course creator**, or a `manager`+ for any course; only students can be enrolled; a subject still referenced by exam questions won't delete (`409`) |
218231 | View a course's roster, an exam's result list / statistics | teacher | Course-management rights |
219-| Read another user's mark report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all |
232+| Read another user's mark report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full |
220233 | Grade students | teacher | Target must be an **enrolled student**; grading never targets oneself |
221234 | Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields |
222235 | Edit **own** UI preferences (theme, language) | student | `null` until chosen — the client then follows the device preference |
236+| List **own** linked students | parent | Read-only: the list plus each student's mark/attendance/pomodoro reports — a parent changes nothing, anywhere |
223237 | Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar |
224238 | Edit school settings; create / edit / delete terms | manager | School policy (exam kinds, attendance statuses, grade bands, the note-file size limit) and the academic calendar are management's call |
225-| List users; look up one user; change a user's role; edit **any** user's personal info or UI preferences | admin | An admin cannot change **their own** role |
239+| List users; look up one user; change a user's role; edit **any** user's personal info or UI preferences; tie/untie students to a `parent` account | admin | An admin cannot change **their own** role |
226240
227241 ### Bootstrapping the first admin
228242
@@ -304,12 +318,16 @@ their existing shapes: the student exam-room reads
304318 | GET | `/auth/me` | student | Current user (incl. `role` and personal info) |
305319 | PATCH | `/users/me` | student | Update own personal info (see below) |
306320 | PATCH | `/users/me/preferences` | student | `{theme?, language?}` — own UI preferences (see below) |
321+| GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) · paged |
307322 | GET | `/users/search` | teacher | `?q=<fragment>&role=<role?>` — find users by username/name fragment (pickers); refs only, no contact info · paged |
308323 | GET | `/users` | admin | List all users · paged |
309324 | GET | `/users/{id}` | admin | Get one user |
310325 | PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll) |
311326 | PATCH | `/users/{id}/profile` | admin | Update any user's personal info |
312327 | PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |
328+| POST | `/users/{id}/students` | admin | `{user_id}` — tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant |
329+| GET | `/users/{id}/students` | admin | List a parent's linked students · paged |
330+| DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent (student data untouched) |
313331 | POST | `/notes` | student | `{title, content?}` |
314332 | GET | `/notes` | student | List own notes · paged |
315333 | GET | `/notes/{id}` | student | Get own note |
@@ -383,7 +401,7 @@ their existing shapes: the student exam-room reads
383401 | GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster × latest attempts × marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager) |
384402 | GET | `/exams/{id}/live/stream` | teacher | The same snapshot as SSE `snapshot` events every ~2s (course manager) |
385403 | GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) |
386-| GET | `/marks/{user}` | teacher | A user's mark report, narrowed to the caller's courses (manager+: full) |
404+| GET | `/marks/{user}` | teacher* | A user's mark report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` — full |
387405 | POST | `/work/check-in` | teacher | Open a work stint (server-stamped; `409` if already open) |
388406 | POST | `/work/check-out` | teacher | Close the open stint (`409` if none open) |
389407 | GET | `/work/me` | teacher | Own work log, newest first (open stint has `check_out: null`) · paged |
@@ -393,9 +411,9 @@ their existing shapes: the student exam-room reads
393411 | POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** — a dangling unfinished session is discarded and replaced) |
394412 | POST | `/pomodoro/finish` | student | Close the running session (`409` if none running) |
395413 | GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` · paged |
396-| GET | `/pomodoro/{user}` | teacher | A user's pomodoro log, same shape · paged |
414+| GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape · paged; *or a `parent` linked to `{user}` |
397415 | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |
398-| GET | `/attendance/{user}` | teacher | A user's attendance report, narrowed to the caller's courses (manager+: full) |
416+| GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` — full |
399417 | GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes` |
400418 | PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other (see "Per-school policy") |
401419 | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) |
@@ -415,7 +433,10 @@ kind was later removed from settings counts with weight `1`.
415433 A course may carry a `term_id` (`null` = unassigned); on `PATCH
416434 /courses/{id}`, an omitted `term_id` keeps the link and an explicit `null`
417435 clears it.
418-`role` ∈ `student | teacher | manager | admin`. Ids in responses are ULIDs.
436+`role` ∈ `parent | student | teacher | manager | admin`. Ids in responses are
437+ULIDs. `parent` accounts are made by an admin (register as `student`, then
438+`PATCH /users/{id}/role`) and observe only the students an admin tied to them
439+— see "Roles & access control".
419440 An exam `mark` is an integer `0`–`100`; it lives in its own `exam_result` row,
420441 never in a `note`. Students never grade anyone — grading is teacher+ with
421442 course-management rights, and the target must be enrolled in the exam's course;
src/database.rsmodified+9 -0
@@ -23,6 +23,7 @@ pub const QUESTION_IMAGE_TABLE: &str = "question_image";
2323 pub const EXAM_ANSWER_TABLE: &str = "exam_answer";
2424 pub const COURSE_TABLE: &str = "course";
2525 pub const ENROLLMENT_TABLE: &str = "enrollment";
26+pub const PARENT_LINK_TABLE: &str = "parent_link";
2627 pub const COURSE_SESSION_TABLE: &str = "course_session";
2728 pub const SESSION_ATTENDANCE_TABLE: &str = "session_attendance";
2829 pub const WORK_ENTRY_TABLE: &str = "work_entry";
@@ -127,6 +128,14 @@ const MIGRATION: &str = "
127128 DEFINE INDEX IF NOT EXISTS enrollment_course_user ON enrollment FIELDS course, user UNIQUE;
128129 DEFINE INDEX IF NOT EXISTS enrollment_user ON enrollment FIELDS user;
129130
131+ DEFINE TABLE IF NOT EXISTS parent_link SCHEMAFULL;
132+ DEFINE FIELD IF NOT EXISTS parent ON parent_link TYPE record<user>;
133+ DEFINE FIELD IF NOT EXISTS student ON parent_link TYPE record<user>;
134+ DEFINE FIELD IF NOT EXISTS linked_by ON parent_link TYPE record<user>;
135+ DEFINE INDEX IF NOT EXISTS parent_link_parent_student ON parent_link FIELDS parent, student UNIQUE;
136+ DEFINE INDEX IF NOT EXISTS parent_link_parent ON parent_link FIELDS parent;
137+ DEFINE INDEX IF NOT EXISTS parent_link_student ON parent_link FIELDS student;
138+
130139 DEFINE TABLE IF NOT EXISTS course_session SCHEMAFULL;
131140 DEFINE FIELD IF NOT EXISTS course ON course_session TYPE record<course>;
132141 DEFINE FIELD IF NOT EXISTS teacher ON course_session TYPE record<user>;
src/domain/mod.rsmodified+1 -0
@@ -14,6 +14,7 @@ pub mod exam_question;
1414 pub mod exam_result;
1515 pub mod note;
1616 pub mod note_file;
17+pub mod parent_link;
1718 pub mod pomodoro;
1819 pub mod preferences;
1920 pub mod profile;
src/domain/parent_link.rsadded+140 -0
@@ -0,0 +1,140 @@
1+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2+
3+use crate::database::{Database, PARENT_LINK_TABLE};
4+use crate::domain::user::UserId;
5+use crate::error::AppError;
6+
7+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
8+pub struct ParentLinkId(RecordId);
9+
10+impl ParentLinkId {
11+ /// A deterministic id for the (parent, student) pair — same trick as
12+ /// `EnrollmentId`: the same pair always maps to the same record id, so
13+ /// linking is a single atomic UPSERT with no find-then-insert race and
14+ /// one-row-per-pair by construction.
15+ pub fn composite(parent: &UserId, student: &UserId) -> Self {
16+ Self(RecordId::new(
17+ PARENT_LINK_TABLE,
18+ format!("{}_{}", parent.key(), student.key()),
19+ ))
20+ }
21+
22+ pub fn record(&self) -> RecordId {
23+ self.0.clone()
24+ }
25+
26+ pub fn key(&self) -> &str {
27+ match &self.0.key {
28+ RecordIdKey::String(key) => key,
29+ _ => "",
30+ }
31+ }
32+}
33+
34+/// A parent account's tie to one student it may observe. Purely a read grant:
35+/// it gates the parent's access to the student's reports (marks, attendance,
36+/// pomodoro) and nothing else — a parent never writes through it.
37+#[derive(Debug, Clone, SurrealValue)]
38+pub struct ParentLink {
39+ id: ParentLinkId,
40+ parent: UserId,
41+ student: UserId,
42+ linked_by: UserId,
43+}
44+
45+impl ParentLink {
46+ pub fn get_id(&self) -> &ParentLinkId {
47+ &self.id
48+ }
49+
50+ pub fn get_parent(&self) -> &UserId {
51+ &self.parent
52+ }
53+
54+ pub fn get_student(&self) -> &UserId {
55+ &self.student
56+ }
57+
58+ pub fn get_linked_by(&self) -> &UserId {
59+ &self.linked_by
60+ }
61+
62+ /// Tie (idempotently) `student` to `parent`. One row per pair, keyed by the
63+ /// deterministic composite id, so concurrent links converge on one row. The
64+ /// caller validates the roles — this only stores the pair.
65+ pub async fn link(
66+ parent: &UserId,
67+ student: &UserId,
68+ linked_by: &UserId,
69+ db: &Database,
70+ ) -> Result<ParentLink, AppError> {
71+ let link = ParentLink {
72+ id: ParentLinkId::composite(parent, student),
73+ parent: parent.clone(),
74+ student: student.clone(),
75+ linked_by: linked_by.clone(),
76+ };
77+ let saved: Option<ParentLink> = db.upsert(link.id.record()).content(link).await?;
78+ saved.ok_or_else(|| AppError::Internal("failed to link student to parent".into()))
79+ }
80+
81+ /// True iff `parent` holds a link to `student` — the observation gate.
82+ pub async fn exists(
83+ parent: &UserId,
84+ student: &UserId,
85+ db: &Database,
86+ ) -> Result<bool, AppError> {
87+ let found: Option<ParentLink> = db
88+ .select(ParentLinkId::composite(parent, student).record())
89+ .await?;
90+ Ok(found.is_some())
91+ }
92+
93+ /// Every student `parent` observes, newest link first.
94+ pub async fn list_for_parent(
95+ parent: &UserId,
96+ db: &Database,
97+ ) -> Result<Vec<ParentLink>, AppError> {
98+ let mut result = db
99+ .query("SELECT * FROM parent_link WHERE parent = $parent ORDER BY id DESC")
100+ .bind(("parent", parent.record()))
101+ .await?
102+ .check()?;
103+ Ok(result.take::<Vec<ParentLink>>(0)?)
104+ }
105+
106+ pub async fn remove(
107+ parent: &UserId,
108+ student: &UserId,
109+ db: &Database,
110+ ) -> Result<Option<ParentLink>, AppError> {
111+ let mut result = db
112+ .query("DELETE parent_link WHERE parent = $parent AND student = $student RETURN BEFORE")
113+ .bind(("parent", parent.record()))
114+ .bind(("student", student.record()))
115+ .await?
116+ .check()?;
117+ Ok(result.take::<Vec<ParentLink>>(0)?.into_iter().next())
118+ }
119+
120+ /// Drop every link where `user` is the observed student — called when a
121+ /// role change takes the student side out of the `student` role, mirroring
122+ /// the enrollment sweep.
123+ pub async fn delete_where_student(user: &UserId, db: &Database) -> Result<(), AppError> {
124+ db.query("DELETE parent_link WHERE student = $usr")
125+ .bind(("usr", user.record()))
126+ .await?
127+ .check()?;
128+ Ok(())
129+ }
130+
131+ /// Drop every link where `user` is the observing parent — called when a
132+ /// role change takes the parent side out of the `parent` role.
133+ pub async fn delete_where_parent(user: &UserId, db: &Database) -> Result<(), AppError> {
134+ db.query("DELETE parent_link WHERE parent = $usr")
135+ .bind(("usr", user.record()))
136+ .await?
137+ .check()?;
138+ Ok(())
139+ }
140+}
src/domain/role.rsmodified+26 -3
@@ -2,12 +2,17 @@ use surrealdb::types::SurrealValue;
22
33 use crate::error::ValidationError;
44
5-/// The four access levels, in ascending order of privilege.
5+/// The five access levels, in ascending order of privilege.
66 ///
77 /// The variants are declared low-to-high, so the derived `Ord` matches the
88 /// hierarchy: `Role::Admin > Role::Teacher`. That ordering is exactly what
99 /// [`Role::at_least`] relies on — a higher role satisfies any lower requirement.
1010 ///
11+/// `Parent` sits at the bottom: a read-only observer of the students linked to
12+/// it (see `domain::parent_link`). It clears no `at_least` bar and fails every
13+/// exact `== Student` gate, so parents can't sit exams, enroll, or be marked on
14+/// a roll call — they only read their own students' reports.
15+///
1116 /// `#[surreal(untagged, rename_all = "lowercase")]` makes each variant serialize
1217 /// to a bare lowercase string (`"student"`, `"teacher"`, …) instead of the
1318 /// default object-wrapped form, so it stores in the `role` column's `TYPE string`
@@ -15,6 +20,7 @@ use crate::error::ValidationError;
1520 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, SurrealValue)]
1621 #[surreal(untagged, rename_all = "lowercase")]
1722 pub enum Role {
23+ Parent,
1824 Student,
1925 Teacher,
2026 Manager,
@@ -23,11 +29,18 @@ pub enum Role {
2329
2430 impl Role {
2531 /// Every role, lowest privilege first.
26- pub const ALL: [Role; 4] = [Role::Student, Role::Teacher, Role::Manager, Role::Admin];
32+ pub const ALL: [Role; 5] = [
33+ Role::Parent,
34+ Role::Student,
35+ Role::Teacher,
36+ Role::Manager,
37+ Role::Admin,
38+ ];
2739
2840 /// The wire/storage form. Must stay in lockstep with `rename_all = "lowercase"`.
2941 pub fn as_str(self) -> &'static str {
3042 match self {
43+ Role::Parent => "parent",
3144 Role::Student => "student",
3245 Role::Teacher => "teacher",
3346 Role::Manager => "manager",
@@ -42,7 +55,7 @@ impl Role {
4255 .find(|role| role.as_str() == value)
4356 .ok_or(ValidationError::Invalid {
4457 field: "role",
45- reason: "must be one of: student, teacher, manager, admin",
58+ reason: "must be one of: parent, student, teacher, manager, admin",
4659 })
4760 }
4861
@@ -59,11 +72,21 @@ mod tests {
5972
6073 #[tokio::test]
6174 async fn hierarchy_orders_low_to_high() {
75+ assert!(Role::Parent < Role::Student);
6276 assert!(Role::Student < Role::Teacher);
6377 assert!(Role::Teacher < Role::Manager);
6478 assert!(Role::Manager < Role::Admin);
6579 }
6680
81+ #[tokio::test]
82+ async fn parent_clears_no_bar_above_itself() {
83+ // A parent is an observer: it must never satisfy a staff (or even
84+ // student) requirement through the hierarchy.
85+ assert!(Role::Parent.at_least(Role::Parent));
86+ assert!(!Role::Parent.at_least(Role::Student));
87+ assert!(!Role::Parent.at_least(Role::Teacher));
88+ }
89+
6790 #[tokio::test]
6891 async fn at_least_is_inclusive_and_upward() {
6992 // A teacher clears the teacher bar and everything below it.
src/lib.rsmodified+5 -5
@@ -32,22 +32,22 @@ use crate::state::AppState;
3232 info(
3333 title = "Hezarfen Backend API",
3434 version = env!("CARGO_PKG_VERSION"),
35- description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds — `course` (a regular class), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call; each course also owns its curriculum as a list of subjects, and every exam question must be tagged with one of its course's subjects (a subject still referenced by questions cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.",
35+ description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds — `course` (a regular class), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call; each course also owns its curriculum as a list of subjects, and every exam question must be tagged with one of its course's subjects (a subject still referenced by questions cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, and pomodoro reports — and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.",
3636 ),
3737 modifiers(&SecurityAddon),
3838 tags(
3939 (name = "meta", description = "Liveness and service metadata"),
4040 (name = "auth", description = "Registration, login, session lifecycle"),
41- (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only)"),
41+ (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties), and a parent lists their own students at `/users/me/students`; the tie grants the parent read access to those students' mark, attendance, and pomodoro reports and nothing else"),
4242 (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"),
4343 (name = "events", description = "Events with an audience (school-wide, one role, a course's enrollment, or a registration signup list — the expected-attendee roster; every event stays visible to all) and their attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts"),
4444 (name = "courses", description = "Courses — kind `course` (regular class), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions"),
4545 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"),
4646 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),
47- (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"),
48- (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"),
47+ (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"),
48+ (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),
4949 (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"),
50- (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings)"),
50+ (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),
5151 (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). Read: any authenticated user; edit: manager+"),
5252 (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, manager+); edit follows course management rights"),
5353 (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"),
src/web/attendance.rsmodified+11 -7
@@ -17,7 +17,7 @@ use crate::error::{AppError, ErrorResponse};
1717 use crate::state::AppState;
1818
1919 use super::courses::can_manage_course;
20-use super::{CourseResponse, CurrentUser, RequireTeacher, person_map};
20+use super::{CourseResponse, CurrentUser, ensure_can_observe, person_map};
2121
2222 pub fn routes() -> OpenApiRouter<AppState> {
2323 OpenApiRouter::new()
@@ -174,9 +174,10 @@ async fn my_report(
174174 Ok(Json(build_report(user.get_id(), None, &st.db).await?))
175175 }
176176
177-/// Any user's attendance report. Requires teacher+. Managers and admins see
178-/// every course; a teacher sees the event tallies plus only the roll-call
179-/// blocks of the target's courses they manage.
177+/// Any user's attendance report. Requires teacher+, or a parent tied to the
178+/// target student. Managers, admins, and parents see every course; a teacher
179+/// sees the event tallies plus only the roll-call blocks of the target's
180+/// courses they manage.
180181 #[utoipa::path(
181182 get,
182183 path = "/{user}",
@@ -186,21 +187,24 @@ async fn my_report(
186187 responses(
187188 (status = 200, description = "The user's attendance report, narrowed to the caller's courses", body = AttendanceReport),
188189 (status = 401, description = "Not authenticated", body = ErrorResponse),
189- (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
190+ (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse),
190191 (status = 404, description = "User not found", body = ErrorResponse),
191192 ),
192193 )]
193194 async fn user_report(
194195 State(st): State<AppState>,
195- RequireTeacher(teacher): RequireTeacher,
196+ CurrentUser(caller): CurrentUser,
196197 Path(user): Path<String>,
197198 ) -> Result<Json<AttendanceReport>, AppError> {
198199 let target = UserId::from_key(&user);
200+ ensure_can_observe(&caller, &target, &st.db).await?;
199201 // User must exist — a missing user is a 404, not an empty report.
200202 User::read(&target, &st.db)
201203 .await?
202204 .ok_or(AppError::NotFound)?;
203- let viewer = (!teacher.get_role().at_least(Role::Manager)).then_some(&teacher);
205+ // Only an exactly-teacher caller is narrowed to their managed courses;
206+ // manager+ and a linked parent read the full report.
207+ let viewer = (caller.get_role() == Role::Teacher).then_some(&caller);
204208 Ok(Json(build_report(&target, viewer, &st.db).await?))
205209 }
206210
src/web/dto.rsmodified+4 -1
@@ -14,13 +14,15 @@ use crate::domain::subject::Subject;
1414 use crate::domain::user::{User, UserId};
1515 use crate::error::AppError;
1616
17-/// The four access roles, lowest to highest privilege. The web-facing mirror of
17+/// The five access roles, lowest to highest privilege (`parent` is a read-only
18+/// observer of its linked students). The web-facing mirror of
1819 /// [`crate::domain::role::Role`] — it carries the serde + OpenAPI derives (which
1920 /// the domain type deliberately omits), so it renders as a proper `enum` in the
2021 /// docs. Serializes to the same lowercase strings the domain stores.
2122 #[derive(Serialize, Clone, Copy, ToSchema)]
2223 #[serde(rename_all = "lowercase")]
2324 pub enum Role {
25+ Parent,
2426 Student,
2527 Teacher,
2628 Manager,
@@ -30,6 +32,7 @@ pub enum Role {
3032 impl From<DomainRole> for Role {
3133 fn from(role: DomainRole) -> Self {
3234 match role {
35+ DomainRole::Parent => Role::Parent,
3336 DomainRole::Student => Role::Student,
3437 DomainRole::Teacher => Role::Teacher,
3538 DomainRole::Manager => Role::Manager,
src/web/events.rsmodified+2 -2
@@ -44,8 +44,8 @@ enum AudienceDto {
4444 /// Everybody in the school. The default when a create request omits
4545 /// `audience` entirely.
4646 School,
47- /// Every user holding exactly this role — `student`, `teacher`, `manager`,
48- /// or `admin` (no implied "and above").
47+ /// Every user holding exactly this role — `parent`, `student`, `teacher`,
48+ /// `manager`, or `admin` (no implied "and above").
4949 Role { role: String },
5050 /// The students currently enrolled in this course (live — enrollment
5151 /// changes move people in and out).
src/web/marks.rsmodified+11 -7
@@ -18,7 +18,7 @@ use crate::error::{AppError, ErrorResponse};
1818 use crate::state::AppState;
1919
2020 use super::courses::can_manage_course;
21-use super::{CourseResponse, CurrentUser, RequireTeacher, person_map};
21+use super::{CourseResponse, CurrentUser, ensure_can_observe, person_map};
2222
2323 pub fn routes() -> OpenApiRouter<AppState> {
2424 OpenApiRouter::new()
@@ -177,9 +177,10 @@ async fn my_marks(
177177 Ok(Json(build_report(user.get_id(), None, &st.db).await?))
178178 }
179179
180-/// Any user's mark report. Requires teacher+. Managers and admins see every
181-/// course; a teacher sees only the target's courses they manage — the rest of
182-/// the report (other teachers' courses) stays out of reach.
180+/// Any user's mark report. Requires teacher+, or a parent tied to the target
181+/// student. Managers, admins, and parents see every course; a teacher sees
182+/// only the target's courses they manage — the rest of the report (other
183+/// teachers' courses) stays out of reach.
183184 #[utoipa::path(
184185 get,
185186 path = "/{user}",
@@ -189,21 +190,24 @@ async fn my_marks(
189190 responses(
190191 (status = 200, description = "The user's mark report, narrowed to the caller's courses", body = MarksReport),
191192 (status = 401, description = "Not authenticated", body = ErrorResponse),
192- (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
193+ (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse),
193194 (status = 404, description = "User not found", body = ErrorResponse),
194195 ),
195196 )]
196197 async fn user_marks(
197198 State(st): State<AppState>,
198- RequireTeacher(teacher): RequireTeacher,
199+ CurrentUser(caller): CurrentUser,
199200 Path(user): Path<String>,
200201 ) -> Result<Json<MarksReport>, AppError> {
201202 let target = UserId::from_key(&user);
203+ ensure_can_observe(&caller, &target, &st.db).await?;
202204 // User must exist — a missing user is a 404, not an empty report.
203205 User::read(&target, &st.db)
204206 .await?
205207 .ok_or(AppError::NotFound)?;
206- let viewer = (!teacher.get_role().at_least(Role::Manager)).then_some(&teacher);
208+ // Only an exactly-teacher caller is narrowed to their managed courses;
209+ // manager+ and a linked parent read the full report.
210+ let viewer = (caller.get_role() == Role::Teacher).then_some(&caller);
207211 Ok(Json(build_report(&target, viewer, &st.db).await?))
208212 }
209213
src/web/mod.rsmodified+25 -0
@@ -39,9 +39,34 @@ use serde::{Deserialize, Deserializer};
3939 use utoipa::ToSchema;
4040
4141 use crate::constant::SCHEDULE_PAST_GRACE_MS;
42+use crate::database::Database;
43+use crate::domain::parent_link::ParentLink;
44+use crate::domain::role::Role;
4245 use crate::domain::timestamp::Timestamp;
46+use crate::domain::user::{User, UserId};
4347 use crate::error::{AppError, ValidationError};
4448
49+/// May `caller` read `target`'s per-student reports (marks, attendance,
50+/// pomodoro)? Teacher+ always may (per-endpoint narrowing is the caller's
51+/// business); a parent may exactly when a `parent_link` row ties them to the
52+/// target. Everyone else — students included — gets a 403 (self-reads go
53+/// through the `/me` endpoints).
54+pub(crate) async fn ensure_can_observe(
55+ caller: &User,
56+ target: &UserId,
57+ db: &Database,
58+) -> Result<(), AppError> {
59+ if caller.get_role().at_least(Role::Teacher) {
60+ return Ok(());
61+ }
62+ if caller.get_role() == Role::Parent && ParentLink::exists(caller.get_id(), target, db).await? {
63+ return Ok(());
64+ }
65+ Err(AppError::Forbidden(
66+ "requires teacher role or higher, or a parent link to this student",
67+ ))
68+}
69+
4570 /// If both ends are present, `ends_at` must not precede `starts_at`. Shared by
4671 /// everything that carries a time range (events, course sessions).
4772 pub(crate) fn check_time_range(
src/web/pomodoro.rsmodified+6 -5
@@ -12,7 +12,7 @@ use crate::domain::user::{User, UserId};
1212 use crate::error::{AppError, ErrorResponse};
1313 use crate::state::AppState;
1414
15-use super::{CurrentUser, PageParams, RequireTeacher, paginate};
15+use super::{CurrentUser, PageParams, ensure_can_observe, paginate};
1616
1717 pub fn routes() -> OpenApiRouter<AppState> {
1818 OpenApiRouter::new()
@@ -178,8 +178,8 @@ async fn my_pomodoro(
178178 }
179179
180180 /// A student's pomodoro log, newest first, with `total_focus_ms` — the same
181-/// shape as `/me`. Requires teacher+ (study oversight). Paged via
182-/// `?limit=&offset=`.
181+/// shape as `/me`. Requires teacher+ (study oversight), or a parent tied to
182+/// the target student. Paged via `?limit=&offset=`.
183183 #[utoipa::path(
184184 get,
185185 path = "/{user}",
@@ -190,18 +190,19 @@ async fn my_pomodoro(
190190 (status = 200, description = "A page of the user's pomodoro log with the unpaged focus total", body = PomodoroLog),
191191 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
192192 (status = 401, description = "Not authenticated", body = ErrorResponse),
193- (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
193+ (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse),
194194 (status = 404, description = "User not found", body = ErrorResponse),
195195 ),
196196 )]
197197 async fn user_pomodoro(
198198 State(st): State<AppState>,
199- _teacher: RequireTeacher,
199+ CurrentUser(caller): CurrentUser,
200200 Path(user): Path<String>,
201201 Query(page): Query<PageParams>,
202202 ) -> Result<Json<PomodoroLog>, AppError> {
203203 let (limit, offset) = page.resolve()?;
204204 let target = UserId::from_key(&user);
205+ ensure_can_observe(&caller, &target, &st.db).await?;
205206 // User must exist — a missing user is a 404, not an empty log.
206207 User::read(&target, &st.db)
207208 .await?
src/web/users.rsmodified+200 -3
@@ -1,12 +1,14 @@
11 use axum::Json;
22 use axum::extract::{Path, Query, State};
3-use serde::Deserialize;
3+use axum::http::StatusCode;
4+use serde::{Deserialize, Serialize};
45 use utoipa::{IntoParams, ToSchema};
56 use utoipa_axum::router::OpenApiRouter;
67 use utoipa_axum::routes;
78
89 use crate::database::Database;
910 use crate::domain::enrollment::Enrollment;
11+use crate::domain::parent_link::ParentLink;
1012 use crate::domain::preferences::{Language, Theme};
1113 use crate::domain::profile::{BirthDate, Email, PersonName, Phone};
1214 use crate::domain::role::Role;
@@ -24,11 +26,14 @@ pub fn routes() -> OpenApiRouter<AppState> {
2426 .routes(routes!(list_users))
2527 .routes(routes!(update_my_profile))
2628 .routes(routes!(update_my_preferences))
29+ .routes(routes!(my_students))
2730 .routes(routes!(search_users))
2831 .routes(routes!(get_user))
2932 .routes(routes!(set_role))
3033 .routes(routes!(update_user_profile))
3134 .routes(routes!(update_user_preferences))
35+ .routes(routes!(link_student, list_parent_students))
36+ .routes(routes!(unlink_student))
3237 }
3338
3439 #[derive(Deserialize, ToSchema)]
@@ -136,8 +141,8 @@ struct SearchUsers {
136141 /// Case-insensitive fragment of a username, name, or surname. May be
137142 /// blank when `role` is given — that lists the whole role.
138143 q: String,
139- /// Restrict matches to one role: `student`, `teacher`, `manager`, or
140- /// `admin`. Omit to search every role.
144+ /// Restrict matches to one role: `parent`, `student`, `teacher`,
145+ /// `manager`, or `admin`. Omit to search every role.
141146 role: Option<String>,
142147 /// Max matches to return. Omit for every match; when given, `1`–`500`.
143148 #[param(minimum = 1, maximum = 500, example = 100)]
@@ -395,8 +400,200 @@ async fn set_role(
395400 // Roster hygiene: only students enroll, so a non-student sheds all their
396401 // enrollment rows (security checks re-read the live role and never
397402 // trusted these; this just stops them polluting rosters and counts).
403+ // Parent links get the same sweep on both sides: only students are
404+ // observed and only parents observe, so a role change off either end
405+ // drops the rows instead of leaving dead grants around.
398406 if role != Role::Student {
399407 Enrollment::delete_for_user(&target, &st.db).await?;
408+ ParentLink::delete_where_student(&target, &st.db).await?;
409+ }
410+ if role != Role::Parent {
411+ ParentLink::delete_where_parent(&target, &st.db).await?;
400412 }
401413 Ok(Json(UserResponse::new(&updated)))
402414 }
415+
416+#[derive(Deserialize, ToSchema)]
417+struct LinkStudent {
418+ /// The student to tie to this parent.
419+ user_id: String,
420+}
421+
422+#[derive(Serialize, ToSchema)]
423+struct ParentLinkResponse {
424+ parent: PersonRef,
425+ student: PersonRef,
426+ /// The admin who created the tie.
427+ linked_by: PersonRef,
428+}
429+
430+/// One page of a parent's observed students, sorted by username. Shared by the
431+/// admin listing and the parent's own `/me/students` — they differ only in
432+/// whose links they read and who may call them.
433+async fn students_page(
434+ parent: &UserId,
435+ page: PageParams,
436+ db: &Database,
437+) -> Result<Page<PersonRef>, AppError> {
438+ let (limit, offset) = page.resolve()?;
439+ let links = ParentLink::list_for_parent(parent, db).await?;
440+ let ids: Vec<UserId> = links
441+ .iter()
442+ .map(|link| link.get_student().clone())
443+ .collect();
444+ let mut students = User::list_by_ids(&ids, db).await?;
445+ students.sort_by(|a, b| a.get_username().as_str().cmp(b.get_username().as_str()));
446+ let total = students.len() as i64;
447+ let items = paginate(&students, limit, offset)
448+ .iter()
449+ .map(PersonRef::new)
450+ .collect();
451+ Ok(Page::new(items, total, limit, offset))
452+}
453+
454+/// Tie a student to a parent account. Admin only — family ties are school-office
455+/// records, like roles. `{id}` must hold the `parent` role and `user_id` the
456+/// `student` role; a parent may observe any number of students. Idempotent:
457+/// linking the same pair again returns the existing tie. The tie grants the
458+/// parent read access to the student's marks, attendance, and pomodoro reports
459+/// — nothing else, and never any write.
460+#[utoipa::path(
461+ post,
462+ path = "/{id}/students",
463+ tag = "users",
464+ security(("session_cookie" = [])),
465+ params(("id" = String, Path, description = "Parent user id")),
466+ request_body = LinkStudent,
467+ responses(
468+ (status = 200, description = "The tie (created or already present)", body = ParentLinkResponse),
469+ (status = 400, description = "The target is not a parent, or user_id is unknown or not a student", body = ErrorResponse),
470+ (status = 401, description = "Not authenticated", body = ErrorResponse),
471+ (status = 403, description = "Requires admin role", body = ErrorResponse),
472+ (status = 404, description = "Parent user not found", body = ErrorResponse),
473+ ),
474+)]
475+async fn link_student(
476+ State(st): State<AppState>,
477+ RequireAdmin(admin): RequireAdmin,
478+ Path(id): Path<String>,
479+ Json(req): Json<LinkStudent>,
480+) -> Result<Json<ParentLinkResponse>, AppError> {
481+ let parent = User::read(&UserId::from_key(&id), &st.db)
482+ .await?
483+ .ok_or(AppError::NotFound)?;
484+ if parent.get_role() != Role::Parent {
485+ return Err(AppError::Validation(ValidationError::Invalid {
486+ field: "id",
487+ reason: "students can only be tied to a parent account",
488+ }));
489+ }
490+ let Some(student) = User::read(&UserId::from_key(&req.user_id), &st.db).await? else {
491+ return Err(AppError::Validation(ValidationError::Invalid {
492+ field: "user_id",
493+ reason: "target user does not exist",
494+ }));
495+ };
496+ if student.get_role() != Role::Student {
497+ return Err(AppError::Validation(ValidationError::Invalid {
498+ field: "user_id",
499+ reason: "only students can be tied to a parent",
500+ }));
501+ }
502+ let link = ParentLink::link(parent.get_id(), student.get_id(), admin.get_id(), &st.db).await?;
503+ let people = PersonRef::map_of(&[&parent, &student, &admin]);
504+ Ok(Json(ParentLinkResponse {
505+ parent: PersonRef::resolve(&people, link.get_parent()),
506+ student: PersonRef::resolve(&people, link.get_student()),
507+ linked_by: PersonRef::resolve(&people, link.get_linked_by()),
508+ }))
509+}
510+
511+/// List the students tied to a parent account, sorted by username. Admin only
512+/// — parents read their own list at `GET /users/me/students`. Paged via
513+/// `?limit=&offset=` like the other lists.
514+#[utoipa::path(
515+ get,
516+ path = "/{id}/students",
517+ tag = "users",
518+ security(("session_cookie" = [])),
519+ params(("id" = String, Path, description = "Parent user id"), PageParams),
520+ responses(
521+ (status = 200, description = "A page of the parent's students", body = Page<PersonRef>),
522+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
523+ (status = 401, description = "Not authenticated", body = ErrorResponse),
524+ (status = 403, description = "Requires admin role", body = ErrorResponse),
525+ (status = 404, description = "User not found", body = ErrorResponse),
526+ ),
527+)]
528+async fn list_parent_students(
529+ State(st): State<AppState>,
530+ _admin: RequireAdmin,
531+ Path(id): Path<String>,
532+ Query(page): Query<PageParams>,
533+) -> Result<Json<Page<PersonRef>>, AppError> {
534+ let parent = UserId::from_key(&id);
535+ User::read(&parent, &st.db)
536+ .await?
537+ .ok_or(AppError::NotFound)?;
538+ Ok(Json(students_page(&parent, page, &st.db).await?))
539+}
540+
541+/// Untie a student from a parent account. Admin only. The student's data is
542+/// untouched — only the parent's read grant goes away.
543+#[utoipa::path(
544+ delete,
545+ path = "/{id}/students/{student}",
546+ tag = "users",
547+ security(("session_cookie" = [])),
548+ params(
549+ ("id" = String, Path, description = "Parent user id"),
550+ ("student" = String, Path, description = "Student user id"),
551+ ),
552+ responses(
553+ (status = 204, description = "Tie removed"),
554+ (status = 401, description = "Not authenticated", body = ErrorResponse),
555+ (status = 403, description = "Requires admin role", body = ErrorResponse),
556+ (status = 404, description = "No such tie", body = ErrorResponse),
557+ ),
558+)]
559+async fn unlink_student(
560+ State(st): State<AppState>,
561+ _admin: RequireAdmin,
562+ Path((id, student)): Path<(String, String)>,
563+) -> Result<StatusCode, AppError> {
564+ if ParentLink::remove(&UserId::from_key(&id), &UserId::from_key(&student), &st.db)
565+ .await?
566+ .is_none()
567+ {
568+ return Err(AppError::NotFound);
569+ }
570+ Ok(StatusCode::NO_CONTENT)
571+}
572+
573+/// The students the calling parent observes, sorted by username. Requires the
574+/// `parent` role. Each entry's reports live at `GET /marks/{user}`,
575+/// `GET /attendance/{user}`, and `GET /pomodoro/{user}`. Paged via
576+/// `?limit=&offset=`.
577+#[utoipa::path(
578+ get,
579+ path = "/me/students",
580+ tag = "users",
581+ security(("session_cookie" = [])),
582+ params(PageParams),
583+ responses(
584+ (status = 200, description = "A page of the caller's students", body = Page<PersonRef>),
585+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
586+ (status = 401, description = "Not authenticated", body = ErrorResponse),
587+ (status = 403, description = "Requires the parent role", body = ErrorResponse),
588+ ),
589+)]
590+async fn my_students(
591+ State(st): State<AppState>,
592+ CurrentUser(user): CurrentUser,
593+ Query(page): Query<PageParams>,
594+) -> Result<Json<Page<PersonRef>>, AppError> {
595+ if user.get_role() != Role::Parent {
596+ return Err(AppError::Forbidden("requires the parent role"));
597+ }
598+ Ok(Json(students_page(user.get_id(), page, &st.db).await?))
599+}
tests/integration.rsmodified+312 -0
@@ -10730,3 +10730,315 @@ async fn results_alone_also_freeze_re_drafting() {
1073010730 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1073110731 assert_eq!(res.body["draft"], true);
1073210732 }
10733+
10734+// --- parent role ---------------------------------------------------------
10735+
10736+/// The tie lifecycle: admin-only, role-checked on both ends, idempotent, and
10737+/// symmetric between the admin listing and the parent's own `/me/students`.
10738+#[tokio::test]
10739+async fn parent_links_are_admin_managed_and_role_checked() {
10740+ let (app, db) = app_and_db().await;
10741+ let admin = login_as(&app, &db, "boss", "admin").await;
10742+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
10743+ let parent = login_as(&app, &db, "mom", "parent").await;
10744+ let parent_id = me_id(&app, &parent).await;
10745+ let ali = login(&app, "ali").await;
10746+ let ali_id = me_id(&app, &ali).await;
10747+ let teacher_id = me_id(&app, &teacher).await;
10748+
10749+ // Only an admin ties.
10750+ let res = send(
10751+ &app,
10752+ "POST",
10753+ &format!("/users/{parent_id}/students"),
10754+ Some(&teacher),
10755+ Some(json!({ "user_id": ali_id })),
10756+ )
10757+ .await;
10758+ assert_eq!(res.status, StatusCode::FORBIDDEN);
10759+
10760+ // Both ends are role-checked: the target must be a parent…
10761+ let res = send(
10762+ &app,
10763+ "POST",
10764+ &format!("/users/{teacher_id}/students"),
10765+ Some(&admin),
10766+ Some(json!({ "user_id": ali_id })),
10767+ )
10768+ .await;
10769+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
10770+ // …the student must be a student…
10771+ let res = send(
10772+ &app,
10773+ "POST",
10774+ &format!("/users/{parent_id}/students"),
10775+ Some(&admin),
10776+ Some(json!({ "user_id": teacher_id })),
10777+ )
10778+ .await;
10779+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
10780+ // …and both must exist.
10781+ let res = send(
10782+ &app,
10783+ "POST",
10784+ &format!("/users/{parent_id}/students"),
10785+ Some(&admin),
10786+ Some(json!({ "user_id": "01ZZZZZZZZZZZZZZZZZZZZZZZZ" })),
10787+ )
10788+ .await;
10789+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
10790+ let res = send(
10791+ &app,
10792+ "POST",
10793+ "/users/01ZZZZZZZZZZZZZZZZZZZZZZZZ/students",
10794+ Some(&admin),
10795+ Some(json!({ "user_id": ali_id })),
10796+ )
10797+ .await;
10798+ assert_eq!(res.status, StatusCode::NOT_FOUND);
10799+
10800+ // A valid tie lands, and linking again is a no-op returning the same tie.
10801+ for _ in 0..2 {
10802+ let res = send(
10803+ &app,
10804+ "POST",
10805+ &format!("/users/{parent_id}/students"),
10806+ Some(&admin),
10807+ Some(json!({ "user_id": ali_id })),
10808+ )
10809+ .await;
10810+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
10811+ assert_eq!(res.body["student"]["id"], json!(ali_id));
10812+ assert_eq!(res.body["parent"]["id"], json!(parent_id));
10813+ }
10814+
10815+ // Admin listing and the parent's own listing agree.
10816+ let res = send(
10817+ &app,
10818+ "GET",
10819+ &format!("/users/{parent_id}/students"),
10820+ Some(&admin),
10821+ None,
10822+ )
10823+ .await;
10824+ assert_eq!(res.status, StatusCode::OK);
10825+ assert_eq!(common::total(&res.body), 1);
10826+ let res = send(&app, "GET", "/users/me/students", Some(&parent), None).await;
10827+ assert_eq!(res.status, StatusCode::OK);
10828+ assert_eq!(common::items(&res.body)[0]["id"], json!(ali_id));
10829+ // /me/students is the parent's view — everyone else is refused.
10830+ let res = send(&app, "GET", "/users/me/students", Some(&ali), None).await;
10831+ assert_eq!(res.status, StatusCode::FORBIDDEN);
10832+
10833+ // Untie: once, then the tie is gone.
10834+ let res = send(
10835+ &app,
10836+ "DELETE",
10837+ &format!("/users/{parent_id}/students/{ali_id}"),
10838+ Some(&admin),
10839+ None,
10840+ )
10841+ .await;
10842+ assert_eq!(res.status, StatusCode::NO_CONTENT);
10843+ let res = send(
10844+ &app,
10845+ "DELETE",
10846+ &format!("/users/{parent_id}/students/{ali_id}"),
10847+ Some(&admin),
10848+ None,
10849+ )
10850+ .await;
10851+ assert_eq!(res.status, StatusCode::NOT_FOUND);
10852+}
10853+
10854+/// The tie is the parent's whole power: linked students' reports open up (in
10855+/// full — no course narrowing), everyone else's stay walled, and every write
10856+/// a parent might try is refused.
10857+#[tokio::test]
10858+async fn parent_observes_linked_students_and_nothing_else() {
10859+ let (app, db) = app_and_db().await;
10860+ let admin = login_as(&app, &db, "boss", "admin").await;
10861+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
10862+ let parent = login_as(&app, &db, "mom", "parent").await;
10863+ let parent_id = me_id(&app, &parent).await;
10864+ let ali = login(&app, "ali").await;
10865+ let ali_id = me_id(&app, &ali).await;
10866+ let bob = login(&app, "bob").await;
10867+ let bob_id = me_id(&app, &bob).await;
10868+
10869+ // ali gets a graded exam in a course the parent has nothing to do with.
10870+ let course = create_course(&app, &teacher, "algebra").await;
10871+ enroll(&app, &teacher, &course, &ali_id).await;
10872+ let exam = create_exam(&app, &teacher, &course, "midterm", "quiz").await;
10873+ let res = send(
10874+ &app,
10875+ "POST",
10876+ &format!("/exams/{exam}/results"),
10877+ Some(&teacher),
10878+ Some(json!({ "mark": 70, "user_id": ali_id })),
10879+ )
10880+ .await;
10881+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
10882+
10883+ let res = send(
10884+ &app,
10885+ "POST",
10886+ &format!("/users/{parent_id}/students"),
10887+ Some(&admin),
10888+ Some(json!({ "user_id": ali_id })),
10889+ )
10890+ .await;
10891+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
10892+
10893+ // Linked student: all three reports open, and the mark report is FULL —
10894+ // the parent manages no courses, so narrowing would blank it.
10895+ let res = send(
10896+ &app,
10897+ "GET",
10898+ &format!("/marks/{ali_id}"),
10899+ Some(&parent),
10900+ None,
10901+ )
10902+ .await;
10903+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
10904+ assert_eq!(res.body["courses"][0]["results"][0]["mark"], 70);
10905+ let res = send(
10906+ &app,
10907+ "GET",
10908+ &format!("/attendance/{ali_id}"),
10909+ Some(&parent),
10910+ None,
10911+ )
10912+ .await;
10913+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
10914+ let res = send(
10915+ &app,
10916+ "GET",
10917+ &format!("/pomodoro/{ali_id}"),
10918+ Some(&parent),
10919+ None,
10920+ )
10921+ .await;
10922+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
10923+
10924+ // Unlinked student: every report stays walled.
10925+ for uri in [
10926+ format!("/marks/{bob_id}"),
10927+ format!("/attendance/{bob_id}"),
10928+ format!("/pomodoro/{bob_id}"),
10929+ ] {
10930+ let res = send(&app, "GET", &uri, Some(&parent), None).await;
10931+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{uri} must stay walled");
10932+ }
10933+
10934+ // A parent writes nothing: not a student (pomodoro, sitting), not staff
10935+ // (courses, grading, search), and the tie grants no write-through.
10936+ let res = send(&app, "POST", "/pomodoro/start", Some(&parent), None).await;
10937+ assert_eq!(res.status, StatusCode::FORBIDDEN);
10938+ let res = send(
10939+ &app,
10940+ "POST",
10941+ "/courses",
10942+ Some(&parent),
10943+ Some(json!({ "title": "sneaky" })),
10944+ )
10945+ .await;
10946+ assert_eq!(res.status, StatusCode::FORBIDDEN);
10947+ // A sittable exam (the modeless `exam` would 409 as unsittable before any
10948+ // role question arises): the student-only wall answers first.
10949+ let sittable = create_exam_with(
10950+ &app,
10951+ &teacher,
10952+ &course,
10953+ json!({ "title": "anytime", "kind": "quiz", "mode": "open" }),
10954+ )
10955+ .await;
10956+ assert_eq!(sittable.status, StatusCode::CREATED, "{}", sittable.body);
10957+ let res = send(
10958+ &app,
10959+ "POST",
10960+ &format!("/exams/{}/attempt", id_of(&sittable.body)),
10961+ Some(&parent),
10962+ None,
10963+ )
10964+ .await;
10965+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
10966+ let res = send(&app, "GET", "/users/search?q=ali", Some(&parent), None).await;
10967+ assert_eq!(res.status, StatusCode::FORBIDDEN);
10968+}
10969+
10970+/// A role change off either end of a tie sweeps it, exactly like promotion
10971+/// sweeps enrollments — no dead read grants left behind.
10972+#[tokio::test]
10973+async fn role_change_sweeps_parent_links() {
10974+ let (app, db) = app_and_db().await;
10975+ let admin = login_as(&app, &db, "boss", "admin").await;
10976+ let parent = login_as(&app, &db, "mom", "parent").await;
10977+ let parent_id = me_id(&app, &parent).await;
10978+ let ali = login(&app, "ali").await;
10979+ let ali_id = me_id(&app, &ali).await;
10980+
10981+ let res = send(
10982+ &app,
10983+ "POST",
10984+ &format!("/users/{parent_id}/students"),
10985+ Some(&admin),
10986+ Some(json!({ "user_id": ali_id })),
10987+ )
10988+ .await;
10989+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
10990+
10991+ // The student side leaves the student role: the tie dies with it.
10992+ let res = send(
10993+ &app,
10994+ "PATCH",
10995+ &format!("/users/{ali_id}/role"),
10996+ Some(&admin),
10997+ Some(json!({ "role": "teacher" })),
10998+ )
10999+ .await;
11000+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
11001+ let res = send(&app, "GET", "/users/me/students", Some(&parent), None).await;
11002+ assert_eq!(common::total(&res.body), 0, "tie must die with the role");
11003+ let res = send(
11004+ &app,
11005+ "GET",
11006+ &format!("/marks/{ali_id}"),
11007+ Some(&parent),
11008+ None,
11009+ )
11010+ .await;
11011+ assert_eq!(res.status, StatusCode::FORBIDDEN);
11012+
11013+ // The parent side leaves the parent role: its remaining ties die too.
11014+ let bob = login(&app, "bob").await;
11015+ let bob_id = me_id(&app, &bob).await;
11016+ let res = send(
11017+ &app,
11018+ "POST",
11019+ &format!("/users/{parent_id}/students"),
11020+ Some(&admin),
11021+ Some(json!({ "user_id": bob_id })),
11022+ )
11023+ .await;
11024+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
11025+ let res = send(
11026+ &app,
11027+ "PATCH",
11028+ &format!("/users/{parent_id}/role"),
11029+ Some(&admin),
11030+ Some(json!({ "role": "student" })),
11031+ )
11032+ .await;
11033+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
11034+
11035+ // Really deleted, not merely hidden by the role checks.
11036+ let mut result = db
11037+ .query("SELECT VALUE id FROM parent_link")
11038+ .await
11039+ .expect("count parent links")
11040+ .check()
11041+ .expect("count parent links check");
11042+ let rows: Vec<surrealdb::types::RecordId> = result.take(0).expect("parent link rows");
11043+ assert!(rows.is_empty(), "parent_link rows deleted from the DB");
11044+}