Gate enrollment, exams, grading, roll call to students
Browse files at this commit32949bd584bca5bfd193fc4bee9d27cc5be1de08Parent: f3d2b0a- feat
- gate enrollment, exams, grading, roll call to students
8 changed files +378 -71
- README.md +24 -20
- src/lib.rs +3 -3
- src/web/courses.rs +14 -2
- src/web/exam_ws.rs +12 -6
- src/web/exams.rs +53 -12
- src/web/sessions.rs +24 -13
- tests/e2e.rs +85 -0
- tests/integration.rs +163 -15
README.mdmodified+24 -20
| @@ -6,7 +6,8 @@ Session-cookie auth with four hierarchical roles (`student < teacher < manager | ||
| 6 | 6 | < admin`). Notes are per-user. Attendance is event + attendees: create an event, |
| 7 | 7 | then mark users present / absent / late / excused. Marks are course-shaped |
| 8 | 8 | (Google Classroom style): a teacher creates a course, enrolls students, adds |
| 9 | -exams inside it, and grades; students read a per-course weighted average and | |
| 9 | +exams inside it, and grades — enrolling, sitting exams, roll call, and marks are | |
| 10 | +all student-only, staff never take part; students read a per-course weighted average and | |
| 10 | 11 | an overall average from their mark report — each exam weighted by its **kind** |
| 11 | 12 | (midterms can count double, orals once: weights are set per kind in settings, |
| 12 | 13 | not per exam). Exams run **sync** (one |
| @@ -162,23 +163,23 @@ effect on the user's very next call (no re-login). | ||
| 162 | 163 | | View a course's sessions | student | Only inside **visible** courses: enrolled, creator, or `manager`+ | |
| 163 | 164 | | List a session's roll call | teacher | The **session's teacher**, or anyone with course-management rights | |
| 164 | 165 | | Create / edit / delete a course session | teacher | Course-management rights (course creator, or `manager`+) | |
| 165 | -| Take a session's roll call (mark/remove **enrolled students**) | teacher | The **session's teacher**, or anyone with course-management rights | | |
| 166 | +| Take a session's roll call (mark/remove **enrolled students**) | teacher | The **session's teacher**, or anyone with course-management rights; only students sit on a roster | | |
| 166 | 167 | | Mark / remove the **session teacher's** presence row | manager | Staff presence is management's call — the teacher can't self-mark | |
| 167 | 168 | | Work check-in / check-out; view **own** work log | teacher | Instants are server-stamped, never client-supplied | |
| 168 | 169 | | View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries | |
| 169 | 170 | | Read **own** attendance report | student | | |
| 170 | 171 | | Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all | |
| 171 | 172 | | View **visible** courses/exams; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created; `manager`+: all) | |
| 172 | -| Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | Must be enrolled; window (where one exists) and `max_attempts` enforced by the server | | |
| 173 | -| Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | Attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off | | |
| 173 | +| 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 | | |
| 174 | +| 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 | | |
| 174 | 175 | | Author an exam's questions (add/edit/delete) | teacher | Course-management rights; frozen once anyone has an attempt | |
| 175 | 176 | | Read a question list (with `correct`) or a student's answer sheet | teacher | Course-management rights — one teacher can't read another's answer key | |
| 176 | 177 | | Watch an exam's live monitor (snapshot or SSE stream) | teacher | Course-management rights | |
| 177 | 178 | | Create courses | teacher | The creator manages the course | |
| 178 | -| Manage inside a course: edit/delete it, enroll/unenroll, add/edit/delete its exams, grade, remove results | teacher | Only the **course creator**, or a `manager`+ for any course | | |
| 179 | +| Manage inside a course: edit/delete it, enroll/unenroll **students**, add/edit/delete its exams, grade, remove results | teacher | Only the **course creator**, or a `manager`+ for any course; only students can be enrolled | | |
| 179 | 180 | | View a course's roster, an exam's result list / statistics | teacher | Course-management rights | |
| 180 | 181 | | Read another user's mark report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all | |
| 181 | -| Grade students | teacher | Target must be **enrolled**; grading never targets oneself | | |
| 182 | +| Grade students | teacher | Target must be an **enrolled student**; grading never targets oneself | | |
| 182 | 183 | | Edit **own** personal info (name, surname, email, phone, birth date) | student | Every account carries the same optional info fields | |
| 183 | 184 | | Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar | |
| 184 | 185 | | Edit school settings; create / edit / delete terms | manager | School policy (exam kinds, attendance statuses, grade bands) and the academic calendar are management's call | |
| @@ -277,7 +278,7 @@ their existing shapes: the student exam-room reads | ||
| 277 | 278 | | GET | `/courses/{id}` | student | Get course (enrolled, creator, or manager+) | |
| 278 | 279 | | PATCH | `/courses/{id}` | teacher | Edit course (creator, or manager+ for any) | |
| 279 | 280 | | DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, enrollments (creator, or manager+) | |
| 280 | -| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a user (idempotent upsert; course manager) | | |
| 281 | +| POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a **student** (idempotent upsert; course manager; only students can be enrolled) | | |
| 281 | 282 | | GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) · paged | |
| 282 | 283 | | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) | |
| 283 | 284 | | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` — add a lesson (course manager; teacher defaults to the caller) | |
| @@ -285,7 +286,7 @@ their existing shapes: the student exam-room reads | ||
| 285 | 286 | | GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) | |
| 286 | 287 | | PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) | |
| 287 | 288 | | DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) | |
| 288 | -| POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` — roll call: session teacher/course manager mark **enrolled** students; the teacher's own row needs manager+ | | |
| 289 | +| POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` — roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ | | |
| 289 | 290 | | GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) · paged | |
| 290 | 291 | | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) | |
| 291 | 292 | | POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?}` — add an exam (course manager); its weight comes from the kind | |
| @@ -294,12 +295,12 @@ their existing shapes: the student exam-room reads | ||
| 294 | 295 | | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+) | |
| 295 | 296 | | PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin` (course manager; `course` immutable, `mode` frozen once attempted — the rest stays live) | |
| 296 | 297 | | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, and answers (course manager) | |
| 297 | -| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled** student (upsert; course manager) | | |
| 298 | +| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled student** (upsert; course manager; students only) | | |
| 298 | 299 | | GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) · paged | |
| 299 | 300 | | GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) | |
| 300 | 301 | | DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) | |
| 301 | 302 | | GET | `/exams/{id}/statistics` | teacher | `{graded, average, min, max}` over the exam's results (course manager) | |
| 302 | -| POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt — enrolled; window open where one exists; `409` once `max_attempts` is spent | | |
| 303 | +| POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt — students only; enrolled; window open where one exists; `409` once `max_attempts` is spent | | |
| 303 | 304 | | GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` | |
| 304 | 305 | | POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room | |
| 305 | 306 | | POST | `/exams/{id}/questions` | teacher | `{text, kind, points, choices?, correct?}` — add a question (course manager; frozen once attempted) | |
| @@ -307,9 +308,9 @@ their existing shapes: the student exam-room reads | ||
| 307 | 308 | | PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question — the kind bundle revalidates as a unit (course manager; frozen once attempted) | |
| 308 | 309 | | DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) | |
| 309 | 310 | | GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded (requires enrollment + an attempt) | |
| 310 | -| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \| text?}` — autosave one answer while enrolled and `in_progress` (and not locked out by a closed rejoin door) | | |
| 311 | +| POST | `/exams/{id}/attempt/answers` | student | `{question_id, selected? \| text?}` — autosave one answer while a student, enrolled, and `in_progress` (and not locked out by a closed rejoin door) | | |
| 311 | 312 | | GET | `/exams/{id}/attempts/{user}/answers` | teacher | A student's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) | |
| 312 | -| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room: state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") | | |
| 313 | +| GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") | | |
| 313 | 314 | | 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) | |
| 314 | 315 | | GET | `/exams/{id}/live/stream` | teacher | The same snapshot as SSE `snapshot` events every ~2s (course manager) | |
| 315 | 316 | | GET | `/marks/me` | student | The caller's mark report (per-course + overall averages) | |
| @@ -459,8 +460,9 @@ A student **sits** an exam through attempts (sitting 1, 2, … — each row id i | ||
| 459 | 460 | the composite `exam_user[_seq]` key, so a sitting exists at most once by |
| 460 | 461 | construction): |
| 461 | 462 | |
| 462 | -- `POST /exams/{id}/attempt` starts, resumes, or retakes (enrolled; window | |
| 463 | - open where one exists — `open` exams start anytime). While the latest | |
| 463 | +- `POST /exams/{id}/attempt` starts, resumes, or retakes (students only — | |
| 464 | + staff never sit; enrolled; window open where one exists — `open` exams start | |
| 465 | + anytime). While the latest | |
| 464 | 466 | sitting runs, re-posting returns it unchanged (`200`, not `201`): |
| 465 | 467 | reconnecting never resets the clock. Once it is submitted or expired, |
| 466 | 468 | re-posting mints the next sitting (`201`) **from a blank answer sheet** — |
| @@ -558,8 +560,9 @@ clock on every save): | ||
| 558 | 560 | upsert: one row per question+user, re-answering overwrites. The payload must |
| 559 | 561 | match the question's kind (`selected` indexing a choice, or `text` |
| 560 | 562 | ≤ 10 000 chars — empty clears the draft); mismatches are `400`s. Requires |
| 561 | - enrollment (`403`): an unenrollment mid-exam closes the sheet (the exam | |
| 562 | - room's door check, applied to every save — finishing stays open). Once the | |
| 563 | + the student role and enrollment (`403`): a promotion out of `student` or an | |
| 564 | + unenrollment mid-exam closes the sheet (the exam room's door checks, | |
| 565 | + re-applied to every save — finishing stays open). Once the | |
| 563 | 566 | attempt is submitted or past its deadline every save is a `409` — likewise |
| 564 | 567 | while the student has left the exam room with `allow_rejoin` off; answers |
| 565 | 568 | saved in time survive untouched for grading (until a retake wipes the sheet |
| @@ -573,9 +576,9 @@ suggestion to read while grading, never written anywhere. | ||
| 573 | 576 | |
| 574 | 577 | **The exam room (WebSocket)** — `GET /exams/{id}/attempt/ws`, cookie-authed |
| 575 | 578 | like everything else; REST above remains the full fallback. Gates run before |
| 576 | -the upgrade: unknown exam `404`, draft with no mode `409`, not enrolled `403`, | |
| 577 | -no attempt yet `404` (start it first), submitted/expired `409`, left while | |
| 578 | -rejoin is closed `409`. Then JSON text frames: | |
| 579 | +the upgrade: unknown exam `404`, draft with no mode `409`, not a student `403`, | |
| 580 | +not enrolled `403`, no attempt yet `404` (start it first), submitted/expired | |
| 581 | +`409`, left while rejoin is closed `409`. Then JSON text frames: | |
| 579 | 582 | |
| 580 | 583 | | direction | frame | |
| 581 | 584 | |-----------|-------| |
| @@ -639,7 +642,8 @@ are ordered by `starts_at` (a timetable, not a creation log). | ||
| 639 | 642 | |
| 640 | 643 | **Roll call** (`/sessions/{id}/attendance`) deliberately differs from event |
| 641 | 644 | attendance: students never mark themselves. The session's teacher or a course |
| 642 | -manager marks **enrolled** students (an unenrolled target is a `400`), and the | |
| 645 | +manager marks **enrolled** students — only students attend classes, so a | |
| 646 | +non-student or unenrolled target is a `400` — and the | |
| 643 | 647 | **session teacher's own** presence row can only be written or removed by |
| 644 | 648 | manager+ — staff presence is management's call, so a teacher can't declare |
| 645 | 649 | themselves present. Listing the roll call follows the same rights as taking |
src/lib.rsmodified+3 -3
| @@ -32,7 +32,7 @@ use crate::state::AppState; | ||
| 32 | 32 | info( |
| 33 | 33 | title = "Hezarfen Backend API", |
| 34 | 34 | version = env!("CARGO_PKG_VERSION"), |
| 35 | - description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. 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. Courses carry lesson sessions with teacher-taken roll call; staff clock in/out on a server-stamped work log; 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) lives in an editable settings singleton, and courses may link to academic terms. 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. 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. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Courses carry lesson sessions with teacher-taken roll call; staff clock in/out on a server-stamped work log; 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) lives in an editable settings singleton, and courses may link to academic terms. 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.", | |
| 36 | 36 | ), |
| 37 | 37 | modifiers(&SecurityAddon), |
| 38 | 38 | tags( |
| @@ -41,11 +41,11 @@ use crate::state::AppState; | ||
| 41 | 41 | (name = "users", description = "User info: self-service profile, name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile administration (admin only)"), |
| 42 | 42 | (name = "notes", description = "Per-user notes CRUD"), |
| 43 | 43 | (name = "events", description = "Events and attendance"), |
| 44 | - (name = "courses", description = "Courses, enrollment, course exams, and course sessions"), | |
| 44 | + (name = "courses", description = "Courses, enrollment (students only), course exams, and course sessions"), | |
| 45 | 45 | (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), |
| 46 | 46 | (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), |
| 47 | 47 | (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"), |
| 48 | - (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts 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). A modeless exam is an offline-graded draft — attempts on it are a 409. 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"), | |
| 48 | + (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). A modeless exam is an offline-graded draft — attempts on it are a 409. 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"), | |
| 49 | 49 | (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 | 50 | (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands. Read: any authenticated user; edit: manager+"), |
| 51 | 51 | (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/courses.rsmodified+14 -2
| @@ -376,7 +376,9 @@ async fn delete_course( | ||
| 376 | 376 | // ---- enrollments ---------------------------------------------------------- |
| 377 | 377 | |
| 378 | 378 | /// Enroll a user into a course (idempotent upsert). Requires teacher+ and |
| 379 | -/// course management rights. | |
| 379 | +/// course management rights. Only students can be enrolled — enrollment is | |
| 380 | +/// student membership, and it gates sitting exams, being graded, and the class | |
| 381 | +/// roster, all student-only. | |
| 380 | 382 | #[utoipa::path( |
| 381 | 383 | post, |
| 382 | 384 | path = "/{id}/enrollments", |
| @@ -386,7 +388,7 @@ async fn delete_course( | ||
| 386 | 388 | request_body = EnrollUser, |
| 387 | 389 | responses( |
| 388 | 390 | (status = 200, description = "Enrolled (or already enrolled)", body = EnrollmentResponse), |
| 389 | - (status = 400, description = "Unknown user", body = ErrorResponse), | |
| 391 | + (status = 400, description = "Unknown user, or user is not a student", body = ErrorResponse), | |
| 390 | 392 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 391 | 393 | (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 392 | 394 | (status = 404, description = "Course not found", body = ErrorResponse), |
| @@ -415,6 +417,16 @@ async fn enroll( | ||
| 415 | 417 | })); |
| 416 | 418 | }; |
| 417 | 419 | |
| 420 | + // Enrollment is student membership: it gates sitting exams, being graded, | |
| 421 | + // and appearing on a lesson roster — all student-only. Staff run courses, | |
| 422 | + // they don't enroll in them. | |
| 423 | + if target_user.get_role() != Role::Student { | |
| 424 | + return Err(AppError::Validation(ValidationError::Invalid { | |
| 425 | + field: "user_id", | |
| 426 | + reason: "only students can be enrolled in a course", | |
| 427 | + })); | |
| 428 | + } | |
| 429 | + | |
| 418 | 430 | let enrollment = Enrollment::enroll(course.get_id(), &target, user.get_id(), &st.db).await?; |
| 419 | 431 | let people = PersonRef::map_of(&[&target_user, &user]); |
| 420 | 432 | Ok(Json(EnrollmentResponse::new(&enrollment, &people))) |
src/web/exam_ws.rsmodified+12 -6
| @@ -24,7 +24,9 @@ | ||
| 24 | 24 | //! Every save and every tick re-reads the exam and attempt, so the deadline |
| 25 | 25 | //! stays server-authoritative: a teacher extending `ends_at` (or `duration_ms`) |
| 26 | 26 | //! mid-exam moves this room's clock on the next tick, and a stale client can |
| 27 | -//! never write past its real deadline. | |
| 27 | +//! never write past its real deadline. Every save also re-judges the sitter — | |
| 28 | +//! live role and enrollment — so a promotion out of `student` or an | |
| 29 | +//! unenrollment mid-exam closes the sheet with no reconnect needed. | |
| 28 | 30 | //! |
| 29 | 31 | //! The room is also the presence signal behind the rejoin policy: connecting |
| 30 | 32 | //! clears the attempt's `left_at`, and the *last* socket of the sitting to |
| @@ -60,7 +62,9 @@ use crate::domain::user::UserId; | ||
| 60 | 62 | use crate::error::AppError; |
| 61 | 63 | use crate::state::AppState; |
| 62 | 64 | use crate::web::CurrentUser; |
| 63 | -use crate::web::exams::{check_rejoin, ensure_enrolled, save_answer_in, writable_attempt}; | |
| 65 | +use crate::web::exams::{ | |
| 66 | + check_rejoin, ensure_enrolled, ensure_student, save_answer_in, writable_attempt, | |
| 67 | +}; | |
| 64 | 68 | |
| 65 | 69 | /// What the client asked for, tagged by `type`. |
| 66 | 70 | #[derive(Deserialize)] |
| @@ -79,10 +83,11 @@ enum ClientMessage { | ||
| 79 | 83 | |
| 80 | 84 | /// Upgrade into the caller's exam room. All gates run *before* the upgrade so |
| 81 | 85 | /// a rejected client gets a proper HTTP status instead of an instant close: |
| 82 | -/// unknown exam (404), draft with no mode (409), not enrolled (403), no | |
| 83 | -/// attempt yet (404 — `POST /exams/{id}/attempt` first), submitted or expired | |
| 84 | -/// (409), left the room while rejoin is closed (409). Entering the room | |
| 85 | -/// clears the attempt's `left_at` — the student is back inside. | |
| 86 | +/// unknown exam (404), draft with no mode (409), not a student (403), not | |
| 87 | +/// enrolled (403), no attempt yet (404 — `POST /exams/{id}/attempt` first), | |
| 88 | +/// submitted or expired (409), left the room while rejoin is closed (409). | |
| 89 | +/// Entering the room clears the attempt's `left_at` — the student is back | |
| 90 | +/// inside. | |
| 86 | 91 | pub async fn attempt_ws( |
| 87 | 92 | State(st): State<AppState>, |
| 88 | 93 | CurrentUser(user): CurrentUser, |
| @@ -97,6 +102,7 @@ pub async fn attempt_ws( | ||
| 97 | 102 | "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)", |
| 98 | 103 | )); |
| 99 | 104 | } |
| 105 | + ensure_student(&user)?; | |
| 100 | 106 | ensure_enrolled(&exam, user.get_id(), &st.db).await?; |
| 101 | 107 | let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; |
| 102 | 108 | check_rejoin(&exam, &attempt)?; |
src/web/exams.rsmodified+53 -12
| @@ -387,8 +387,9 @@ async fn delete_exam( | ||
| 387 | 387 | // ---- results ------------------------------------------------------------ |
| 388 | 388 | |
| 389 | 389 | /// Record (or overwrite) a student's mark for an exam. Requires teacher+ and |
| 390 | -/// management rights over the exam's course; the target must be enrolled. | |
| 391 | -/// Students never grade — and nobody grades themselves. | |
| 390 | +/// management rights over the exam's course; the target must be a student and | |
| 391 | +/// enrolled. Only students carry marks; students never grade — and nobody | |
| 392 | +/// grades themselves. | |
| 392 | 393 | #[utoipa::path( |
| 393 | 394 | post, |
| 394 | 395 | path = "/{id}/results", |
| @@ -398,7 +399,7 @@ async fn delete_exam( | ||
| 398 | 399 | request_body = GradeResult, |
| 399 | 400 | responses( |
| 400 | 401 | (status = 200, description = "Result recorded", body = ExamResultResponse), |
| 401 | - (status = 400, description = "Invalid mark, unknown user, or user not enrolled", body = ErrorResponse), | |
| 402 | + (status = 400, description = "Invalid mark, unknown user, user not a student, or not enrolled", body = ErrorResponse), | |
| 402 | 403 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 403 | 404 | (status = 403, description = "Not the course creator (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse), |
| 404 | 405 | (status = 404, description = "Exam not found", body = ErrorResponse), |
| @@ -439,6 +440,15 @@ async fn grade( | ||
| 439 | 440 | })); |
| 440 | 441 | }; |
| 441 | 442 | |
| 443 | + // Only students carry marks — the grade system is theirs alone. A stale | |
| 444 | + // enrollment left behind by a promotion can't reopen grading for staff. | |
| 445 | + if target_user.get_role() != Role::Student { | |
| 446 | + return Err(AppError::Validation(ValidationError::Invalid { | |
| 447 | + field: "user_id", | |
| 448 | + reason: "only students can be graded", | |
| 449 | + })); | |
| 450 | + } | |
| 451 | + | |
| 442 | 452 | // ... and be enrolled in the exam's course. |
| 443 | 453 | if Enrollment::read_for_user(exam.get_course(), &target, &st.db) |
| 444 | 454 | .await? |
| @@ -741,9 +751,10 @@ async fn attempts_used(exam: &ExamId, user: &UserId, db: &Database) -> Result<u6 | ||
| 741 | 751 | Ok(ExamAttempt::list_for_user(exam, user, db).await?.len() as u64) |
| 742 | 752 | } |
| 743 | 753 | |
| 744 | -/// Start, resume, or retake the caller's attempt. Requires enrollment in the | |
| 745 | -/// exam's course, a sittable exam (`sync`/`async`/`open` mode), and — when a | |
| 746 | -/// window exists — the window to be open. A still-running attempt is returned | |
| 754 | +/// Start, resume, or retake the caller's attempt. Requires the student role | |
| 755 | +/// (staff run exams, they don't sit them), enrollment in the exam's course, a | |
| 756 | +/// sittable exam (`sync`/`async`/`open` mode), and — when a window exists — the | |
| 757 | +/// window to be open. A still-running attempt is returned | |
| 747 | 758 | /// as-is (`200` instead of `201`), so a reconnecting client gets its original |
| 748 | 759 | /// clock back — re-starting never resets the time. Once the latest attempt is |
| 749 | 760 | /// submitted or expired, re-posting starts the next sitting (`201`, blank |
| @@ -758,7 +769,7 @@ async fn attempts_used(exam: &ExamId, user: &UserId, db: &Database) -> Result<u6 | ||
| 758 | 769 | (status = 201, description = "Attempt started (first sitting or a retake)", body = AttemptResponse), |
| 759 | 770 | (status = 200, description = "Running attempt resumed (unchanged)", body = AttemptResponse), |
| 760 | 771 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 761 | - (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse), | |
| 772 | + (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), | |
| 762 | 773 | (status = 404, description = "Exam not found", body = ErrorResponse), |
| 763 | 774 | (status = 409, description = "Draft exam, outside the window, or no attempts remaining", body = ErrorResponse), |
| 764 | 775 | ), |
| @@ -772,6 +783,7 @@ async fn start_attempt( | ||
| 772 | 783 | .await? |
| 773 | 784 | .ok_or(AppError::NotFound)?; |
| 774 | 785 | ensure_sittable(&exam)?; |
| 786 | + ensure_student(&user)?; | |
| 775 | 787 | ensure_enrolled(&exam, user.get_id(), &st.db).await?; |
| 776 | 788 | let now = Timestamp::now(); |
| 777 | 789 | if let Some(starts_at) = exam.get_starts_at() |
| @@ -1589,8 +1601,9 @@ pub(crate) async fn save_answer_checked( | ||
| 1589 | 1601 | } |
| 1590 | 1602 | |
| 1591 | 1603 | /// The tail of the answer write path, given the sitting to write in: the |
| 1592 | -/// enrollment wall (leaving the course closes the sheet, mid-exam included), | |
| 1593 | -/// the rejoin gate, the question lookup, and the upsert. | |
| 1604 | +/// student wall and the enrollment wall (a promotion out of `student` or an | |
| 1605 | +/// unenrollment closes the sheet, mid-exam included), the rejoin gate, the | |
| 1606 | +/// question lookup, and the upsert. | |
| 1594 | 1607 | pub(crate) async fn save_answer_in( |
| 1595 | 1608 | exam: &Exam, |
| 1596 | 1609 | attempt: &ExamAttempt, |
| @@ -1599,12 +1612,38 @@ pub(crate) async fn save_answer_in( | ||
| 1599 | 1612 | text: Option<String>, |
| 1600 | 1613 | db: &Database, |
| 1601 | 1614 | ) -> Result<ExamAnswer, AppError> { |
| 1615 | + ensure_student_now(attempt.get_user(), db).await?; | |
| 1602 | 1616 | ensure_enrolled(exam, attempt.get_user(), db).await?; |
| 1603 | 1617 | check_rejoin(exam, attempt)?; |
| 1604 | 1618 | let question = question_of_exam(exam.get_id(), question_id, db).await?; |
| 1605 | 1619 | ExamAnswer::save(&question, attempt.get_user(), selected, text, db).await |
| 1606 | 1620 | } |
| 1607 | 1621 | |
| 1622 | +/// A 403 unless `user` is a student. Sitting an exam is a student action — | |
| 1623 | +/// teachers and above run exams, they never take them — so the sit paths | |
| 1624 | +/// (start, room, save) enforce it on the *current* role. Checking the live | |
| 1625 | +/// role, not just enrollment, closes the gap a mid-exam promotion would open | |
| 1626 | +/// and neutralizes any stale non-student enrollment. Reading one's own attempt | |
| 1627 | +/// and finishing stay ungated: a non-student has no attempt to read, and | |
| 1628 | +/// finishing only submits work already saved. | |
| 1629 | +pub(crate) fn ensure_student(user: &User) -> Result<(), AppError> { | |
| 1630 | + if user.get_role() != Role::Student { | |
| 1631 | + return Err(AppError::Forbidden("only students can sit exams")); | |
| 1632 | + } | |
| 1633 | + Ok(()) | |
| 1634 | +} | |
| 1635 | + | |
| 1636 | +/// The answer path's live edition of [`ensure_student`]: re-read the row and | |
| 1637 | +/// judge the *current* role, exactly like the enrollment wall beside it. Both | |
| 1638 | +/// save paths run through here (REST per request, the exam room per message), | |
| 1639 | +/// so a promotion out of `student` mid-exam closes the sheet on the very next | |
| 1640 | +/// save — the room's door check is not the last word for a socket that | |
| 1641 | +/// outlives the role. | |
| 1642 | +pub(crate) async fn ensure_student_now(user: &UserId, db: &Database) -> Result<(), AppError> { | |
| 1643 | + let user = User::read(user, db).await?.ok_or(AppError::Unauthorized)?; | |
| 1644 | + ensure_student(&user) | |
| 1645 | +} | |
| 1646 | + | |
| 1608 | 1647 | /// A 403 unless `user` is enrolled in the exam's course — the same wall the |
| 1609 | 1648 | /// exam room checks at its door, re-applied to the sitting's content paths so |
| 1610 | 1649 | /// an unenrollment mid-exam cuts them too. Finishing stays exempt: like the |
| @@ -1688,8 +1727,9 @@ async fn attempt_questions( | ||
| 1688 | 1727 | |
| 1689 | 1728 | /// Save (or overwrite) one answer in the caller's in-progress attempt. |
| 1690 | 1729 | /// `choice` questions take `selected`; `text` questions take `text`. Requires |
| 1691 | -/// enrollment in the exam's course — an unenrollment mid-exam closes the | |
| 1692 | -/// sheet. Rejected once the attempt is submitted or its deadline has passed — | |
| 1730 | +/// the student role and enrollment in the exam's course — an unenrollment (or a | |
| 1731 | +/// promotion out of `student`) mid-exam closes the sheet. Rejected once the | |
| 1732 | +/// attempt is submitted or its deadline has passed — | |
| 1693 | 1733 | /// the server clock, not the client's, is the judge — and rejected while the |
| 1694 | 1734 | /// student has left the exam room with the exam's rejoin door closed. |
| 1695 | 1735 | #[utoipa::path( |
| @@ -1703,7 +1743,7 @@ async fn attempt_questions( | ||
| 1703 | 1743 | (status = 200, description = "Answer saved", body = AnswerSavedResponse), |
| 1704 | 1744 | (status = 400, description = "Payload doesn't match the question's kind", body = ErrorResponse), |
| 1705 | 1745 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1706 | - (status = 403, description = "Not enrolled in the exam's course", body = ErrorResponse), | |
| 1746 | + (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), | |
| 1707 | 1747 | (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse), |
| 1708 | 1748 | (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), |
| 1709 | 1749 | ), |
| @@ -1717,6 +1757,7 @@ async fn save_answer( | ||
| 1717 | 1757 | let exam = Exam::read(&ExamId::from_key(&id), &st.db) |
| 1718 | 1758 | .await? |
| 1719 | 1759 | .ok_or(AppError::NotFound)?; |
| 1760 | + ensure_student(&user)?; | |
| 1720 | 1761 | let answer = save_answer_checked( |
| 1721 | 1762 | &exam, |
| 1722 | 1763 | user.get_id(), |
src/web/sessions.rsmodified+24 -13
| @@ -266,9 +266,10 @@ async fn delete_session( | ||
| 266 | 266 | // ---- roll call -------------------------------------------------------------- |
| 267 | 267 | |
| 268 | 268 | /// Record a user's roll-call state for a session. The session's teacher or a |
| 269 | -/// course manager marks **enrolled students**; marking the **session's | |
| 270 | -/// teacher** requires manager+ (staff presence is management's call, so a | |
| 271 | -/// teacher can't mark themselves present). Students never self-mark a lesson. | |
| 269 | +/// course manager marks **enrolled students** (only students attend classes); | |
| 270 | +/// marking the **session's teacher** requires manager+ (staff presence is | |
| 271 | +/// management's call, so a teacher can't mark themselves present). Students | |
| 272 | +/// never self-mark a lesson. | |
| 272 | 273 | #[utoipa::path( |
| 273 | 274 | post, |
| 274 | 275 | path = "/{id}/attendance", |
| @@ -278,7 +279,7 @@ async fn delete_session( | ||
| 278 | 279 | request_body = MarkRollCall, |
| 279 | 280 | responses( |
| 280 | 281 | (status = 200, description = "Roll-call state recorded", body = SessionAttendanceResponse), |
| 281 | - (status = 400, description = "Invalid status, unknown user, or target not on the roster", body = ErrorResponse), | |
| 282 | + (status = 400, description = "Invalid status, unknown user, target not a student, or not on the roster", body = ErrorResponse), | |
| 282 | 283 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 283 | 284 | (status = 403, description = "Not the session teacher or a course manager; or marking the teacher without manager+", body = ErrorResponse), |
| 284 | 285 | (status = 404, description = "Session not found", body = ErrorResponse), |
| @@ -316,15 +317,25 @@ async fn mark_roll_call( | ||
| 316 | 317 | "marking the session's teacher requires manager role or higher", |
| 317 | 318 | )); |
| 318 | 319 | } |
| 319 | - } else if Enrollment::read_for_user(session.get_course(), &target, &st.db) | |
| 320 | - .await? | |
| 321 | - .is_none() | |
| 322 | - { | |
| 323 | - // Everyone else on a lesson's roster comes from the enrollment list. | |
| 324 | - return Err(AppError::Validation(ValidationError::Invalid { | |
| 325 | - field: "user_id", | |
| 326 | - reason: "target user is not enrolled in this course", | |
| 327 | - })); | |
| 320 | + } else { | |
| 321 | + // Everyone else on a lesson's roster is an enrolled student. Only | |
| 322 | + // students attend classes; checking the live role keeps a stale | |
| 323 | + // enrollment (left by a promotion) from putting staff on the roll. | |
| 324 | + if target_user.get_role() != Role::Student { | |
| 325 | + return Err(AppError::Validation(ValidationError::Invalid { | |
| 326 | + field: "user_id", | |
| 327 | + reason: "only students can be marked present in a lesson", | |
| 328 | + })); | |
| 329 | + } | |
| 330 | + if Enrollment::read_for_user(session.get_course(), &target, &st.db) | |
| 331 | + .await? | |
| 332 | + .is_none() | |
| 333 | + { | |
| 334 | + return Err(AppError::Validation(ValidationError::Invalid { | |
| 335 | + field: "user_id", | |
| 336 | + reason: "target user is not enrolled in this course", | |
| 337 | + })); | |
| 338 | + } | |
| 328 | 339 | } |
| 329 | 340 | |
| 330 | 341 | let attendance = |
tests/e2e.rsmodified+85 -0
| @@ -758,6 +758,7 @@ async fn ws_frame_of_type(ws: &mut WsStream, kind: &str) -> Value { | ||
| 758 | 758 | /// `window_ms` from now. |
| 759 | 759 | struct ExamRoom { |
| 760 | 760 | base: String, |
| 761 | + db: Database, | |
| 761 | 762 | teacher: Client, |
| 762 | 763 | student: Client, |
| 763 | 764 | student_id: String, |
| @@ -840,6 +841,7 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom { | ||
| 840 | 841 | let cookie = raw_session_cookie(&base, "veli").await; |
| 841 | 842 | ExamRoom { |
| 842 | 843 | base, |
| 844 | + db, | |
| 843 | 845 | teacher, |
| 844 | 846 | student, |
| 845 | 847 | student_id, |
| @@ -1060,6 +1062,89 @@ async fn exam_room_rejects_bad_handshakes() { | ||
| 1060 | 1062 | ); |
| 1061 | 1063 | } |
| 1062 | 1064 | |
| 1065 | +/// A promotion out of `student` mid-exam closes the open room's answer sheet | |
| 1066 | +/// on the very next save: the role wall is re-judged per save against the | |
| 1067 | +/// live row — like the enrollment wall — so the door check is never the last | |
| 1068 | +/// word for a socket that outlives the role. A demotion back reopens the | |
| 1069 | +/// sheet on the same socket: it is a live check, not a latch. | |
| 1070 | +#[tokio::test] | |
| 1071 | +async fn exam_room_promotion_mid_exam_closes_the_sheet() { | |
| 1072 | + let room = exam_room_fixture(600_000).await; | |
| 1073 | + let ExamRoom { | |
| 1074 | + base, | |
| 1075 | + db, | |
| 1076 | + teacher, | |
| 1077 | + student, | |
| 1078 | + student_id, | |
| 1079 | + cookie, | |
| 1080 | + exam_id, | |
| 1081 | + question_id, | |
| 1082 | + .. | |
| 1083 | + } = &room; | |
| 1084 | + let res = student | |
| 1085 | + .post(format!("{base}/exams/{exam_id}/attempt")) | |
| 1086 | + .send() | |
| 1087 | + .await | |
| 1088 | + .unwrap(); | |
| 1089 | + assert_eq!(res.status(), StatusCode::CREATED); | |
| 1090 | + let mut ws = ws_open(base, exam_id, Some(cookie)).await.expect("upgrade"); | |
| 1091 | + | |
| 1092 | + // While the sitter is a student the sheet is open — save one answer. | |
| 1093 | + ws_send( | |
| 1094 | + &mut ws, | |
| 1095 | + json!({ "type": "answer", "question_id": question_id, "selected": 1 }), | |
| 1096 | + ) | |
| 1097 | + .await; | |
| 1098 | + ws_frame_of_type(&mut ws, "saved").await; | |
| 1099 | + | |
| 1100 | + // Mid-exam, with the socket still open, the sitter stops being a student. | |
| 1101 | + promote(db, "veli", "teacher").await; | |
| 1102 | + | |
| 1103 | + // The very next save is refused over the same socket... | |
| 1104 | + ws_send( | |
| 1105 | + &mut ws, | |
| 1106 | + json!({ "type": "answer", "question_id": question_id, "selected": 0 }), | |
| 1107 | + ) | |
| 1108 | + .await; | |
| 1109 | + let error = ws_frame_of_type(&mut ws, "error").await; | |
| 1110 | + assert!( | |
| 1111 | + error["message"].as_str().unwrap().contains("only students"), | |
| 1112 | + "{error}" | |
| 1113 | + ); | |
| 1114 | + | |
| 1115 | + // ... and over REST — the two paths share the wall. | |
| 1116 | + let res = student | |
| 1117 | + .post(format!("{base}/exams/{exam_id}/attempt/answers")) | |
| 1118 | + .json(&json!({ "question_id": question_id, "selected": 0 })) | |
| 1119 | + .send() | |
| 1120 | + .await | |
| 1121 | + .unwrap(); | |
| 1122 | + assert_eq!(res.status(), StatusCode::FORBIDDEN); | |
| 1123 | + | |
| 1124 | + // The refused writes left no trace: the sheet still holds the original. | |
| 1125 | + let sheet: Value = teacher | |
| 1126 | + .get(format!( | |
| 1127 | + "{base}/exams/{exam_id}/attempts/{student_id}/answers" | |
| 1128 | + )) | |
| 1129 | + .send() | |
| 1130 | + .await | |
| 1131 | + .unwrap() | |
| 1132 | + .json() | |
| 1133 | + .await | |
| 1134 | + .unwrap(); | |
| 1135 | + assert_eq!(sheet["answers"].as_array().unwrap().len(), 1); | |
| 1136 | + assert_eq!(sheet["answers"][0]["selected"], 1); | |
| 1137 | + | |
| 1138 | + // Demoted back, the same socket writes again — no reconnect required. | |
| 1139 | + promote(db, "veli", "student").await; | |
| 1140 | + ws_send( | |
| 1141 | + &mut ws, | |
| 1142 | + json!({ "type": "answer", "question_id": question_id, "selected": 0 }), | |
| 1143 | + ) | |
| 1144 | + .await; | |
| 1145 | + ws_frame_of_type(&mut ws, "saved").await; | |
| 1146 | +} | |
| 1147 | + | |
| 1063 | 1148 | /// A teacher extending `ends_at` mid-exam moves the open room's countdown on |
| 1064 | 1149 | /// the next tick — the deadline is re-read, never cached in the socket. |
| 1065 | 1150 | #[tokio::test] |
tests/integration.rsmodified+163 -15
| @@ -7,7 +7,7 @@ use axum::body::Body; | ||
| 7 | 7 | use axum::http::{Request, StatusCode}; |
| 8 | 8 | use common::{ |
| 9 | 9 | app_and_db, create_course, create_exam, create_exam_with, create_session, enroll, id_of, login, |
| 10 | - login_as, me_id, mem_app, send, | |
| 10 | + login_as, me_id, mem_app, send, set_role, | |
| 11 | 11 | }; |
| 12 | 12 | use hezarfen_backend::domain::exam::ExamId; |
| 13 | 13 | use hezarfen_backend::domain::exam_attempt::ExamAttempt; |
| @@ -2989,7 +2989,10 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { | ||
| 2989 | 2989 | |
| 2990 | 2990 | /// Regression: the grade endpoint verified the exam, the mark, and that the |
| 2991 | 2991 | /// target exists — but never that the grader isn't the target, so any teacher |
| 2992 | -/// could write their own mark. "Grading never targets oneself" (README). | |
| 2992 | +/// could write their own mark. "Grading never targets oneself" (README). The | |
| 2993 | +/// self-check precedes the target-role and enrollment checks, so it holds even | |
| 2994 | +/// though staff — the only ones who can grade — are never enrolled or | |
| 2995 | +/// gradeable themselves. | |
| 2993 | 2996 | #[tokio::test] |
| 2994 | 2997 | async fn graders_cannot_grade_themselves() { |
| 2995 | 2998 | let (app, db) = app_and_db().await; |
| @@ -2997,10 +3000,11 @@ async fn graders_cannot_grade_themselves() { | ||
| 2997 | 3000 | let boss = login_as(&app, &db, "boss", "manager").await; |
| 2998 | 3001 | let teacher_id = me_id(&app, &teacher).await; |
| 2999 | 3002 | let boss_id = me_id(&app, &boss).await; |
| 3003 | + let student = login(&app, "veli").await; | |
| 3004 | + let student_id = me_id(&app, &student).await; | |
| 3000 | 3005 | |
| 3001 | 3006 | let course_id = create_course(&app, &teacher, "algebra").await; |
| 3002 | - enroll(&app, &teacher, &course_id, &teacher_id).await; | |
| 3003 | - enroll(&app, &teacher, &course_id, &boss_id).await; | |
| 3007 | + enroll(&app, &teacher, &course_id, &student_id).await; | |
| 3004 | 3008 | let exam_id = create_exam(&app, &teacher, &course_id, "t", "quiz").await; |
| 3005 | 3009 | |
| 3006 | 3010 | // Self-grading is forbidden at every privilege level, not just for teachers. |
| @@ -3036,18 +3040,154 @@ async fn graders_cannot_grade_themselves() { | ||
| 3036 | 3040 | 0 |
| 3037 | 3041 | ); |
| 3038 | 3042 | |
| 3039 | - // Grading someone *else* still works (boss grades teacher). | |
| 3043 | + // Grading someone *else* still works (boss grades the enrolled student). | |
| 3040 | 3044 | let res = send( |
| 3041 | 3045 | &app, |
| 3042 | 3046 | "POST", |
| 3043 | 3047 | &format!("/exams/{exam_id}/results"), |
| 3044 | 3048 | Some(&boss), |
| 3045 | - Some(json!({ "mark": 90, "user_id": teacher_id })), | |
| 3049 | + Some(json!({ "mark": 90, "user_id": student_id })), | |
| 3046 | 3050 | ) |
| 3047 | 3051 | .await; |
| 3048 | 3052 | assert_eq!(res.status, StatusCode::OK); |
| 3049 | 3053 | } |
| 3050 | 3054 | |
| 3055 | +/// Enrollment is student membership: staff (teacher/manager/admin) can't be | |
| 3056 | +/// enrolled, so they never gain the seat that gates sitting exams, being | |
| 3057 | +/// graded, and the class roster. A plain student enrolls fine. | |
| 3058 | +#[tokio::test] | |
| 3059 | +async fn only_students_can_be_enrolled() { | |
| 3060 | + let (app, db) = app_and_db().await; | |
| 3061 | + let teacher = login_as(&app, &db, "teacher", "teacher").await; | |
| 3062 | + let colleague = login_as(&app, &db, "colleague", "teacher").await; | |
| 3063 | + let manager = login_as(&app, &db, "boss", "manager").await; | |
| 3064 | + let colleague_id = me_id(&app, &colleague).await; | |
| 3065 | + let manager_id = me_id(&app, &manager).await; | |
| 3066 | + | |
| 3067 | + let course = create_course(&app, &teacher, "algebra").await; | |
| 3068 | + | |
| 3069 | + // A fellow teacher and a manager are both refused — staff don't enroll. | |
| 3070 | + for staff_id in [&colleague_id, &manager_id] { | |
| 3071 | + let res = send( | |
| 3072 | + &app, | |
| 3073 | + "POST", | |
| 3074 | + &format!("/courses/{course}/enrollments"), | |
| 3075 | + Some(&teacher), | |
| 3076 | + Some(json!({ "user_id": staff_id })), | |
| 3077 | + ) | |
| 3078 | + .await; | |
| 3079 | + assert_eq!( | |
| 3080 | + res.status, | |
| 3081 | + StatusCode::BAD_REQUEST, | |
| 3082 | + "enrolling staff must be rejected" | |
| 3083 | + ); | |
| 3084 | + } | |
| 3085 | + | |
| 3086 | + // A student enrolls without complaint (the helper asserts 200). | |
| 3087 | + let student = login(&app, "veli").await; | |
| 3088 | + let student_id = me_id(&app, &student).await; | |
| 3089 | + enroll(&app, &teacher, &course, &student_id).await; | |
| 3090 | +} | |
| 3091 | + | |
| 3092 | +/// The student-only rule is enforced on the *live* role, not merely at enroll | |
| 3093 | +/// time. A student enrolled mid-course, then promoted to staff, keeps the | |
| 3094 | +/// enrollment row — but it goes inert: they can no longer sit the exam, save | |
| 3095 | +/// answers, be graded, or be marked present. This is the "stale rows stay | |
| 3096 | +/// inert" decision, made airtight by the action-time checks. | |
| 3097 | +#[tokio::test] | |
| 3098 | +async fn promotion_out_of_student_freezes_the_seat() { | |
| 3099 | + let (app, db) = app_and_db().await; | |
| 3100 | + let teacher = login_as(&app, &db, "teacher", "teacher").await; | |
| 3101 | + let student = login(&app, "veli").await; | |
| 3102 | + let student_id = me_id(&app, &student).await; | |
| 3103 | + | |
| 3104 | + let course = create_course(&app, &teacher, "algebra").await; | |
| 3105 | + enroll(&app, &teacher, &course, &student_id).await; | |
| 3106 | + let future = Timestamp::now().as_millis() + 3_600_000; | |
| 3107 | + let session = create_session(&app, &teacher, &course, future).await; | |
| 3108 | + let exam = scheduled_exam( | |
| 3109 | + &app, | |
| 3110 | + &teacher, | |
| 3111 | + &course, | |
| 3112 | + json!({ "title": "essay", "kind": "quiz", "mode": "open" }), | |
| 3113 | + ) | |
| 3114 | + .await; | |
| 3115 | + | |
| 3116 | + // While still a student, the seat works: they can start a sitting. | |
| 3117 | + let res = send( | |
| 3118 | + &app, | |
| 3119 | + "POST", | |
| 3120 | + &format!("/exams/{exam}/attempt"), | |
| 3121 | + Some(&student), | |
| 3122 | + None, | |
| 3123 | + ) | |
| 3124 | + .await; | |
| 3125 | + assert_eq!(res.status, StatusCode::CREATED, "student sits: {}", res.body); | |
| 3126 | + | |
| 3127 | + // Promote the enrolled student to teacher; the enrollment row survives. | |
| 3128 | + set_role(&db, "veli", "teacher").await; | |
| 3129 | + | |
| 3130 | + // Sitting is now refused — the live role, not the stale seat, decides. | |
| 3131 | + let res = send( | |
| 3132 | + &app, | |
| 3133 | + "POST", | |
| 3134 | + &format!("/exams/{exam}/attempt"), | |
| 3135 | + Some(&student), | |
| 3136 | + None, | |
| 3137 | + ) | |
| 3138 | + .await; | |
| 3139 | + assert_eq!( | |
| 3140 | + res.status, | |
| 3141 | + StatusCode::FORBIDDEN, | |
| 3142 | + "promoted user can't start a sitting" | |
| 3143 | + ); | |
| 3144 | + | |
| 3145 | + // Nor can they save into the attempt they opened while still a student. | |
| 3146 | + let res = send( | |
| 3147 | + &app, | |
| 3148 | + "POST", | |
| 3149 | + &format!("/exams/{exam}/attempt/answers"), | |
| 3150 | + Some(&student), | |
| 3151 | + Some(json!({ "question_id": "nope", "selected": 0 })), | |
| 3152 | + ) | |
| 3153 | + .await; | |
| 3154 | + assert_eq!( | |
| 3155 | + res.status, | |
| 3156 | + StatusCode::FORBIDDEN, | |
| 3157 | + "promoted user can't save answers" | |
| 3158 | + ); | |
| 3159 | + | |
| 3160 | + // Grading the promoted user is refused — only students carry marks. | |
| 3161 | + let res = send( | |
| 3162 | + &app, | |
| 3163 | + "POST", | |
| 3164 | + &format!("/exams/{exam}/results"), | |
| 3165 | + Some(&teacher), | |
| 3166 | + Some(json!({ "mark": 80, "user_id": student_id })), | |
| 3167 | + ) | |
| 3168 | + .await; | |
| 3169 | + assert_eq!( | |
| 3170 | + res.status, | |
| 3171 | + StatusCode::BAD_REQUEST, | |
| 3172 | + "promoted user can't be graded" | |
| 3173 | + ); | |
| 3174 | + | |
| 3175 | + // Roll call is refused too — only students attend classes. | |
| 3176 | + let res = send( | |
| 3177 | + &app, | |
| 3178 | + "POST", | |
| 3179 | + &format!("/sessions/{session}/attendance"), | |
| 3180 | + Some(&teacher), | |
| 3181 | + Some(json!({ "status": "present", "user_id": student_id })), | |
| 3182 | + ) | |
| 3183 | + .await; | |
| 3184 | + assert_eq!( | |
| 3185 | + res.status, | |
| 3186 | + StatusCode::BAD_REQUEST, | |
| 3187 | + "promoted user can't be rolled" | |
| 3188 | + ); | |
| 3189 | +} | |
| 3190 | + | |
| 3051 | 3191 | /// Regression: `User::create` pre-checks the username and then inserts, so two |
| 3052 | 3192 | /// concurrent registrations of the same name could both pass the check; the |
| 3053 | 3193 | /// loser then hit the unique index and surfaced as a raw 500. A lost race must |
| @@ -7158,18 +7298,27 @@ async fn search_rejects_a_blank_query() { | ||
| 7158 | 7298 | |
| 7159 | 7299 | // --- courses: catalog dedup ------------------------------------------------- |
| 7160 | 7300 | |
| 7161 | -/// A teacher who is also enrolled in their own course sees it once in the | |
| 7162 | -/// catalog, not twice — the created and enrolled sources are deduplicated. | |
| 7301 | +/// A user who both created a course (while staff) and is enrolled in it (after | |
| 7302 | +/// a demotion to student) sees it once in the catalog, not twice — the created | |
| 7303 | +/// and enrolled sources are deduplicated. Enrollment is student-only now, so | |
| 7304 | +/// that overlap can only arise across a role change; the dedup must still hold. | |
| 7163 | 7305 | #[tokio::test] |
| 7164 | 7306 | async fn course_catalog_lists_a_creator_enrolled_course_once() { |
| 7165 | 7307 | let (app, db) = app_and_db().await; |
| 7166 | - let teacher = login_as(&app, &db, "teacher", "teacher").await; | |
| 7167 | - let teacher_id = me_id(&app, &teacher).await; | |
| 7308 | + let creator = login_as(&app, &db, "teacher", "teacher").await; | |
| 7309 | + let boss = login_as(&app, &db, "boss", "manager").await; | |
| 7310 | + let creator_id = me_id(&app, &creator).await; | |
| 7168 | 7311 | |
| 7169 | - let course = create_course(&app, &teacher, "algebra").await; | |
| 7170 | - enroll(&app, &teacher, &course, &teacher_id).await; | |
| 7312 | + let course = create_course(&app, &creator, "algebra").await; | |
| 7313 | + // Author the exam while still staff, before the demotion below. | |
| 7314 | + let exam = create_exam(&app, &creator, &course, "mt", "quiz").await; | |
| 7315 | + | |
| 7316 | + // Demote the creator to student, then have a manager enroll them into their | |
| 7317 | + // own course: they now show up in both the created and enrolled sources. | |
| 7318 | + set_role(&db, "teacher", "student").await; | |
| 7319 | + enroll(&app, &boss, &course, &creator_id).await; | |
| 7171 | 7320 | |
| 7172 | - let res = send(&app, "GET", "/courses", Some(&teacher), None).await; | |
| 7321 | + let res = send(&app, "GET", "/courses", Some(&creator), None).await; | |
| 7173 | 7322 | assert_eq!(res.status, StatusCode::OK); |
| 7174 | 7323 | let courses = common::items(&res.body); |
| 7175 | 7324 | assert_eq!(courses.len(), 1, "created+enrolled must dedup: {courses:?}"); |
| @@ -7177,8 +7326,7 @@ async fn course_catalog_lists_a_creator_enrolled_course_once() { | ||
| 7177 | 7326 | |
| 7178 | 7327 | // The exam catalog derives from the same visible set and must not double |
| 7179 | 7328 | // the course's exams either. |
| 7180 | - let exam = create_exam(&app, &teacher, &course, "mt", "quiz").await; | |
| 7181 | - let res = send(&app, "GET", "/exams", Some(&teacher), None).await; | |
| 7329 | + let res = send(&app, "GET", "/exams", Some(&creator), None).await; | |
| 7182 | 7330 | let exams = common::items(&res.body); |
| 7183 | 7331 | assert_eq!(exams.len(), 1, "one exam listed once: {exams:?}"); |
| 7184 | 7332 | assert_eq!(exams[0]["id"], json!(exam)); |