diff --git a/src/domain/course.rs b/src/domain/course.rs index 98f843a..6ce73c3 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -133,6 +133,16 @@ impl Course { Ok(result.take::>(0)?) } + /// The courses `user` created — a teacher's slice of the catalog. + pub async fn list_created(user: &UserId, db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM course WHERE creator = $usr ORDER BY id DESC") + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + /// Load every course behind `ids` (one query) — the join half of the /// attendance report's per-course blocks. pub async fn list_by_ids(ids: &[CourseId], db: &Database) -> Result, AppError> { diff --git a/src/domain/exam.rs b/src/domain/exam.rs index a197e8c..e05ef40 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -329,6 +329,24 @@ impl Exam { Ok(result.take::>(0)?) } + /// Every exam of every course in `courses` (one query) — the catalog as one + /// user sees it. + pub async fn list_for_courses( + courses: &[CourseId], + db: &Database, + ) -> Result, AppError> { + if courses.is_empty() { + return Ok(Vec::new()); + } + let records: Vec = courses.iter().map(CourseId::record).collect(); + let mut result = db + .query("SELECT * FROM exam WHERE course IN $courses ORDER BY id DESC") + .bind(("courses", records)) + .await? + .check()?; + Ok(result.take::>(0)?) + } + // `course` is deliberately not updatable — moving an exam between courses // would strand results of students not enrolled in the target course. pub async fn update( diff --git a/src/domain/user.rs b/src/domain/user.rs index eeca062..c063506 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -285,7 +285,11 @@ impl User { db: &Database, ) -> Result, AppError> { let needle = query.trim().to_lowercase(); - let role_clause = if role.is_some() { "AND role = $role" } else { "" }; + let role_clause = if role.is_some() { + "AND role = $role" + } else { + "" + }; let mut query = db .query(format!( "SELECT * FROM user WHERE \ diff --git a/src/web/attendance.rs b/src/web/attendance.rs index f0110ab..f7df648 100644 --- a/src/web/attendance.rs +++ b/src/web/attendance.rs @@ -10,11 +10,13 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::attendance::{Attendance, AttendanceStatus}; use crate::domain::course::{Course, CourseId}; +use crate::domain::role::Role; use crate::domain::session_attendance::SessionAttendance; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse}; use crate::state::AppState; +use super::courses::can_manage_course; use super::{CourseResponse, CurrentUser, RequireTeacher}; pub fn routes() -> OpenApiRouter { @@ -87,8 +89,15 @@ struct AttendanceReport { } /// Assemble the report: tally the user's event rows, then their session rows -/// grouped by the (denormalized) course reference. -async fn build_report(user: &UserId, db: &Database) -> Result { +/// grouped by the (denormalized) course reference. A `viewer` narrows the +/// per-course blocks — and the overall session tally — to the courses that +/// viewer manages (self-reports and manager+ reports pass `None`). Event +/// tallies are school-wide, not course data, so they stay in either case. +async fn build_report( + user: &UserId, + viewer: Option<&User>, + db: &Database, +) -> Result { let events = Attendance::list_for_user(user, db).await?; let sessions = SessionAttendance::list_for_user(user, db).await?; @@ -108,23 +117,35 @@ async fn build_report(user: &UserId, db: &Database) -> Result = Vec::with_capacity(sessions.len()); for course_id in &course_ids { // A row whose course is gone cannot happen given the delete cascade — // skip defensively rather than fabricate a course block. let Some(course) = course_by_key.get(course_id.key()) else { continue; }; + if viewer.is_some_and(|viewer| !can_manage_course(course, viewer)) { + continue; + } let rows = &by_course[course_id.key()]; + visible_rows.extend(rows.iter().copied()); blocks.push(CourseAttendance { course: CourseResponse::new(course), counts: StatusCounts::tally(rows.iter().map(|r| r.get_status())), }); } + // A narrowed viewer's overall tally follows the visible blocks; a full + // report keeps the historical every-row tally. + let session_counts = match viewer { + Some(_) => StatusCounts::tally(visible_rows.iter().map(|r| r.get_status())), + None => StatusCounts::tally(sessions.iter().map(|a| a.get_status())), + }; + Ok(AttendanceReport { user: user.key().to_string(), events: StatusCounts::tally(events.iter().map(|a| a.get_status())), - sessions: StatusCounts::tally(sessions.iter().map(|a| a.get_status())), + sessions: session_counts, courses: blocks, }) } @@ -145,10 +166,12 @@ async fn my_report( State(st): State, CurrentUser(user): CurrentUser, ) -> Result, AppError> { - Ok(Json(build_report(user.get_id(), &st.db).await?)) + Ok(Json(build_report(user.get_id(), None, &st.db).await?)) } -/// Any user's attendance report. Requires teacher+. +/// Any user's attendance report. Requires teacher+. Managers and admins see +/// every course; a teacher sees the event tallies plus only the roll-call +/// blocks of the target's courses they manage. #[utoipa::path( get, path = "/{user}", @@ -156,7 +179,7 @@ async fn my_report( security(("session_cookie" = [])), params(("user" = String, Path, description = "User id")), responses( - (status = 200, description = "The user's attendance report", body = AttendanceReport), + (status = 200, description = "The user's attendance report, narrowed to the caller's courses", body = AttendanceReport), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), (status = 404, description = "User not found", body = ErrorResponse), @@ -164,7 +187,7 @@ async fn my_report( )] async fn user_report( State(st): State, - _teacher: RequireTeacher, + RequireTeacher(teacher): RequireTeacher, Path(user): Path, ) -> Result, AppError> { let target = UserId::from_key(&user); @@ -172,7 +195,8 @@ async fn user_report( User::read(&target, &st.db) .await? .ok_or(AppError::NotFound)?; - Ok(Json(build_report(&target, &st.db).await?)) + let viewer = (!teacher.get_role().at_least(Role::Manager)).then_some(&teacher); + Ok(Json(build_report(&target, viewer, &st.db).await?)) } #[cfg(test)] diff --git a/src/web/courses.rs b/src/web/courses.rs index 1d621f7..beadf18 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -8,6 +8,7 @@ use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; +use crate::database::Database; use crate::domain::course::{Course, CourseDescription, CourseId, CourseTitle}; use crate::domain::course_session::{CourseSession, SessionTopic}; use crate::domain::enrollment::Enrollment; @@ -115,6 +116,44 @@ pub(crate) fn can_manage_course(course: &Course, user: &User) -> bool { course.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager) } +/// Who may read inside a specific course (its details, exams, sessions): +/// anyone who can manage it, plus its enrolled users. Other teachers and +/// unenrolled students see nothing. +pub(crate) async fn can_view_course( + course: &Course, + user: &User, + db: &Database, +) -> Result { + if can_manage_course(course, user) { + return Ok(true); + } + Ok( + Enrollment::read_for_user(course.get_id(), user.get_id(), db) + .await? + .is_some(), + ) +} + +/// The catalog as one user sees it: every course for manager+, otherwise the +/// courses they created plus the ones they're enrolled in, newest first. +pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result, AppError> { + if user.get_role().at_least(Role::Manager) { + return Course::list_all(db).await; + } + let mut courses = Course::list_created(user.get_id(), db).await?; + for course in Course::list_enrolled(user.get_id(), db).await? { + if !courses + .iter() + .any(|known| known.get_id() == course.get_id()) + { + courses.push(course); + } + } + // Both sources come newest-first; re-sort so the merged list is too. + courses.sort_by(|a, b| b.get_id().key().cmp(a.get_id().key())); + Ok(courses) +} + // ---- courses ------------------------------------------------------------ /// Create a course owned by the current user. Requires the `teacher` role or higher. @@ -142,22 +181,23 @@ async fn create_course( Ok((StatusCode::CREATED, Json(CourseResponse::new(&course)))) } -/// List all courses. +/// List the courses visible to the caller: every course for manager+, +/// otherwise the courses they created plus the ones they're enrolled in. #[utoipa::path( get, path = "/", tag = "courses", security(("session_cookie" = [])), responses( - (status = 200, description = "All courses", body = [CourseResponse]), + (status = 200, description = "The caller's visible courses", body = [CourseResponse]), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn list_courses( State(st): State, - _user: CurrentUser, + CurrentUser(user): CurrentUser, ) -> Result>, AppError> { - let courses = Course::list_all(&st.db).await?; + let courses = visible_courses(&user, &st.db).await?; Ok(Json(courses.iter().map(CourseResponse::new).collect())) } @@ -180,7 +220,8 @@ async fn my_courses( Ok(Json(courses.iter().map(CourseResponse::new).collect())) } -/// Fetch a single course by id. +/// Fetch a single course by id. Visible to its enrolled users, its creator, +/// and managers/admins. #[utoipa::path( get, path = "/{id}", @@ -190,17 +231,23 @@ async fn my_courses( responses( (status = 200, description = "The course", body = CourseResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), ), )] async fn get_course( State(st): State, - _user: CurrentUser, + CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { let course = Course::read(&CourseId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; + if !can_view_course(&course, &user, &st.db).await? { + return Err(AppError::Forbidden( + "only enrolled users, the course creator, or a manager/admin can view this course", + )); + } Ok(Json(CourseResponse::new(&course))) } @@ -329,8 +376,8 @@ async fn enroll( Ok(Json(EnrollmentResponse::new(&enrollment, &people))) } -/// List a course's roster. Requires teacher+ — students see their own courses -/// via `GET /courses/me`. +/// List a course's roster. Requires teacher+ and course management rights — +/// students see their own courses via `GET /courses/me`. #[utoipa::path( get, path = "/{id}/enrollments", @@ -340,21 +387,25 @@ async fn enroll( responses( (status = 200, description = "All enrollments", body = [EnrollmentResponse]), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), ), )] async fn list_roster( State(st): State, - _teacher: RequireTeacher, + RequireTeacher(user): RequireTeacher, Path(id): Path, ) -> Result>, AppError> { - let course_id = CourseId::from_key(&id); // Course must exist — a missing course is a 404, not an empty roster. - Course::read(&course_id, &st.db) + let course = Course::read(&CourseId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - let enrollments = Enrollment::list_for_course(&course_id, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can list the roster", + )); + } + let enrollments = Enrollment::list_for_course(course.get_id(), &st.db).await?; let people = person_map( enrollments .iter() @@ -471,7 +522,8 @@ async fn create_exam_in_course( Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam)))) } -/// List a course's exams. +/// List a course's exams. Visible to the course's enrolled users, its +/// creator, and managers/admins. #[utoipa::path( get, path = "/{id}/exams", @@ -481,20 +533,25 @@ async fn create_exam_in_course( responses( (status = 200, description = "The course's exams", body = [ExamResponse]), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), ), )] async fn list_course_exams( State(st): State, - _user: CurrentUser, + CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result>, AppError> { - let course_id = CourseId::from_key(&id); // Course must exist — a missing course is a 404, not an empty exam list. - Course::read(&course_id, &st.db) + let course = Course::read(&CourseId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - let exams = Exam::list_for_course(&course_id, &st.db).await?; + if !can_view_course(&course, &user, &st.db).await? { + return Err(AppError::Forbidden( + "only enrolled users, the course creator, or a manager/admin can view this course", + )); + } + let exams = Exam::list_for_course(course.get_id(), &st.db).await?; Ok(Json(exams.iter().map(ExamResponse::new).collect())) } @@ -572,7 +629,8 @@ async fn create_session_in_course( )) } -/// List a course's lesson sessions, most recent first. +/// List a course's lesson sessions, most recent first. Visible to the +/// course's enrolled users, its creator, and managers/admins. #[utoipa::path( get, path = "/{id}/sessions", @@ -582,20 +640,25 @@ async fn create_session_in_course( responses( (status = 200, description = "The course's sessions", body = [SessionResponse]), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), ), )] async fn list_course_sessions( State(st): State, - _user: CurrentUser, + CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result>, AppError> { - let course_id = CourseId::from_key(&id); // Course must exist — a missing course is a 404, not an empty list. - Course::read(&course_id, &st.db) + let course = Course::read(&CourseId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - let sessions = CourseSession::list_for_course(&course_id, &st.db).await?; + if !can_view_course(&course, &user, &st.db).await? { + return Err(AppError::Forbidden( + "only enrolled users, the course creator, or a manager/admin can view this course", + )); + } + let sessions = CourseSession::list_for_course(course.get_id(), &st.db).await?; let people = person_map(sessions.iter().map(|s| s.get_teacher().clone()), &st.db).await?; Ok(Json( sessions diff --git a/src/web/events.rs b/src/web/events.rs index 57bca72..ec135c8 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -359,7 +359,8 @@ async fn mark( Ok(Json(AttendanceResponse::new(&attendance, &people))) } -/// List the attendance roster for an event. +/// List the attendance roster for an event. Requires teacher+ — students see +/// their own tallies via `GET /attendance/me`. #[utoipa::path( get, path = "/{id}/attendance", @@ -369,12 +370,13 @@ async fn mark( responses( (status = 200, description = "Attendance roster", body = [AttendanceResponse]), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), (status = 404, description = "Event not found", body = ErrorResponse), ), )] async fn list_attendance( State(st): State, - _user: CurrentUser, + _teacher: RequireTeacher, Path(id): Path, ) -> Result>, AppError> { let event_id = EventId::from_key(&id); diff --git a/src/web/exams.rs b/src/web/exams.rs index 5a33b82..24c2761 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -26,12 +26,13 @@ use crate::domain::exam_question::{ ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, }; use crate::domain::exam_result::{ExamResult, Mark}; +use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; -use super::courses::can_manage_course; +use super::courses::{can_manage_course, can_view_course, visible_courses}; use super::{ CurrentUser, ExamResponse, PersonRef, RequireTeacher, check_not_past, person_map, set_or_clear, }; @@ -146,26 +147,34 @@ async fn course_of(exam: &Exam, db: &Database) -> Result { // ---- exams -------------------------------------------------------------- // Exams are created inside a course: `POST /courses/{id}/exams`. -/// List all exams. +/// List the exams visible to the caller: every exam for manager+, otherwise +/// the exams of the courses they created or are enrolled in. #[utoipa::path( get, path = "/", tag = "exams", security(("session_cookie" = [])), responses( - (status = 200, description = "All exams", body = [ExamResponse]), + (status = 200, description = "The caller's visible exams", body = [ExamResponse]), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn list_exams( State(st): State, - _user: CurrentUser, + CurrentUser(user): CurrentUser, ) -> Result>, AppError> { - let exams = Exam::list_all(&st.db).await?; + let exams = if user.get_role().at_least(Role::Manager) { + Exam::list_all(&st.db).await? + } else { + let courses = visible_courses(&user, &st.db).await?; + let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect(); + Exam::list_for_courses(&ids, &st.db).await? + }; Ok(Json(exams.iter().map(ExamResponse::new).collect())) } -/// Fetch a single exam by id. +/// Fetch a single exam by id. Visible to its course's enrolled users, the +/// course creator, and managers/admins. #[utoipa::path( get, path = "/{id}", @@ -175,17 +184,24 @@ async fn list_exams( responses( (status = 200, description = "The exam", body = ExamResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled in the exam's course, not its creator, and not a manager/admin", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), ), )] async fn get_exam( State(st): State, - _user: CurrentUser, + CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_view_course(&course, &user, &st.db).await? { + return Err(AppError::Forbidden( + "only enrolled users, the course creator, or a manager/admin can view this exam", + )); + } Ok(Json(ExamResponse::new(&exam))) } @@ -397,8 +413,9 @@ async fn grade( Ok(Json(ExamResultResponse::new(&result, &people))) } -/// List every result for an exam. Requires teacher+ — students read only their -/// own via `GET /exams/{id}/result`. +/// List every result for an exam. Requires teacher+ and management rights +/// over the exam's course — students read only their own via +/// `GET /exams/{id}/result`. #[utoipa::path( get, path = "/{id}/results", @@ -408,21 +425,26 @@ async fn grade( responses( (status = 200, description = "All results", body = [ExamResultResponse]), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Exam not found", body = ErrorResponse), ), )] async fn list_results( State(st): State, - _teacher: RequireTeacher, + RequireTeacher(user): RequireTeacher, Path(id): Path, ) -> Result>, AppError> { - let exam_id = ExamId::from_key(&id); // Exam must exist — a missing exam is a 404, not an empty result list. - Exam::read(&exam_id, &st.db) + let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - let results = ExamResult::list_for_exam(&exam_id, &st.db).await?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can list results", + )); + } + let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?; let people = person_map( results .iter() @@ -507,7 +529,8 @@ async fn remove_result( Ok(StatusCode::NO_CONTENT) } -/// Summary statistics for an exam's graded results. Requires teacher+. +/// Summary statistics for an exam's graded results. Requires teacher+ and +/// management rights over the exam's course. #[utoipa::path( get, path = "/{id}/statistics", @@ -517,27 +540,32 @@ async fn remove_result( responses( (status = 200, description = "The exam's mark statistics", body = ExamStatisticsResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Exam not found", body = ErrorResponse), ), )] async fn exam_statistics( State(st): State, - _teacher: RequireTeacher, + RequireTeacher(user): RequireTeacher, Path(id): Path, ) -> Result, AppError> { - let exam_id = ExamId::from_key(&id); // Exam must exist — a missing exam is a 404, not an empty statistic. - Exam::read(&exam_id, &st.db) + let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - let results = ExamResult::list_for_exam(&exam_id, &st.db).await?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can view statistics", + )); + } + let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?; let marks: Vec = results.iter().map(|r| r.get_mark().as_i64()).collect(); let average = (!marks.is_empty()).then(|| marks.iter().sum::() as f64 / marks.len() as f64); Ok(Json(ExamStatisticsResponse { - exam: exam_id.key().to_string(), + exam: exam.get_id().key().to_string(), graded: marks.len() as u64, average, min: marks.iter().min().copied(), @@ -929,8 +957,9 @@ async fn live_snapshot(exam: &Exam, db: &Database) -> Result Result, - _teacher: RequireTeacher, + RequireTeacher(user): RequireTeacher, Path(id): Path, ) -> Result, AppError> { let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can monitor this exam", + )); + } Ok(Json(live_snapshot(&exam, &st.db).await?)) } /// The live snapshot as a Server-Sent-Events stream: one `snapshot` event /// (the `ExamLiveResponse` JSON) immediately on connect and then every couple /// of seconds, so attendance, remaining time, submissions, and marks update -/// without polling. Requires teacher+. Consume with `EventSource` (cookies -/// ride along on same-site / credentialed requests). If the exam disappears -/// mid-stream an `error` event is sent instead. +/// without polling. Requires teacher+ and management rights over the exam's +/// course. Consume with `EventSource` (cookies ride along on same-site / +/// credentialed requests). If the exam disappears mid-stream an `error` event +/// is sent instead. #[utoipa::path( get, path = "/{id}/live/stream", @@ -970,20 +1006,26 @@ async fn exam_live( responses( (status = 200, description = "SSE feed of `snapshot` events (`ExamLiveResponse` as JSON)", content_type = "text/event-stream"), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Exam not found", body = ErrorResponse), ), )] async fn exam_live_stream( State(st): State, - _teacher: RequireTeacher, + RequireTeacher(user): RequireTeacher, Path(id): Path, ) -> Result>>, AppError> { let exam_id = ExamId::from_key(&id); // A missing exam is a 404 up front; after this the response is a stream. - Exam::read(&exam_id, &st.db) + let exam = Exam::read(&exam_id, &st.db) .await? .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can monitor this exam", + )); + } // First tick fires immediately, so the monitor paints on connect. The // exam is re-read every tick: schedule edits (deadline extensions) show @@ -1159,8 +1201,9 @@ async fn create_question( Ok((StatusCode::CREATED, Json(QuestionResponse::new(&question)))) } -/// The exam's full question list, `correct` indexes included. Requires -/// teacher+. Students read questions through `GET /exams/{id}/attempt/questions`. +/// The exam's full question list, `correct` indexes included — the answer +/// key. Requires teacher+ and management rights over the exam's course. +/// Students read questions through `GET /exams/{id}/attempt/questions`. #[utoipa::path( get, path = "/{id}/questions", @@ -1170,20 +1213,25 @@ async fn create_question( responses( (status = 200, description = "The exam's questions", body = [QuestionResponse]), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Exam not found", body = ErrorResponse), ), )] async fn list_questions( State(st): State, - _teacher: RequireTeacher, + RequireTeacher(user): RequireTeacher, Path(id): Path, ) -> Result>, AppError> { - let exam_id = ExamId::from_key(&id); - Exam::read(&exam_id, &st.db) + let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - let questions = ExamQuestion::list_for_exam(&exam_id, &st.db).await?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can read the question list", + )); + } + let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?; Ok(Json(questions.iter().map(QuestionResponse::new).collect())) } @@ -1496,7 +1544,8 @@ async fn save_answer( /// saved answer plus `is_correct` (`null` for text questions — those are the /// grader's call), and the machine's `auto_score` over the choice questions is /// attached as a *suggestion*: the final mark stays human, via -/// `POST /exams/{id}/results`. Requires teacher+. +/// `POST /exams/{id}/results`. Requires teacher+ and management rights over +/// the exam's course. #[utoipa::path( get, path = "/{id}/attempts/{user}/answers", @@ -1509,18 +1558,24 @@ async fn save_answer( responses( (status = 200, description = "The student's answers, judged", body = AttemptAnswersResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "No such exam, or the student has no attempt", body = ErrorResponse), ), )] async fn attempt_answers( State(st): State, - _teacher: RequireTeacher, + RequireTeacher(user): RequireTeacher, Path((id, target)): Path<(String, String)>, ) -> Result, AppError> { let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can read answer sheets", + )); + } let target = UserId::from_key(&target); // No attempt means no answer sheet — a 404, not an empty one. ExamAttempt::read_for_user(exam.get_id(), &target, &st.db) diff --git a/src/web/marks.rs b/src/web/marks.rs index 6a6dcc4..214e907 100644 --- a/src/web/marks.rs +++ b/src/web/marks.rs @@ -11,10 +11,12 @@ use crate::database::Database; use crate::domain::course::Course; use crate::domain::exam::Exam; use crate::domain::exam_result::ExamResult; +use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse}; use crate::state::AppState; +use super::courses::can_manage_course; use super::{CourseResponse, CurrentUser, RequireTeacher}; pub fn routes() -> OpenApiRouter { @@ -69,9 +71,19 @@ fn weighted_average(pairs: &[(i64, i64)]) -> Option { } /// Assemble the report: for each enrolled course, join the course's exams -/// (weights) with the user's graded results, then average. -async fn build_report(user: &UserId, db: &Database) -> Result { - let courses = Course::list_enrolled(user, db).await?; +/// (weights) with the user's graded results, then average. A `viewer` narrows +/// the report to the courses that viewer manages (self-reports and manager+ +/// reports pass `None` and see everything); the overall average follows the +/// narrowed set. +async fn build_report( + user: &UserId, + viewer: Option<&User>, + db: &Database, +) -> Result { + let mut courses = Course::list_enrolled(user, db).await?; + if let Some(viewer) = viewer { + courses.retain(|course| can_manage_course(course, viewer)); + } let mut blocks = Vec::with_capacity(courses.len()); for course in &courses { @@ -132,10 +144,12 @@ async fn my_marks( State(st): State, CurrentUser(user): CurrentUser, ) -> Result, AppError> { - Ok(Json(build_report(user.get_id(), &st.db).await?)) + Ok(Json(build_report(user.get_id(), None, &st.db).await?)) } -/// Any user's mark report. Requires teacher+. +/// Any user's mark report. Requires teacher+. Managers and admins see every +/// course; a teacher sees only the target's courses they manage — the rest of +/// the report (other teachers' courses) stays out of reach. #[utoipa::path( get, path = "/{user}", @@ -143,7 +157,7 @@ async fn my_marks( security(("session_cookie" = [])), params(("user" = String, Path, description = "User id")), responses( - (status = 200, description = "The user's mark report", body = MarksReport), + (status = 200, description = "The user's mark report, narrowed to the caller's courses", body = MarksReport), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), (status = 404, description = "User not found", body = ErrorResponse), @@ -151,7 +165,7 @@ async fn my_marks( )] async fn user_marks( State(st): State, - _teacher: RequireTeacher, + RequireTeacher(teacher): RequireTeacher, Path(user): Path, ) -> Result, AppError> { let target = UserId::from_key(&user); @@ -159,7 +173,8 @@ async fn user_marks( User::read(&target, &st.db) .await? .ok_or(AppError::NotFound)?; - Ok(Json(build_report(&target, &st.db).await?)) + let viewer = (!teacher.get_role().at_least(Role::Manager)).then_some(&teacher); + Ok(Json(build_report(&target, viewer, &st.db).await?)) } #[cfg(test)] diff --git a/src/web/sessions.rs b/src/web/sessions.rs index cbf7075..f36deb0 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -20,7 +20,7 @@ use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; -use super::courses::can_manage_course; +use super::courses::{can_manage_course, can_view_course}; use super::{ CurrentUser, PersonRef, RequireTeacher, SessionResponse, check_not_past, check_time_range, person_map, set_or_clear, @@ -131,7 +131,8 @@ fn can_roll_call(session: &CourseSession, course: &Course, user: &User) -> bool // ---- sessions ------------------------------------------------------------- -/// Fetch a single session by id. +/// Fetch a single session by id. Visible to its course's enrolled users, the +/// session's teacher, the course creator, and managers/admins. #[utoipa::path( get, path = "/{id}", @@ -141,17 +142,21 @@ fn can_roll_call(session: &CourseSession, course: &Course, user: &User) -> bool responses( (status = 200, description = "The session", body = SessionResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled, not the session teacher, and without course rights", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), ), )] async fn get_session( State(st): State, - _user: CurrentUser, + CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { - let session = CourseSession::read(&CourseSessionId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; + let (session, course) = session_with_course(&id, &st.db).await?; + if !session.is_teacher(user.get_id()) && !can_view_course(&course, &user, &st.db).await? { + return Err(AppError::Forbidden( + "only enrolled users, the session teacher, the course creator, or a manager/admin can view this session", + )); + } let people = person_map([session.get_teacher().clone()], &st.db).await?; Ok(Json(SessionResponse::new(&session, &people))) } @@ -325,7 +330,9 @@ async fn mark_roll_call( Ok(Json(SessionAttendanceResponse::new(&attendance, &people))) } -/// List a session's roll call. +/// List a session's roll call. Same rights as taking it: the session's +/// teacher or a course manager — students see their own tallies via +/// `GET /attendance/me`. #[utoipa::path( get, path = "/{id}/attendance", @@ -335,17 +342,21 @@ async fn mark_roll_call( responses( (status = 200, description = "Roll-call roster", body = [SessionAttendanceResponse]), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the session teacher or a course manager", body = ErrorResponse), (status = 404, description = "Session not found", body = ErrorResponse), ), )] async fn list_roll_call( State(st): State, - _user: CurrentUser, + RequireTeacher(user): RequireTeacher, Path(id): Path, ) -> Result>, AppError> { - let session = CourseSession::read(&CourseSessionId::from_key(&id), &st.db) - .await? - .ok_or(AppError::NotFound)?; + let (session, course) = session_with_course(&id, &st.db).await?; + if !can_roll_call(&session, &course, &user) { + return Err(AppError::Forbidden( + "only the session's teacher or a course manager can list the roll call", + )); + } let roster = SessionAttendance::list_for_session(session.get_id(), &st.db).await?; let people = person_map( roster diff --git a/tests/e2e.rs b/tests/e2e.rs index 91733a6..98a2f8d 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -159,7 +159,16 @@ async fn full_user_journey() { .unwrap(); assert_eq!(res.status(), StatusCode::OK); - let roster: Value = veli + // The roster is a teacher+ view — veli (a student) is refused … + let res = veli + .get(format!("{base}/events/{event_id}/attendance")) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::FORBIDDEN); + + // … while ali (the teacher) reads it in full. + let roster: Value = ali .get(format!("{base}/events/{event_id}/attendance")) .send() .await @@ -353,8 +362,17 @@ async fn attendance_rollup_across_users() { .await .unwrap(); - // Any attendee can read the full roster (3 people). - let roster: Value = b + // The roster is a teacher+ view: an attendee sees only their own tallies + // (`/attendance/me`), so ben is refused … + let res = b + .get(format!("{base}/events/{event_id}/attendance")) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::FORBIDDEN); + + // … while the host reads the full roster (3 people). + let roster: Value = host .get(format!("{base}/events/{event_id}/attendance")) .send() .await diff --git a/tests/integration.rs b/tests/integration.rs index 8d23712..fe10138 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -788,7 +788,7 @@ async fn event_timestamps_echo_and_validate() { // --- exams + results ----------------------------------------------------- #[tokio::test] -async fn exams_are_shared_but_course_guarded() { +async fn exams_are_course_scoped_and_course_guarded() { let (app, db) = app_and_db().await; let ali = login_as(&app, &db, "ali", "teacher").await; let veli = login_as(&app, &db, "veli", "teacher").await; @@ -808,12 +808,13 @@ async fn exams_are_shared_but_course_guarded() { assert_eq!(ex.body["weight"], 2); let exam_id = id_of(&ex.body); - // Any authenticated user can read the exam and the lists. + // A teacher outside the course sees none of it: not the exam, not the + // course's exam list, and an empty catalog. assert_eq!( send(&app, "GET", &format!("/exams/{exam_id}"), Some(&veli), None) .await .status, - StatusCode::OK + StatusCode::FORBIDDEN ); assert_eq!( send(&app, "GET", "/exams", Some(&veli), None) @@ -822,7 +823,7 @@ async fn exams_are_shared_but_course_guarded() { .as_array() .unwrap() .len(), - 1 + 0 ); assert_eq!( send( @@ -833,6 +834,35 @@ async fn exams_are_shared_but_course_guarded() { None ) .await + .status, + StatusCode::FORBIDDEN + ); + + // The course creator reads all three views. + assert_eq!( + send(&app, "GET", &format!("/exams/{exam_id}"), Some(&ali), None) + .await + .status, + StatusCode::OK + ); + assert_eq!( + send(&app, "GET", "/exams", Some(&ali), None) + .await + .body + .as_array() + .unwrap() + .len(), + 1 + ); + assert_eq!( + send( + &app, + "GET", + &format!("/courses/{course_id}/exams"), + Some(&ali), + None + ) + .await .body .as_array() .unwrap() @@ -1273,7 +1303,7 @@ async fn deleting_exam_cascades_results() { // --- courses + enrollments + marks ---------------------------------------- #[tokio::test] -async fn courses_are_shared_but_creator_guarded() { +async fn courses_are_owner_scoped_and_creator_guarded() { let (app, db) = app_and_db().await; let ali = login_as(&app, &db, "ali", "teacher").await; let veli = login_as(&app, &db, "veli", "teacher").await; @@ -1291,7 +1321,8 @@ async fn courses_are_shared_but_creator_guarded() { assert_eq!(res.body["title"], "algebra"); let course_id = id_of(&res.body); - // Any authenticated user can read the course and the list. + // Another teacher is not enrolled and doesn't manage it: no read, and the + // catalog shows them nothing. assert_eq!( send( &app, @@ -1302,7 +1333,7 @@ async fn courses_are_shared_but_creator_guarded() { ) .await .status, - StatusCode::OK + StatusCode::FORBIDDEN ); assert_eq!( send(&app, "GET", "/courses", Some(&veli), None) @@ -1311,9 +1342,34 @@ async fn courses_are_shared_but_creator_guarded() { .as_array() .unwrap() .len(), - 1 + 0 ); + // The creator and a manager see it — in the catalog too. + for caller in [&ali, &boss] { + assert_eq!( + send( + &app, + "GET", + &format!("/courses/{course_id}"), + Some(caller), + None + ) + .await + .status, + StatusCode::OK + ); + assert_eq!( + send(&app, "GET", "/courses", Some(caller), None) + .await + .body + .as_array() + .unwrap() + .len(), + 1 + ); + } + // Non-creator teacher cannot edit or delete. assert_eq!( send( @@ -1606,7 +1662,34 @@ async fn exam_creation_lives_under_courses() { StatusCode::FORBIDDEN ); - // Any authenticated user (a student) can list the course's exams. + // An unenrolled student cannot list the course's exams … + assert_eq!( + send( + &app, + "GET", + &format!("/courses/{course_id}/exams"), + Some(&alice), + None + ) + .await + .status, + StatusCode::FORBIDDEN + ); + + // … but an enrolled one can. + let alice_id = me_id(&app, &alice).await; + assert_eq!( + send( + &app, + "POST", + &format!("/courses/{course_id}/enrollments"), + Some(&teacher), + Some(json!({ "user_id": alice_id })) + ) + .await + .status, + StatusCode::OK + ); assert_eq!( send( &app, @@ -1904,6 +1987,114 @@ async fn marks_reports_are_self_or_teacher_scoped() { ); } +/// One teacher's course is a wall: another teacher can't read its roster, +/// results, statistics, live monitor, answer key, or answer sheets, and the +/// per-user reports narrow to the courses the caller manages. Managers see +/// through the wall; an enrolled student sees the course itself. +#[tokio::test] +async fn course_data_is_walled_off_from_other_teachers() { + let (app, db) = app_and_db().await; + let owner = login_as(&app, &db, "owner", "teacher").await; + let rival = login_as(&app, &db, "rival", "teacher").await; + let boss = login_as(&app, &db, "boss", "manager").await; + let alice = login(&app, "alice").await; + let alice_id = me_id(&app, &alice).await; + + let course_id = create_course(&app, &owner, "algebra").await; + enroll(&app, &owner, &course_id, &alice_id).await; + let exam_id = create_exam(&app, &owner, &course_id, "mt", "quiz", 2).await; + let res = send( + &app, + "POST", + &format!("/exams/{exam_id}/results"), + Some(&owner), + Some(json!({ "mark": 70, "user_id": alice_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + + // Every course-scoped teacher read is refused for the rival … + for uri in [ + format!("/courses/{course_id}/enrollments"), + format!("/exams/{exam_id}/results"), + format!("/exams/{exam_id}/statistics"), + format!("/exams/{exam_id}/live"), + format!("/exams/{exam_id}/live/stream"), + format!("/exams/{exam_id}/questions"), + format!("/exams/{exam_id}/attempts/{alice_id}/answers"), + ] { + let res = send(&app, "GET", &uri, Some(&rival), None).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{uri}"); + } + + // … and open to the owner and a manager. (The answer sheet turns into a + // 404 once authorization clears: alice never sat the exam.) + for caller in [&owner, &boss] { + for uri in [ + format!("/courses/{course_id}/enrollments"), + format!("/exams/{exam_id}/results"), + format!("/exams/{exam_id}/statistics"), + format!("/exams/{exam_id}/live"), + format!("/exams/{exam_id}/questions"), + ] { + let res = send(&app, "GET", &uri, Some(caller), None).await; + assert_eq!(res.status, StatusCode::OK, "{uri}"); + } + let res = send( + &app, + "GET", + &format!("/exams/{exam_id}/attempts/{alice_id}/answers"), + Some(caller), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND); + } + + // The marks report narrows to the caller's courses: the rival gets an + // empty shell, the owner and the manager get the graded course. + let res = send( + &app, + "GET", + &format!("/marks/{alice_id}"), + Some(&rival), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert!(res.body["courses"].as_array().unwrap().is_empty()); + assert!(res.body["overall_average"].is_null()); + for caller in [&owner, &boss] { + let res = send( + &app, + "GET", + &format!("/marks/{alice_id}"), + Some(caller), + None, + ) + .await; + assert_eq!(res.body["courses"].as_array().unwrap().len(), 1); + assert_eq!(res.body["overall_average"], 70.0); + } + + // The enrolled student reads the course and its exam, and both catalogs + // include them; the rival's catalogs stay empty; a manager sees all. + for uri in [format!("/courses/{course_id}"), format!("/exams/{exam_id}")] { + let res = send(&app, "GET", &uri, Some(&alice), None).await; + assert_eq!(res.status, StatusCode::OK, "{uri}"); + } + for (caller, visible) in [(&alice, 1), (&rival, 0), (&boss, 1)] { + for uri in ["/courses", "/exams"] { + let res = send(&app, "GET", uri, Some(caller), None).await; + assert_eq!( + res.body.as_array().unwrap().len(), + visible, + "{uri} as seen by caller" + ); + } + } +} + #[tokio::test] async fn deleting_course_cascades_enrollments_exams_and_results() { let (app, db) = app_and_db().await; @@ -5354,7 +5545,27 @@ async fn session_crud_follows_course_management() { .await; assert_eq!(res.status, StatusCode::BAD_REQUEST, "past ends_at"); - // Reads are open to any logged-in user; parents must exist. + // Reads follow course visibility: an unenrolled student is refused … + let res = send( + &app, + "GET", + &format!("/courses/{course}/sessions"), + Some(&student), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN); + + // … an enrolled one reads; parents must exist. + let res = send( + &app, + "POST", + &format!("/courses/{course}/enrollments"), + Some(&owner), + Some(json!({ "user_id": ali_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); let res = send( &app, "GET", @@ -5379,6 +5590,26 @@ async fn session_crud_follows_course_management() { ) .await; assert_eq!(res.status, StatusCode::OK); + // The session's own teacher reads it without course rights; a session of + // someone else's course stays out of reach. + let res = send( + &app, + "GET", + &format!("/sessions/{rival_session}"), + Some(&rival), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK); + let res = send( + &app, + "GET", + &format!("/sessions/{session}"), + Some(&rival), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN); let res = send(&app, "GET", "/sessions/nope", Some(&student), None).await; assert_eq!(res.status, StatusCode::NOT_FOUND); @@ -5556,11 +5787,18 @@ async fn roll_call_rbac_and_upsert() { ) .await; assert_eq!(res.status, StatusCode::OK); - let res = send(&app, "GET", &mark_uri, Some(&ali), None).await; - assert_eq!(res.status, StatusCode::OK, "roster is readable by students"); + // The roster follows roll-call rights: the session teacher reads it, a + // student (even a listed one) and an unrelated teacher do not — students + // get their own tallies via `/attendance/me`. + let res = send(&app, "GET", &mark_uri, Some(&hoca), None).await; + assert_eq!(res.status, StatusCode::OK); let roster = res.body.as_array().unwrap(); assert_eq!(roster.len(), 1); assert_eq!(roster[0]["status"], "absent"); + let res = send(&app, "GET", &mark_uri, Some(&ali), None).await; + assert_eq!(res.status, StatusCode::FORBIDDEN); + let res = send(&app, "GET", &mark_uri, Some(&rival), None).await; + assert_eq!(res.status, StatusCode::FORBIDDEN); // Neither an unrelated teacher nor the student themselves may mark. let res = send( @@ -6070,6 +6308,62 @@ async fn attendance_report_tallies_events_and_sessions_per_course() { .await; assert_eq!(res.status, StatusCode::OK); assert_eq!(res.body["sessions"]["total"], 4); + + // A teacher's view narrows to the courses they manage: rival runs only + // chemistry, so ali's report shows that block alone — the overall session + // tally follows, while event tallies stay school-wide. + let rival = login_as(&app, &db, "rival", "teacher").await; + let chemistry = create_course(&app, &rival, "chemistry").await; + enroll(&app, &rival, &chemistry, &ali_id).await; + let session = create_session( + &app, + &rival, + &chemistry, + Timestamp::now().as_millis() + 10 * 3_600_000, + ) + .await; + let res = send( + &app, + "POST", + &format!("/sessions/{session}/attendance"), + Some(&rival), + Some(json!({ "status": "present", "user_id": ali_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + + let res = send( + &app, + "GET", + &format!("/attendance/{ali_id}"), + Some(&rival), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["events"]["total"], 2, "events stay school-wide"); + assert_eq!(res.body["sessions"]["total"], 1); + let blocks = res.body["courses"].as_array().unwrap(); + assert_eq!(blocks.len(), 1); + assert_eq!(blocks[0]["course"]["title"], "chemistry"); + + // The owner's view still carries only their own two courses … + let res = send( + &app, + "GET", + &format!("/attendance/{ali_id}"), + Some(&owner), + None, + ) + .await; + assert_eq!(res.body["courses"].as_array().unwrap().len(), 2); + assert_eq!(res.body["sessions"]["total"], 4); + + // … and the self view stays complete: all three courses, every row. + let res = send(&app, "GET", "/attendance/me", Some(&ali), None).await; + assert_eq!(res.body["courses"].as_array().unwrap().len(), 3); + assert_eq!(res.body["sessions"]["total"], 5); + let res = send(&app, "GET", "/attendance/01UNKNOWN", Some(&owner), None).await; assert_eq!(res.status, StatusCode::NOT_FOUND); }