Wall course reads behind enrollment and ownership
Browse files at this commited007d9e9a68142c940b8dc8002512bea36e9507Parent: f89c4f8- feat
- wall course reads behind enrollment and ownership
11 changed files +623 -109
- src/domain/course.rs +10 -0
- src/domain/exam.rs +18 -0
- src/domain/user.rs +5 -1
- src/web/attendance.rs +32 -8
- src/web/courses.rs +86 -23
- src/web/events.rs +4 -2
- src/web/exams.rs +96 -41
- src/web/marks.rs +23 -8
- src/web/sessions.rs +22 -11
- tests/e2e.rs +21 -3
- tests/integration.rs +306 -12
src/domain/course.rsmodified+10 -0
| @@ -133,6 +133,16 @@ impl Course { | |||
| 133 | Ok(result.take::<Vec<Course>>(0)?) | 133 | Ok(result.take::<Vec<Course>>(0)?) |
| 134 | } | 134 | } |
| 135 | 135 | ||
| 136 | + /// The courses `user` created — a teacher's slice of the catalog. | ||
| 137 | + pub async fn list_created(user: &UserId, db: &Database) -> Result<Vec<Course>, AppError> { | ||
| 138 | + let mut result = db | ||
| 139 | + .query("SELECT * FROM course WHERE creator = $usr ORDER BY id DESC") | ||
| 140 | + .bind(("usr", user.record())) | ||
| 141 | + .await? | ||
| 142 | + .check()?; | ||
| 143 | + Ok(result.take::<Vec<Course>>(0)?) | ||
| 144 | + } | ||
| 145 | + | ||
| 136 | /// Load every course behind `ids` (one query) — the join half of the | 146 | /// Load every course behind `ids` (one query) — the join half of the |
| 137 | /// attendance report's per-course blocks. | 147 | /// attendance report's per-course blocks. |
| 138 | pub async fn list_by_ids(ids: &[CourseId], db: &Database) -> Result<Vec<Course>, AppError> { | 148 | pub async fn list_by_ids(ids: &[CourseId], db: &Database) -> Result<Vec<Course>, AppError> { |
src/domain/exam.rsmodified+18 -0
| @@ -329,6 +329,24 @@ impl Exam { | |||
| 329 | Ok(result.take::<Vec<Exam>>(0)?) | 329 | Ok(result.take::<Vec<Exam>>(0)?) |
| 330 | } | 330 | } |
| 331 | 331 | ||
| 332 | + /// Every exam of every course in `courses` (one query) — the catalog as one | ||
| 333 | + /// user sees it. | ||
| 334 | + pub async fn list_for_courses( | ||
| 335 | + courses: &[CourseId], | ||
| 336 | + db: &Database, | ||
| 337 | + ) -> Result<Vec<Exam>, AppError> { | ||
| 338 | + if courses.is_empty() { | ||
| 339 | + return Ok(Vec::new()); | ||
| 340 | + } | ||
| 341 | + let records: Vec<RecordId> = courses.iter().map(CourseId::record).collect(); | ||
| 342 | + let mut result = db | ||
| 343 | + .query("SELECT * FROM exam WHERE course IN $courses ORDER BY id DESC") | ||
| 344 | + .bind(("courses", records)) | ||
| 345 | + .await? | ||
| 346 | + .check()?; | ||
| 347 | + Ok(result.take::<Vec<Exam>>(0)?) | ||
| 348 | + } | ||
| 349 | + | ||
| 332 | // `course` is deliberately not updatable — moving an exam between courses | 350 | // `course` is deliberately not updatable — moving an exam between courses |
| 333 | // would strand results of students not enrolled in the target course. | 351 | // would strand results of students not enrolled in the target course. |
| 334 | pub async fn update( | 352 | pub async fn update( |
src/domain/user.rsmodified+5 -1
| @@ -285,7 +285,11 @@ impl User { | |||
| 285 | db: &Database, | 285 | db: &Database, |
| 286 | ) -> Result<Vec<User>, AppError> { | 286 | ) -> Result<Vec<User>, AppError> { |
| 287 | let needle = query.trim().to_lowercase(); | 287 | let needle = query.trim().to_lowercase(); |
| 288 | - let role_clause = if role.is_some() { "AND role = $role" } else { "" }; | 288 | + let role_clause = if role.is_some() { |
| 289 | + "AND role = $role" | ||
| 290 | + } else { | ||
| 291 | + "" | ||
| 292 | + }; | ||
| 289 | let mut query = db | 293 | let mut query = db |
| 290 | .query(format!( | 294 | .query(format!( |
| 291 | "SELECT * FROM user WHERE \ | 295 | "SELECT * FROM user WHERE \ |
src/web/attendance.rsmodified+32 -8
| @@ -10,11 +10,13 @@ use utoipa_axum::routes; | |||
| 10 | use crate::database::Database; | 10 | use crate::database::Database; |
| 11 | use crate::domain::attendance::{Attendance, AttendanceStatus}; | 11 | use crate::domain::attendance::{Attendance, AttendanceStatus}; |
| 12 | use crate::domain::course::{Course, CourseId}; | 12 | use crate::domain::course::{Course, CourseId}; |
| 13 | +use crate::domain::role::Role; | ||
| 13 | use crate::domain::session_attendance::SessionAttendance; | 14 | use crate::domain::session_attendance::SessionAttendance; |
| 14 | use crate::domain::user::{User, UserId}; | 15 | use crate::domain::user::{User, UserId}; |
| 15 | use crate::error::{AppError, ErrorResponse}; | 16 | use crate::error::{AppError, ErrorResponse}; |
| 16 | use crate::state::AppState; | 17 | use crate::state::AppState; |
| 17 | 18 | ||
| 19 | +use super::courses::can_manage_course; | ||
| 18 | use super::{CourseResponse, CurrentUser, RequireTeacher}; | 20 | use super::{CourseResponse, CurrentUser, RequireTeacher}; |
| 19 | 21 | ||
| 20 | pub fn routes() -> OpenApiRouter<AppState> { | 22 | pub fn routes() -> OpenApiRouter<AppState> { |
| @@ -87,8 +89,15 @@ struct AttendanceReport { | |||
| 87 | } | 89 | } |
| 88 | 90 | ||
| 89 | /// Assemble the report: tally the user's event rows, then their session rows | 91 | /// Assemble the report: tally the user's event rows, then their session rows |
| 90 | -/// grouped by the (denormalized) course reference. | 92 | +/// grouped by the (denormalized) course reference. A `viewer` narrows the |
| 91 | -async fn build_report(user: &UserId, db: &Database) -> Result<AttendanceReport, AppError> { | 93 | +/// per-course blocks — and the overall session tally — to the courses that |
| 94 | +/// viewer manages (self-reports and manager+ reports pass `None`). Event | ||
| 95 | +/// tallies are school-wide, not course data, so they stay in either case. | ||
| 96 | +async fn build_report( | ||
| 97 | + user: &UserId, | ||
| 98 | + viewer: Option<&User>, | ||
| 99 | + db: &Database, | ||
| 100 | +) -> Result<AttendanceReport, AppError> { | ||
| 92 | let events = Attendance::list_for_user(user, db).await?; | 101 | let events = Attendance::list_for_user(user, db).await?; |
| 93 | let sessions = SessionAttendance::list_for_user(user, db).await?; | 102 | let sessions = SessionAttendance::list_for_user(user, db).await?; |
| 94 | 103 | ||
| @@ -108,23 +117,35 @@ async fn build_report(user: &UserId, db: &Database) -> Result<AttendanceReport, | |||
| 108 | courses.iter().map(|c| (c.get_id().key(), c)).collect(); | 117 | courses.iter().map(|c| (c.get_id().key(), c)).collect(); |
| 109 | 118 | ||
| 110 | let mut blocks = Vec::with_capacity(course_ids.len()); | 119 | let mut blocks = Vec::with_capacity(course_ids.len()); |
| 120 | + let mut visible_rows: Vec<&SessionAttendance> = Vec::with_capacity(sessions.len()); | ||
| 111 | for course_id in &course_ids { | 121 | for course_id in &course_ids { |
| 112 | // A row whose course is gone cannot happen given the delete cascade — | 122 | // A row whose course is gone cannot happen given the delete cascade — |
| 113 | // skip defensively rather than fabricate a course block. | 123 | // skip defensively rather than fabricate a course block. |
| 114 | let Some(course) = course_by_key.get(course_id.key()) else { | 124 | let Some(course) = course_by_key.get(course_id.key()) else { |
| 115 | continue; | 125 | continue; |
| 116 | }; | 126 | }; |
| 127 | + if viewer.is_some_and(|viewer| !can_manage_course(course, viewer)) { | ||
| 128 | + continue; | ||
| 129 | + } | ||
| 117 | let rows = &by_course[course_id.key()]; | 130 | let rows = &by_course[course_id.key()]; |
| 131 | + visible_rows.extend(rows.iter().copied()); | ||
| 118 | blocks.push(CourseAttendance { | 132 | blocks.push(CourseAttendance { |
| 119 | course: CourseResponse::new(course), | 133 | course: CourseResponse::new(course), |
| 120 | counts: StatusCounts::tally(rows.iter().map(|r| r.get_status())), | 134 | counts: StatusCounts::tally(rows.iter().map(|r| r.get_status())), |
| 121 | }); | 135 | }); |
| 122 | } | 136 | } |
| 123 | 137 | ||
| 138 | + // A narrowed viewer's overall tally follows the visible blocks; a full | ||
| 139 | + // report keeps the historical every-row tally. | ||
| 140 | + let session_counts = match viewer { | ||
| 141 | + Some(_) => StatusCounts::tally(visible_rows.iter().map(|r| r.get_status())), | ||
| 142 | + None => StatusCounts::tally(sessions.iter().map(|a| a.get_status())), | ||
| 143 | + }; | ||
| 144 | + | ||
| 124 | Ok(AttendanceReport { | 145 | Ok(AttendanceReport { |
| 125 | user: user.key().to_string(), | 146 | user: user.key().to_string(), |
| 126 | events: StatusCounts::tally(events.iter().map(|a| a.get_status())), | 147 | events: StatusCounts::tally(events.iter().map(|a| a.get_status())), |
| 127 | - sessions: StatusCounts::tally(sessions.iter().map(|a| a.get_status())), | 148 | + sessions: session_counts, |
| 128 | courses: blocks, | 149 | courses: blocks, |
| 129 | }) | 150 | }) |
| 130 | } | 151 | } |
| @@ -145,10 +166,12 @@ async fn my_report( | |||
| 145 | State(st): State<AppState>, | 166 | State(st): State<AppState>, |
| 146 | CurrentUser(user): CurrentUser, | 167 | CurrentUser(user): CurrentUser, |
| 147 | ) -> Result<Json<AttendanceReport>, AppError> { | 168 | ) -> Result<Json<AttendanceReport>, AppError> { |
| 148 | - Ok(Json(build_report(user.get_id(), &st.db).await?)) | 169 | + Ok(Json(build_report(user.get_id(), None, &st.db).await?)) |
| 149 | } | 170 | } |
| 150 | 171 | ||
| 151 | -/// Any user's attendance report. Requires teacher+. | 172 | +/// Any user's attendance report. Requires teacher+. Managers and admins see |
| 173 | +/// every course; a teacher sees the event tallies plus only the roll-call | ||
| 174 | +/// blocks of the target's courses they manage. | ||
| 152 | #[utoipa::path( | 175 | #[utoipa::path( |
| 153 | get, | 176 | get, |
| 154 | path = "/{user}", | 177 | path = "/{user}", |
| @@ -156,7 +179,7 @@ async fn my_report( | |||
| 156 | security(("session_cookie" = [])), | 179 | security(("session_cookie" = [])), |
| 157 | params(("user" = String, Path, description = "User id")), | 180 | params(("user" = String, Path, description = "User id")), |
| 158 | responses( | 181 | responses( |
| 159 | - (status = 200, description = "The user's attendance report", body = AttendanceReport), | 182 | + (status = 200, description = "The user's attendance report, narrowed to the caller's courses", body = AttendanceReport), |
| 160 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 183 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 161 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 184 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 162 | (status = 404, description = "User not found", body = ErrorResponse), | 185 | (status = 404, description = "User not found", body = ErrorResponse), |
| @@ -164,7 +187,7 @@ async fn my_report( | |||
| 164 | )] | 187 | )] |
| 165 | async fn user_report( | 188 | async fn user_report( |
| 166 | State(st): State<AppState>, | 189 | State(st): State<AppState>, |
| 167 | - _teacher: RequireTeacher, | 190 | + RequireTeacher(teacher): RequireTeacher, |
| 168 | Path(user): Path<String>, | 191 | Path(user): Path<String>, |
| 169 | ) -> Result<Json<AttendanceReport>, AppError> { | 192 | ) -> Result<Json<AttendanceReport>, AppError> { |
| 170 | let target = UserId::from_key(&user); | 193 | let target = UserId::from_key(&user); |
| @@ -172,7 +195,8 @@ async fn user_report( | |||
| 172 | User::read(&target, &st.db) | 195 | User::read(&target, &st.db) |
| 173 | .await? | 196 | .await? |
| 174 | .ok_or(AppError::NotFound)?; | 197 | .ok_or(AppError::NotFound)?; |
| 175 | - Ok(Json(build_report(&target, &st.db).await?)) | 198 | + let viewer = (!teacher.get_role().at_least(Role::Manager)).then_some(&teacher); |
| 199 | + Ok(Json(build_report(&target, viewer, &st.db).await?)) | ||
| 176 | } | 200 | } |
| 177 | 201 | ||
| 178 | #[cfg(test)] | 202 | #[cfg(test)] |
src/web/courses.rsmodified+86 -23
| @@ -8,6 +8,7 @@ use utoipa::ToSchema; | |||
| 8 | use utoipa_axum::router::OpenApiRouter; | 8 | use utoipa_axum::router::OpenApiRouter; |
| 9 | use utoipa_axum::routes; | 9 | use utoipa_axum::routes; |
| 10 | 10 | ||
| 11 | +use crate::database::Database; | ||
| 11 | use crate::domain::course::{Course, CourseDescription, CourseId, CourseTitle}; | 12 | use crate::domain::course::{Course, CourseDescription, CourseId, CourseTitle}; |
| 12 | use crate::domain::course_session::{CourseSession, SessionTopic}; | 13 | use crate::domain::course_session::{CourseSession, SessionTopic}; |
| 13 | use crate::domain::enrollment::Enrollment; | 14 | use crate::domain::enrollment::Enrollment; |
| @@ -115,6 +116,44 @@ pub(crate) fn can_manage_course(course: &Course, user: &User) -> bool { | |||
| 115 | course.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager) | 116 | course.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager) |
| 116 | } | 117 | } |
| 117 | 118 | ||
| 119 | +/// Who may read inside a specific course (its details, exams, sessions): | ||
| 120 | +/// anyone who can manage it, plus its enrolled users. Other teachers and | ||
| 121 | +/// unenrolled students see nothing. | ||
| 122 | +pub(crate) async fn can_view_course( | ||
| 123 | + course: &Course, | ||
| 124 | + user: &User, | ||
| 125 | + db: &Database, | ||
| 126 | +) -> Result<bool, AppError> { | ||
| 127 | + if can_manage_course(course, user) { | ||
| 128 | + return Ok(true); | ||
| 129 | + } | ||
| 130 | + Ok( | ||
| 131 | + Enrollment::read_for_user(course.get_id(), user.get_id(), db) | ||
| 132 | + .await? | ||
| 133 | + .is_some(), | ||
| 134 | + ) | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +/// The catalog as one user sees it: every course for manager+, otherwise the | ||
| 138 | +/// courses they created plus the ones they're enrolled in, newest first. | ||
| 139 | +pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Course>, AppError> { | ||
| 140 | + if user.get_role().at_least(Role::Manager) { | ||
| 141 | + return Course::list_all(db).await; | ||
| 142 | + } | ||
| 143 | + let mut courses = Course::list_created(user.get_id(), db).await?; | ||
| 144 | + for course in Course::list_enrolled(user.get_id(), db).await? { | ||
| 145 | + if !courses | ||
| 146 | + .iter() | ||
| 147 | + .any(|known| known.get_id() == course.get_id()) | ||
| 148 | + { | ||
| 149 | + courses.push(course); | ||
| 150 | + } | ||
| 151 | + } | ||
| 152 | + // Both sources come newest-first; re-sort so the merged list is too. | ||
| 153 | + courses.sort_by(|a, b| b.get_id().key().cmp(a.get_id().key())); | ||
| 154 | + Ok(courses) | ||
| 155 | +} | ||
| 156 | + | ||
| 118 | // ---- courses ------------------------------------------------------------ | 157 | // ---- courses ------------------------------------------------------------ |
| 119 | 158 | ||
| 120 | /// Create a course owned by the current user. Requires the `teacher` role or higher. | 159 | /// Create a course owned by the current user. Requires the `teacher` role or higher. |
| @@ -142,22 +181,23 @@ async fn create_course( | |||
| 142 | Ok((StatusCode::CREATED, Json(CourseResponse::new(&course)))) | 181 | Ok((StatusCode::CREATED, Json(CourseResponse::new(&course)))) |
| 143 | } | 182 | } |
| 144 | 183 | ||
| 145 | -/// List all courses. | 184 | +/// List the courses visible to the caller: every course for manager+, |
| 185 | +/// otherwise the courses they created plus the ones they're enrolled in. | ||
| 146 | #[utoipa::path( | 186 | #[utoipa::path( |
| 147 | get, | 187 | get, |
| 148 | path = "/", | 188 | path = "/", |
| 149 | tag = "courses", | 189 | tag = "courses", |
| 150 | security(("session_cookie" = [])), | 190 | security(("session_cookie" = [])), |
| 151 | responses( | 191 | responses( |
| 152 | - (status = 200, description = "All courses", body = [CourseResponse]), | 192 | + (status = 200, description = "The caller's visible courses", body = [CourseResponse]), |
| 153 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 193 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 154 | ), | 194 | ), |
| 155 | )] | 195 | )] |
| 156 | async fn list_courses( | 196 | async fn list_courses( |
| 157 | State(st): State<AppState>, | 197 | State(st): State<AppState>, |
| 158 | - _user: CurrentUser, | 198 | + CurrentUser(user): CurrentUser, |
| 159 | ) -> Result<Json<Vec<CourseResponse>>, AppError> { | 199 | ) -> Result<Json<Vec<CourseResponse>>, AppError> { |
| 160 | - let courses = Course::list_all(&st.db).await?; | 200 | + let courses = visible_courses(&user, &st.db).await?; |
| 161 | Ok(Json(courses.iter().map(CourseResponse::new).collect())) | 201 | Ok(Json(courses.iter().map(CourseResponse::new).collect())) |
| 162 | } | 202 | } |
| 163 | 203 | ||
| @@ -180,7 +220,8 @@ async fn my_courses( | |||
| 180 | Ok(Json(courses.iter().map(CourseResponse::new).collect())) | 220 | Ok(Json(courses.iter().map(CourseResponse::new).collect())) |
| 181 | } | 221 | } |
| 182 | 222 | ||
| 183 | -/// Fetch a single course by id. | 223 | +/// Fetch a single course by id. Visible to its enrolled users, its creator, |
| 224 | +/// and managers/admins. | ||
| 184 | #[utoipa::path( | 225 | #[utoipa::path( |
| 185 | get, | 226 | get, |
| 186 | path = "/{id}", | 227 | path = "/{id}", |
| @@ -190,17 +231,23 @@ async fn my_courses( | |||
| 190 | responses( | 231 | responses( |
| 191 | (status = 200, description = "The course", body = CourseResponse), | 232 | (status = 200, description = "The course", body = CourseResponse), |
| 192 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 233 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 234 | + (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse), | ||
| 193 | (status = 404, description = "Not found", body = ErrorResponse), | 235 | (status = 404, description = "Not found", body = ErrorResponse), |
| 194 | ), | 236 | ), |
| 195 | )] | 237 | )] |
| 196 | async fn get_course( | 238 | async fn get_course( |
| 197 | State(st): State<AppState>, | 239 | State(st): State<AppState>, |
| 198 | - _user: CurrentUser, | 240 | + CurrentUser(user): CurrentUser, |
| 199 | Path(id): Path<String>, | 241 | Path(id): Path<String>, |
| 200 | ) -> Result<Json<CourseResponse>, AppError> { | 242 | ) -> Result<Json<CourseResponse>, AppError> { |
| 201 | let course = Course::read(&CourseId::from_key(&id), &st.db) | 243 | let course = Course::read(&CourseId::from_key(&id), &st.db) |
| 202 | .await? | 244 | .await? |
| 203 | .ok_or(AppError::NotFound)?; | 245 | .ok_or(AppError::NotFound)?; |
| 246 | + if !can_view_course(&course, &user, &st.db).await? { | ||
| 247 | + return Err(AppError::Forbidden( | ||
| 248 | + "only enrolled users, the course creator, or a manager/admin can view this course", | ||
| 249 | + )); | ||
| 250 | + } | ||
| 204 | Ok(Json(CourseResponse::new(&course))) | 251 | Ok(Json(CourseResponse::new(&course))) |
| 205 | } | 252 | } |
| 206 | 253 | ||
| @@ -329,8 +376,8 @@ async fn enroll( | |||
| 329 | Ok(Json(EnrollmentResponse::new(&enrollment, &people))) | 376 | Ok(Json(EnrollmentResponse::new(&enrollment, &people))) |
| 330 | } | 377 | } |
| 331 | 378 | ||
| 332 | -/// List a course's roster. Requires teacher+ — students see their own courses | 379 | +/// List a course's roster. Requires teacher+ and course management rights — |
| 333 | -/// via `GET /courses/me`. | 380 | +/// students see their own courses via `GET /courses/me`. |
| 334 | #[utoipa::path( | 381 | #[utoipa::path( |
| 335 | get, | 382 | get, |
| 336 | path = "/{id}/enrollments", | 383 | path = "/{id}/enrollments", |
| @@ -340,21 +387,25 @@ async fn enroll( | |||
| 340 | responses( | 387 | responses( |
| 341 | (status = 200, description = "All enrollments", body = [EnrollmentResponse]), | 388 | (status = 200, description = "All enrollments", body = [EnrollmentResponse]), |
| 342 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 389 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 343 | - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 390 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 344 | (status = 404, description = "Course not found", body = ErrorResponse), | 391 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 345 | ), | 392 | ), |
| 346 | )] | 393 | )] |
| 347 | async fn list_roster( | 394 | async fn list_roster( |
| 348 | State(st): State<AppState>, | 395 | State(st): State<AppState>, |
| 349 | - _teacher: RequireTeacher, | 396 | + RequireTeacher(user): RequireTeacher, |
| 350 | Path(id): Path<String>, | 397 | Path(id): Path<String>, |
| 351 | ) -> Result<Json<Vec<EnrollmentResponse>>, AppError> { | 398 | ) -> Result<Json<Vec<EnrollmentResponse>>, AppError> { |
| 352 | - let course_id = CourseId::from_key(&id); | ||
| 353 | // Course must exist — a missing course is a 404, not an empty roster. | 399 | // Course must exist — a missing course is a 404, not an empty roster. |
| 354 | - Course::read(&course_id, &st.db) | 400 | + let course = Course::read(&CourseId::from_key(&id), &st.db) |
| 355 | .await? | 401 | .await? |
| 356 | .ok_or(AppError::NotFound)?; | 402 | .ok_or(AppError::NotFound)?; |
| 357 | - let enrollments = Enrollment::list_for_course(&course_id, &st.db).await?; | 403 | + if !can_manage_course(&course, &user) { |
| 404 | + return Err(AppError::Forbidden( | ||
| 405 | + "only the course creator or a manager/admin can list the roster", | ||
| 406 | + )); | ||
| 407 | + } | ||
| 408 | + let enrollments = Enrollment::list_for_course(course.get_id(), &st.db).await?; | ||
| 358 | let people = person_map( | 409 | let people = person_map( |
| 359 | enrollments | 410 | enrollments |
| 360 | .iter() | 411 | .iter() |
| @@ -471,7 +522,8 @@ async fn create_exam_in_course( | |||
| 471 | Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam)))) | 522 | Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam)))) |
| 472 | } | 523 | } |
| 473 | 524 | ||
| 474 | -/// List a course's exams. | 525 | +/// List a course's exams. Visible to the course's enrolled users, its |
| 526 | +/// creator, and managers/admins. | ||
| 475 | #[utoipa::path( | 527 | #[utoipa::path( |
| 476 | get, | 528 | get, |
| 477 | path = "/{id}/exams", | 529 | path = "/{id}/exams", |
| @@ -481,20 +533,25 @@ async fn create_exam_in_course( | |||
| 481 | responses( | 533 | responses( |
| 482 | (status = 200, description = "The course's exams", body = [ExamResponse]), | 534 | (status = 200, description = "The course's exams", body = [ExamResponse]), |
| 483 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 535 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 536 | + (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse), | ||
| 484 | (status = 404, description = "Course not found", body = ErrorResponse), | 537 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 485 | ), | 538 | ), |
| 486 | )] | 539 | )] |
| 487 | async fn list_course_exams( | 540 | async fn list_course_exams( |
| 488 | State(st): State<AppState>, | 541 | State(st): State<AppState>, |
| 489 | - _user: CurrentUser, | 542 | + CurrentUser(user): CurrentUser, |
| 490 | Path(id): Path<String>, | 543 | Path(id): Path<String>, |
| 491 | ) -> Result<Json<Vec<ExamResponse>>, AppError> { | 544 | ) -> Result<Json<Vec<ExamResponse>>, AppError> { |
| 492 | - let course_id = CourseId::from_key(&id); | ||
| 493 | // Course must exist — a missing course is a 404, not an empty exam list. | 545 | // Course must exist — a missing course is a 404, not an empty exam list. |
| 494 | - Course::read(&course_id, &st.db) | 546 | + let course = Course::read(&CourseId::from_key(&id), &st.db) |
| 495 | .await? | 547 | .await? |
| 496 | .ok_or(AppError::NotFound)?; | 548 | .ok_or(AppError::NotFound)?; |
| 497 | - let exams = Exam::list_for_course(&course_id, &st.db).await?; | 549 | + if !can_view_course(&course, &user, &st.db).await? { |
| 550 | + return Err(AppError::Forbidden( | ||
| 551 | + "only enrolled users, the course creator, or a manager/admin can view this course", | ||
| 552 | + )); | ||
| 553 | + } | ||
| 554 | + let exams = Exam::list_for_course(course.get_id(), &st.db).await?; | ||
| 498 | Ok(Json(exams.iter().map(ExamResponse::new).collect())) | 555 | Ok(Json(exams.iter().map(ExamResponse::new).collect())) |
| 499 | } | 556 | } |
| 500 | 557 | ||
| @@ -572,7 +629,8 @@ async fn create_session_in_course( | |||
| 572 | )) | 629 | )) |
| 573 | } | 630 | } |
| 574 | 631 | ||
| 575 | -/// List a course's lesson sessions, most recent first. | 632 | +/// List a course's lesson sessions, most recent first. Visible to the |
| 633 | +/// course's enrolled users, its creator, and managers/admins. | ||
| 576 | #[utoipa::path( | 634 | #[utoipa::path( |
| 577 | get, | 635 | get, |
| 578 | path = "/{id}/sessions", | 636 | path = "/{id}/sessions", |
| @@ -582,20 +640,25 @@ async fn create_session_in_course( | |||
| 582 | responses( | 640 | responses( |
| 583 | (status = 200, description = "The course's sessions", body = [SessionResponse]), | 641 | (status = 200, description = "The course's sessions", body = [SessionResponse]), |
| 584 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 642 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 643 | + (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse), | ||
| 585 | (status = 404, description = "Course not found", body = ErrorResponse), | 644 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 586 | ), | 645 | ), |
| 587 | )] | 646 | )] |
| 588 | async fn list_course_sessions( | 647 | async fn list_course_sessions( |
| 589 | State(st): State<AppState>, | 648 | State(st): State<AppState>, |
| 590 | - _user: CurrentUser, | 649 | + CurrentUser(user): CurrentUser, |
| 591 | Path(id): Path<String>, | 650 | Path(id): Path<String>, |
| 592 | ) -> Result<Json<Vec<SessionResponse>>, AppError> { | 651 | ) -> Result<Json<Vec<SessionResponse>>, AppError> { |
| 593 | - let course_id = CourseId::from_key(&id); | ||
| 594 | // Course must exist — a missing course is a 404, not an empty list. | 652 | // Course must exist — a missing course is a 404, not an empty list. |
| 595 | - Course::read(&course_id, &st.db) | 653 | + let course = Course::read(&CourseId::from_key(&id), &st.db) |
| 596 | .await? | 654 | .await? |
| 597 | .ok_or(AppError::NotFound)?; | 655 | .ok_or(AppError::NotFound)?; |
| 598 | - let sessions = CourseSession::list_for_course(&course_id, &st.db).await?; | 656 | + if !can_view_course(&course, &user, &st.db).await? { |
| 657 | + return Err(AppError::Forbidden( | ||
| 658 | + "only enrolled users, the course creator, or a manager/admin can view this course", | ||
| 659 | + )); | ||
| 660 | + } | ||
| 661 | + let sessions = CourseSession::list_for_course(course.get_id(), &st.db).await?; | ||
| 599 | let people = person_map(sessions.iter().map(|s| s.get_teacher().clone()), &st.db).await?; | 662 | let people = person_map(sessions.iter().map(|s| s.get_teacher().clone()), &st.db).await?; |
| 600 | Ok(Json( | 663 | Ok(Json( |
| 601 | sessions | 664 | sessions |
src/web/events.rsmodified+4 -2
| @@ -359,7 +359,8 @@ async fn mark( | |||
| 359 | Ok(Json(AttendanceResponse::new(&attendance, &people))) | 359 | Ok(Json(AttendanceResponse::new(&attendance, &people))) |
| 360 | } | 360 | } |
| 361 | 361 | ||
| 362 | -/// List the attendance roster for an event. | 362 | +/// List the attendance roster for an event. Requires teacher+ — students see |
| 363 | +/// their own tallies via `GET /attendance/me`. | ||
| 363 | #[utoipa::path( | 364 | #[utoipa::path( |
| 364 | get, | 365 | get, |
| 365 | path = "/{id}/attendance", | 366 | path = "/{id}/attendance", |
| @@ -369,12 +370,13 @@ async fn mark( | |||
| 369 | responses( | 370 | responses( |
| 370 | (status = 200, description = "Attendance roster", body = [AttendanceResponse]), | 371 | (status = 200, description = "Attendance roster", body = [AttendanceResponse]), |
| 371 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 372 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 373 | + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | ||
| 372 | (status = 404, description = "Event not found", body = ErrorResponse), | 374 | (status = 404, description = "Event not found", body = ErrorResponse), |
| 373 | ), | 375 | ), |
| 374 | )] | 376 | )] |
| 375 | async fn list_attendance( | 377 | async fn list_attendance( |
| 376 | State(st): State<AppState>, | 378 | State(st): State<AppState>, |
| 377 | - _user: CurrentUser, | 379 | + _teacher: RequireTeacher, |
| 378 | Path(id): Path<String>, | 380 | Path(id): Path<String>, |
| 379 | ) -> Result<Json<Vec<AttendanceResponse>>, AppError> { | 381 | ) -> Result<Json<Vec<AttendanceResponse>>, AppError> { |
| 380 | let event_id = EventId::from_key(&id); | 382 | let event_id = EventId::from_key(&id); |
src/web/exams.rsmodified+96 -41
| @@ -26,12 +26,13 @@ use crate::domain::exam_question::{ | |||
| 26 | ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, | 26 | ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, |
| 27 | }; | 27 | }; |
| 28 | use crate::domain::exam_result::{ExamResult, Mark}; | 28 | use crate::domain::exam_result::{ExamResult, Mark}; |
| 29 | +use crate::domain::role::Role; | ||
| 29 | use crate::domain::timestamp::Timestamp; | 30 | use crate::domain::timestamp::Timestamp; |
| 30 | use crate::domain::user::{User, UserId}; | 31 | use crate::domain::user::{User, UserId}; |
| 31 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 32 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 32 | use crate::state::AppState; | 33 | use crate::state::AppState; |
| 33 | 34 | ||
| 34 | -use super::courses::can_manage_course; | 35 | +use super::courses::{can_manage_course, can_view_course, visible_courses}; |
| 35 | use super::{ | 36 | use super::{ |
| 36 | CurrentUser, ExamResponse, PersonRef, RequireTeacher, check_not_past, person_map, set_or_clear, | 37 | CurrentUser, ExamResponse, PersonRef, RequireTeacher, check_not_past, person_map, set_or_clear, |
| 37 | }; | 38 | }; |
| @@ -146,26 +147,34 @@ async fn course_of(exam: &Exam, db: &Database) -> Result<Course, AppError> { | |||
| 146 | // ---- exams -------------------------------------------------------------- | 147 | // ---- exams -------------------------------------------------------------- |
| 147 | // Exams are created inside a course: `POST /courses/{id}/exams`. | 148 | // Exams are created inside a course: `POST /courses/{id}/exams`. |
| 148 | 149 | ||
| 149 | -/// List all exams. | 150 | +/// List the exams visible to the caller: every exam for manager+, otherwise |
| 151 | +/// the exams of the courses they created or are enrolled in. | ||
| 150 | #[utoipa::path( | 152 | #[utoipa::path( |
| 151 | get, | 153 | get, |
| 152 | path = "/", | 154 | path = "/", |
| 153 | tag = "exams", | 155 | tag = "exams", |
| 154 | security(("session_cookie" = [])), | 156 | security(("session_cookie" = [])), |
| 155 | responses( | 157 | responses( |
| 156 | - (status = 200, description = "All exams", body = [ExamResponse]), | 158 | + (status = 200, description = "The caller's visible exams", body = [ExamResponse]), |
| 157 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 159 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 158 | ), | 160 | ), |
| 159 | )] | 161 | )] |
| 160 | async fn list_exams( | 162 | async fn list_exams( |
| 161 | State(st): State<AppState>, | 163 | State(st): State<AppState>, |
| 162 | - _user: CurrentUser, | 164 | + CurrentUser(user): CurrentUser, |
| 163 | ) -> Result<Json<Vec<ExamResponse>>, AppError> { | 165 | ) -> Result<Json<Vec<ExamResponse>>, AppError> { |
| 164 | - let exams = Exam::list_all(&st.db).await?; | 166 | + let exams = if user.get_role().at_least(Role::Manager) { |
| 167 | + Exam::list_all(&st.db).await? | ||
| 168 | + } else { | ||
| 169 | + let courses = visible_courses(&user, &st.db).await?; | ||
| 170 | + let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect(); | ||
| 171 | + Exam::list_for_courses(&ids, &st.db).await? | ||
| 172 | + }; | ||
| 165 | Ok(Json(exams.iter().map(ExamResponse::new).collect())) | 173 | Ok(Json(exams.iter().map(ExamResponse::new).collect())) |
| 166 | } | 174 | } |
| 167 | 175 | ||
| 168 | -/// Fetch a single exam by id. | 176 | +/// Fetch a single exam by id. Visible to its course's enrolled users, the |
| 177 | +/// course creator, and managers/admins. | ||
| 169 | #[utoipa::path( | 178 | #[utoipa::path( |
| 170 | get, | 179 | get, |
| 171 | path = "/{id}", | 180 | path = "/{id}", |
| @@ -175,17 +184,24 @@ async fn list_exams( | |||
| 175 | responses( | 184 | responses( |
| 176 | (status = 200, description = "The exam", body = ExamResponse), | 185 | (status = 200, description = "The exam", body = ExamResponse), |
| 177 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 186 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 187 | + (status = 403, description = "Not enrolled in the exam's course, not its creator, and not a manager/admin", body = ErrorResponse), | ||
| 178 | (status = 404, description = "Not found", body = ErrorResponse), | 188 | (status = 404, description = "Not found", body = ErrorResponse), |
| 179 | ), | 189 | ), |
| 180 | )] | 190 | )] |
| 181 | async fn get_exam( | 191 | async fn get_exam( |
| 182 | State(st): State<AppState>, | 192 | State(st): State<AppState>, |
| 183 | - _user: CurrentUser, | 193 | + CurrentUser(user): CurrentUser, |
| 184 | Path(id): Path<String>, | 194 | Path(id): Path<String>, |
| 185 | ) -> Result<Json<ExamResponse>, AppError> { | 195 | ) -> Result<Json<ExamResponse>, AppError> { |
| 186 | let exam = Exam::read(&ExamId::from_key(&id), &st.db) | 196 | let exam = Exam::read(&ExamId::from_key(&id), &st.db) |
| 187 | .await? | 197 | .await? |
| 188 | .ok_or(AppError::NotFound)?; | 198 | .ok_or(AppError::NotFound)?; |
| 199 | + let course = course_of(&exam, &st.db).await?; | ||
| 200 | + if !can_view_course(&course, &user, &st.db).await? { | ||
| 201 | + return Err(AppError::Forbidden( | ||
| 202 | + "only enrolled users, the course creator, or a manager/admin can view this exam", | ||
| 203 | + )); | ||
| 204 | + } | ||
| 189 | Ok(Json(ExamResponse::new(&exam))) | 205 | Ok(Json(ExamResponse::new(&exam))) |
| 190 | } | 206 | } |
| 191 | 207 | ||
| @@ -397,8 +413,9 @@ async fn grade( | |||
| 397 | Ok(Json(ExamResultResponse::new(&result, &people))) | 413 | Ok(Json(ExamResultResponse::new(&result, &people))) |
| 398 | } | 414 | } |
| 399 | 415 | ||
| 400 | -/// List every result for an exam. Requires teacher+ — students read only their | 416 | +/// List every result for an exam. Requires teacher+ and management rights |
| 401 | -/// own via `GET /exams/{id}/result`. | 417 | +/// over the exam's course — students read only their own via |
| 418 | +/// `GET /exams/{id}/result`. | ||
| 402 | #[utoipa::path( | 419 | #[utoipa::path( |
| 403 | get, | 420 | get, |
| 404 | path = "/{id}/results", | 421 | path = "/{id}/results", |
| @@ -408,21 +425,26 @@ async fn grade( | |||
| 408 | responses( | 425 | responses( |
| 409 | (status = 200, description = "All results", body = [ExamResultResponse]), | 426 | (status = 200, description = "All results", body = [ExamResultResponse]), |
| 410 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 427 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 411 | - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 428 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 412 | (status = 404, description = "Exam not found", body = ErrorResponse), | 429 | (status = 404, description = "Exam not found", body = ErrorResponse), |
| 413 | ), | 430 | ), |
| 414 | )] | 431 | )] |
| 415 | async fn list_results( | 432 | async fn list_results( |
| 416 | State(st): State<AppState>, | 433 | State(st): State<AppState>, |
| 417 | - _teacher: RequireTeacher, | 434 | + RequireTeacher(user): RequireTeacher, |
| 418 | Path(id): Path<String>, | 435 | Path(id): Path<String>, |
| 419 | ) -> Result<Json<Vec<ExamResultResponse>>, AppError> { | 436 | ) -> Result<Json<Vec<ExamResultResponse>>, AppError> { |
| 420 | - let exam_id = ExamId::from_key(&id); | ||
| 421 | // Exam must exist — a missing exam is a 404, not an empty result list. | 437 | // Exam must exist — a missing exam is a 404, not an empty result list. |
| 422 | - Exam::read(&exam_id, &st.db) | 438 | + let exam = Exam::read(&ExamId::from_key(&id), &st.db) |
| 423 | .await? | 439 | .await? |
| 424 | .ok_or(AppError::NotFound)?; | 440 | .ok_or(AppError::NotFound)?; |
| 425 | - let results = ExamResult::list_for_exam(&exam_id, &st.db).await?; | 441 | + let course = course_of(&exam, &st.db).await?; |
| 442 | + if !can_manage_course(&course, &user) { | ||
| 443 | + return Err(AppError::Forbidden( | ||
| 444 | + "only the course creator or a manager/admin can list results", | ||
| 445 | + )); | ||
| 446 | + } | ||
| 447 | + let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?; | ||
| 426 | let people = person_map( | 448 | let people = person_map( |
| 427 | results | 449 | results |
| 428 | .iter() | 450 | .iter() |
| @@ -507,7 +529,8 @@ async fn remove_result( | |||
| 507 | Ok(StatusCode::NO_CONTENT) | 529 | Ok(StatusCode::NO_CONTENT) |
| 508 | } | 530 | } |
| 509 | 531 | ||
| 510 | -/// Summary statistics for an exam's graded results. Requires teacher+. | 532 | +/// Summary statistics for an exam's graded results. Requires teacher+ and |
| 533 | +/// management rights over the exam's course. | ||
| 511 | #[utoipa::path( | 534 | #[utoipa::path( |
| 512 | get, | 535 | get, |
| 513 | path = "/{id}/statistics", | 536 | path = "/{id}/statistics", |
| @@ -517,27 +540,32 @@ async fn remove_result( | |||
| 517 | responses( | 540 | responses( |
| 518 | (status = 200, description = "The exam's mark statistics", body = ExamStatisticsResponse), | 541 | (status = 200, description = "The exam's mark statistics", body = ExamStatisticsResponse), |
| 519 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 542 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 520 | - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 543 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 521 | (status = 404, description = "Exam not found", body = ErrorResponse), | 544 | (status = 404, description = "Exam not found", body = ErrorResponse), |
| 522 | ), | 545 | ), |
| 523 | )] | 546 | )] |
| 524 | async fn exam_statistics( | 547 | async fn exam_statistics( |
| 525 | State(st): State<AppState>, | 548 | State(st): State<AppState>, |
| 526 | - _teacher: RequireTeacher, | 549 | + RequireTeacher(user): RequireTeacher, |
| 527 | Path(id): Path<String>, | 550 | Path(id): Path<String>, |
| 528 | ) -> Result<Json<ExamStatisticsResponse>, AppError> { | 551 | ) -> Result<Json<ExamStatisticsResponse>, AppError> { |
| 529 | - let exam_id = ExamId::from_key(&id); | ||
| 530 | // Exam must exist — a missing exam is a 404, not an empty statistic. | 552 | // Exam must exist — a missing exam is a 404, not an empty statistic. |
| 531 | - Exam::read(&exam_id, &st.db) | 553 | + let exam = Exam::read(&ExamId::from_key(&id), &st.db) |
| 532 | .await? | 554 | .await? |
| 533 | .ok_or(AppError::NotFound)?; | 555 | .ok_or(AppError::NotFound)?; |
| 534 | - let results = ExamResult::list_for_exam(&exam_id, &st.db).await?; | 556 | + let course = course_of(&exam, &st.db).await?; |
| 557 | + if !can_manage_course(&course, &user) { | ||
| 558 | + return Err(AppError::Forbidden( | ||
| 559 | + "only the course creator or a manager/admin can view statistics", | ||
| 560 | + )); | ||
| 561 | + } | ||
| 562 | + let results = ExamResult::list_for_exam(exam.get_id(), &st.db).await?; | ||
| 535 | 563 | ||
| 536 | let marks: Vec<i64> = results.iter().map(|r| r.get_mark().as_i64()).collect(); | 564 | let marks: Vec<i64> = results.iter().map(|r| r.get_mark().as_i64()).collect(); |
| 537 | let average = | 565 | let average = |
| 538 | (!marks.is_empty()).then(|| marks.iter().sum::<i64>() as f64 / marks.len() as f64); | 566 | (!marks.is_empty()).then(|| marks.iter().sum::<i64>() as f64 / marks.len() as f64); |
| 539 | Ok(Json(ExamStatisticsResponse { | 567 | Ok(Json(ExamStatisticsResponse { |
| 540 | - exam: exam_id.key().to_string(), | 568 | + exam: exam.get_id().key().to_string(), |
| 541 | graded: marks.len() as u64, | 569 | graded: marks.len() as u64, |
| 542 | average, | 570 | average, |
| 543 | min: marks.iter().min().copied(), | 571 | min: marks.iter().min().copied(), |
| @@ -929,8 +957,9 @@ async fn live_snapshot(exam: &Exam, db: &Database) -> Result<ExamLiveResponse, A | |||
| 929 | } | 957 | } |
| 930 | 958 | ||
| 931 | /// A one-shot live snapshot of the exam: who's in, who's still writing, time | 959 | /// A one-shot live snapshot of the exam: who's in, who's still writing, time |
| 932 | -/// each student has left, and marks as they land. Requires teacher+. For a | 960 | +/// each student has left, and marks as they land. Requires teacher+ and |
| 933 | -/// self-updating feed of the same shape, see `GET /exams/{id}/live/stream`. | 961 | +/// management rights over the exam's course. For a self-updating feed of the |
| 962 | +/// same shape, see `GET /exams/{id}/live/stream`. | ||
| 934 | #[utoipa::path( | 963 | #[utoipa::path( |
| 935 | get, | 964 | get, |
| 936 | path = "/{id}/live", | 965 | path = "/{id}/live", |
| @@ -940,27 +969,34 @@ async fn live_snapshot(exam: &Exam, db: &Database) -> Result<ExamLiveResponse, A | |||
| 940 | responses( | 969 | responses( |
| 941 | (status = 200, description = "Live snapshot", body = ExamLiveResponse), | 970 | (status = 200, description = "Live snapshot", body = ExamLiveResponse), |
| 942 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 971 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 943 | - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 972 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 944 | (status = 404, description = "Exam not found", body = ErrorResponse), | 973 | (status = 404, description = "Exam not found", body = ErrorResponse), |
| 945 | ), | 974 | ), |
| 946 | )] | 975 | )] |
| 947 | async fn exam_live( | 976 | async fn exam_live( |
| 948 | State(st): State<AppState>, | 977 | State(st): State<AppState>, |
| 949 | - _teacher: RequireTeacher, | 978 | + RequireTeacher(user): RequireTeacher, |
| 950 | Path(id): Path<String>, | 979 | Path(id): Path<String>, |
| 951 | ) -> Result<Json<ExamLiveResponse>, AppError> { | 980 | ) -> Result<Json<ExamLiveResponse>, AppError> { |
| 952 | let exam = Exam::read(&ExamId::from_key(&id), &st.db) | 981 | let exam = Exam::read(&ExamId::from_key(&id), &st.db) |
| 953 | .await? | 982 | .await? |
| 954 | .ok_or(AppError::NotFound)?; | 983 | .ok_or(AppError::NotFound)?; |
| 984 | + let course = course_of(&exam, &st.db).await?; | ||
| 985 | + if !can_manage_course(&course, &user) { | ||
| 986 | + return Err(AppError::Forbidden( | ||
| 987 | + "only the course creator or a manager/admin can monitor this exam", | ||
| 988 | + )); | ||
| 989 | + } | ||
| 955 | Ok(Json(live_snapshot(&exam, &st.db).await?)) | 990 | Ok(Json(live_snapshot(&exam, &st.db).await?)) |
| 956 | } | 991 | } |
| 957 | 992 | ||
| 958 | /// The live snapshot as a Server-Sent-Events stream: one `snapshot` event | 993 | /// The live snapshot as a Server-Sent-Events stream: one `snapshot` event |
| 959 | /// (the `ExamLiveResponse` JSON) immediately on connect and then every couple | 994 | /// (the `ExamLiveResponse` JSON) immediately on connect and then every couple |
| 960 | /// of seconds, so attendance, remaining time, submissions, and marks update | 995 | /// of seconds, so attendance, remaining time, submissions, and marks update |
| 961 | -/// without polling. Requires teacher+. Consume with `EventSource` (cookies | 996 | +/// without polling. Requires teacher+ and management rights over the exam's |
| 962 | -/// ride along on same-site / credentialed requests). If the exam disappears | 997 | +/// course. Consume with `EventSource` (cookies ride along on same-site / |
| 963 | -/// mid-stream an `error` event is sent instead. | 998 | +/// credentialed requests). If the exam disappears mid-stream an `error` event |
| 999 | +/// is sent instead. | ||
| 964 | #[utoipa::path( | 1000 | #[utoipa::path( |
| 965 | get, | 1001 | get, |
| 966 | path = "/{id}/live/stream", | 1002 | path = "/{id}/live/stream", |
| @@ -970,20 +1006,26 @@ async fn exam_live( | |||
| 970 | responses( | 1006 | responses( |
| 971 | (status = 200, description = "SSE feed of `snapshot` events (`ExamLiveResponse` as JSON)", content_type = "text/event-stream"), | 1007 | (status = 200, description = "SSE feed of `snapshot` events (`ExamLiveResponse` as JSON)", content_type = "text/event-stream"), |
| 972 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 1008 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 973 | - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 1009 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 974 | (status = 404, description = "Exam not found", body = ErrorResponse), | 1010 | (status = 404, description = "Exam not found", body = ErrorResponse), |
| 975 | ), | 1011 | ), |
| 976 | )] | 1012 | )] |
| 977 | async fn exam_live_stream( | 1013 | async fn exam_live_stream( |
| 978 | State(st): State<AppState>, | 1014 | State(st): State<AppState>, |
| 979 | - _teacher: RequireTeacher, | 1015 | + RequireTeacher(user): RequireTeacher, |
| 980 | Path(id): Path<String>, | 1016 | Path(id): Path<String>, |
| 981 | ) -> Result<Sse<impl Stream<Item = Result<Event, axum::Error>>>, AppError> { | 1017 | ) -> Result<Sse<impl Stream<Item = Result<Event, axum::Error>>>, AppError> { |
| 982 | let exam_id = ExamId::from_key(&id); | 1018 | let exam_id = ExamId::from_key(&id); |
| 983 | // A missing exam is a 404 up front; after this the response is a stream. | 1019 | // A missing exam is a 404 up front; after this the response is a stream. |
| 984 | - Exam::read(&exam_id, &st.db) | 1020 | + let exam = Exam::read(&exam_id, &st.db) |
| 985 | .await? | 1021 | .await? |
| 986 | .ok_or(AppError::NotFound)?; | 1022 | .ok_or(AppError::NotFound)?; |
| 1023 | + let course = course_of(&exam, &st.db).await?; | ||
| 1024 | + if !can_manage_course(&course, &user) { | ||
| 1025 | + return Err(AppError::Forbidden( | ||
| 1026 | + "only the course creator or a manager/admin can monitor this exam", | ||
| 1027 | + )); | ||
| 1028 | + } | ||
| 987 | 1029 | ||
| 988 | // First tick fires immediately, so the monitor paints on connect. The | 1030 | // First tick fires immediately, so the monitor paints on connect. The |
| 989 | // exam is re-read every tick: schedule edits (deadline extensions) show | 1031 | // exam is re-read every tick: schedule edits (deadline extensions) show |
| @@ -1159,8 +1201,9 @@ async fn create_question( | |||
| 1159 | Ok((StatusCode::CREATED, Json(QuestionResponse::new(&question)))) | 1201 | Ok((StatusCode::CREATED, Json(QuestionResponse::new(&question)))) |
| 1160 | } | 1202 | } |
| 1161 | 1203 | ||
| 1162 | -/// The exam's full question list, `correct` indexes included. Requires | 1204 | +/// The exam's full question list, `correct` indexes included — the answer |
| 1163 | -/// teacher+. Students read questions through `GET /exams/{id}/attempt/questions`. | 1205 | +/// key. Requires teacher+ and management rights over the exam's course. |
| 1206 | +/// Students read questions through `GET /exams/{id}/attempt/questions`. | ||
| 1164 | #[utoipa::path( | 1207 | #[utoipa::path( |
| 1165 | get, | 1208 | get, |
| 1166 | path = "/{id}/questions", | 1209 | path = "/{id}/questions", |
| @@ -1170,20 +1213,25 @@ async fn create_question( | |||
| 1170 | responses( | 1213 | responses( |
| 1171 | (status = 200, description = "The exam's questions", body = [QuestionResponse]), | 1214 | (status = 200, description = "The exam's questions", body = [QuestionResponse]), |
| 1172 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 1215 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1173 | - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 1216 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 1174 | (status = 404, description = "Exam not found", body = ErrorResponse), | 1217 | (status = 404, description = "Exam not found", body = ErrorResponse), |
| 1175 | ), | 1218 | ), |
| 1176 | )] | 1219 | )] |
| 1177 | async fn list_questions( | 1220 | async fn list_questions( |
| 1178 | State(st): State<AppState>, | 1221 | State(st): State<AppState>, |
| 1179 | - _teacher: RequireTeacher, | 1222 | + RequireTeacher(user): RequireTeacher, |
| 1180 | Path(id): Path<String>, | 1223 | Path(id): Path<String>, |
| 1181 | ) -> Result<Json<Vec<QuestionResponse>>, AppError> { | 1224 | ) -> Result<Json<Vec<QuestionResponse>>, AppError> { |
| 1182 | - let exam_id = ExamId::from_key(&id); | 1225 | + let exam = Exam::read(&ExamId::from_key(&id), &st.db) |
| 1183 | - Exam::read(&exam_id, &st.db) | ||
| 1184 | .await? | 1226 | .await? |
| 1185 | .ok_or(AppError::NotFound)?; | 1227 | .ok_or(AppError::NotFound)?; |
| 1186 | - let questions = ExamQuestion::list_for_exam(&exam_id, &st.db).await?; | 1228 | + let course = course_of(&exam, &st.db).await?; |
| 1229 | + if !can_manage_course(&course, &user) { | ||
| 1230 | + return Err(AppError::Forbidden( | ||
| 1231 | + "only the course creator or a manager/admin can read the question list", | ||
| 1232 | + )); | ||
| 1233 | + } | ||
| 1234 | + let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?; | ||
| 1187 | Ok(Json(questions.iter().map(QuestionResponse::new).collect())) | 1235 | Ok(Json(questions.iter().map(QuestionResponse::new).collect())) |
| 1188 | } | 1236 | } |
| 1189 | 1237 | ||
| @@ -1496,7 +1544,8 @@ async fn save_answer( | |||
| 1496 | /// saved answer plus `is_correct` (`null` for text questions — those are the | 1544 | /// saved answer plus `is_correct` (`null` for text questions — those are the |
| 1497 | /// grader's call), and the machine's `auto_score` over the choice questions is | 1545 | /// grader's call), and the machine's `auto_score` over the choice questions is |
| 1498 | /// attached as a *suggestion*: the final mark stays human, via | 1546 | /// attached as a *suggestion*: the final mark stays human, via |
| 1499 | -/// `POST /exams/{id}/results`. Requires teacher+. | 1547 | +/// `POST /exams/{id}/results`. Requires teacher+ and management rights over |
| 1548 | +/// the exam's course. | ||
| 1500 | #[utoipa::path( | 1549 | #[utoipa::path( |
| 1501 | get, | 1550 | get, |
| 1502 | path = "/{id}/attempts/{user}/answers", | 1551 | path = "/{id}/attempts/{user}/answers", |
| @@ -1509,18 +1558,24 @@ async fn save_answer( | |||
| 1509 | responses( | 1558 | responses( |
| 1510 | (status = 200, description = "The student's answers, judged", body = AttemptAnswersResponse), | 1559 | (status = 200, description = "The student's answers, judged", body = AttemptAnswersResponse), |
| 1511 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 1560 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1512 | - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 1561 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 1513 | (status = 404, description = "No such exam, or the student has no attempt", body = ErrorResponse), | 1562 | (status = 404, description = "No such exam, or the student has no attempt", body = ErrorResponse), |
| 1514 | ), | 1563 | ), |
| 1515 | )] | 1564 | )] |
| 1516 | async fn attempt_answers( | 1565 | async fn attempt_answers( |
| 1517 | State(st): State<AppState>, | 1566 | State(st): State<AppState>, |
| 1518 | - _teacher: RequireTeacher, | 1567 | + RequireTeacher(user): RequireTeacher, |
| 1519 | Path((id, target)): Path<(String, String)>, | 1568 | Path((id, target)): Path<(String, String)>, |
| 1520 | ) -> Result<Json<AttemptAnswersResponse>, AppError> { | 1569 | ) -> Result<Json<AttemptAnswersResponse>, AppError> { |
| 1521 | let exam = Exam::read(&ExamId::from_key(&id), &st.db) | 1570 | let exam = Exam::read(&ExamId::from_key(&id), &st.db) |
| 1522 | .await? | 1571 | .await? |
| 1523 | .ok_or(AppError::NotFound)?; | 1572 | .ok_or(AppError::NotFound)?; |
| 1573 | + let course = course_of(&exam, &st.db).await?; | ||
| 1574 | + if !can_manage_course(&course, &user) { | ||
| 1575 | + return Err(AppError::Forbidden( | ||
| 1576 | + "only the course creator or a manager/admin can read answer sheets", | ||
| 1577 | + )); | ||
| 1578 | + } | ||
| 1524 | let target = UserId::from_key(&target); | 1579 | let target = UserId::from_key(&target); |
| 1525 | // No attempt means no answer sheet — a 404, not an empty one. | 1580 | // No attempt means no answer sheet — a 404, not an empty one. |
| 1526 | ExamAttempt::read_for_user(exam.get_id(), &target, &st.db) | 1581 | ExamAttempt::read_for_user(exam.get_id(), &target, &st.db) |
src/web/marks.rsmodified+23 -8
| @@ -11,10 +11,12 @@ use crate::database::Database; | |||
| 11 | use crate::domain::course::Course; | 11 | use crate::domain::course::Course; |
| 12 | use crate::domain::exam::Exam; | 12 | use crate::domain::exam::Exam; |
| 13 | use crate::domain::exam_result::ExamResult; | 13 | use crate::domain::exam_result::ExamResult; |
| 14 | +use crate::domain::role::Role; | ||
| 14 | use crate::domain::user::{User, UserId}; | 15 | use crate::domain::user::{User, UserId}; |
| 15 | use crate::error::{AppError, ErrorResponse}; | 16 | use crate::error::{AppError, ErrorResponse}; |
| 16 | use crate::state::AppState; | 17 | use crate::state::AppState; |
| 17 | 18 | ||
| 19 | +use super::courses::can_manage_course; | ||
| 18 | use super::{CourseResponse, CurrentUser, RequireTeacher}; | 20 | use super::{CourseResponse, CurrentUser, RequireTeacher}; |
| 19 | 21 | ||
| 20 | pub fn routes() -> OpenApiRouter<AppState> { | 22 | pub fn routes() -> OpenApiRouter<AppState> { |
| @@ -69,9 +71,19 @@ fn weighted_average(pairs: &[(i64, i64)]) -> Option<f64> { | |||
| 69 | } | 71 | } |
| 70 | 72 | ||
| 71 | /// Assemble the report: for each enrolled course, join the course's exams | 73 | /// Assemble the report: for each enrolled course, join the course's exams |
| 72 | -/// (weights) with the user's graded results, then average. | 74 | +/// (weights) with the user's graded results, then average. A `viewer` narrows |
| 73 | -async fn build_report(user: &UserId, db: &Database) -> Result<MarksReport, AppError> { | 75 | +/// the report to the courses that viewer manages (self-reports and manager+ |
| 74 | - let courses = Course::list_enrolled(user, db).await?; | 76 | +/// reports pass `None` and see everything); the overall average follows the |
| 77 | +/// narrowed set. | ||
| 78 | +async fn build_report( | ||
| 79 | + user: &UserId, | ||
| 80 | + viewer: Option<&User>, | ||
| 81 | + db: &Database, | ||
| 82 | +) -> Result<MarksReport, AppError> { | ||
| 83 | + let mut courses = Course::list_enrolled(user, db).await?; | ||
| 84 | + if let Some(viewer) = viewer { | ||
| 85 | + courses.retain(|course| can_manage_course(course, viewer)); | ||
| 86 | + } | ||
| 75 | 87 | ||
| 76 | let mut blocks = Vec::with_capacity(courses.len()); | 88 | let mut blocks = Vec::with_capacity(courses.len()); |
| 77 | for course in &courses { | 89 | for course in &courses { |
| @@ -132,10 +144,12 @@ async fn my_marks( | |||
| 132 | State(st): State<AppState>, | 144 | State(st): State<AppState>, |
| 133 | CurrentUser(user): CurrentUser, | 145 | CurrentUser(user): CurrentUser, |
| 134 | ) -> Result<Json<MarksReport>, AppError> { | 146 | ) -> Result<Json<MarksReport>, AppError> { |
| 135 | - Ok(Json(build_report(user.get_id(), &st.db).await?)) | 147 | + Ok(Json(build_report(user.get_id(), None, &st.db).await?)) |
| 136 | } | 148 | } |
| 137 | 149 | ||
| 138 | -/// Any user's mark report. Requires teacher+. | 150 | +/// Any user's mark report. Requires teacher+. Managers and admins see every |
| 151 | +/// course; a teacher sees only the target's courses they manage — the rest of | ||
| 152 | +/// the report (other teachers' courses) stays out of reach. | ||
| 139 | #[utoipa::path( | 153 | #[utoipa::path( |
| 140 | get, | 154 | get, |
| 141 | path = "/{user}", | 155 | path = "/{user}", |
| @@ -143,7 +157,7 @@ async fn my_marks( | |||
| 143 | security(("session_cookie" = [])), | 157 | security(("session_cookie" = [])), |
| 144 | params(("user" = String, Path, description = "User id")), | 158 | params(("user" = String, Path, description = "User id")), |
| 145 | responses( | 159 | responses( |
| 146 | - (status = 200, description = "The user's mark report", body = MarksReport), | 160 | + (status = 200, description = "The user's mark report, narrowed to the caller's courses", body = MarksReport), |
| 147 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 161 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 148 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 162 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 149 | (status = 404, description = "User not found", body = ErrorResponse), | 163 | (status = 404, description = "User not found", body = ErrorResponse), |
| @@ -151,7 +165,7 @@ async fn my_marks( | |||
| 151 | )] | 165 | )] |
| 152 | async fn user_marks( | 166 | async fn user_marks( |
| 153 | State(st): State<AppState>, | 167 | State(st): State<AppState>, |
| 154 | - _teacher: RequireTeacher, | 168 | + RequireTeacher(teacher): RequireTeacher, |
| 155 | Path(user): Path<String>, | 169 | Path(user): Path<String>, |
| 156 | ) -> Result<Json<MarksReport>, AppError> { | 170 | ) -> Result<Json<MarksReport>, AppError> { |
| 157 | let target = UserId::from_key(&user); | 171 | let target = UserId::from_key(&user); |
| @@ -159,7 +173,8 @@ async fn user_marks( | |||
| 159 | User::read(&target, &st.db) | 173 | User::read(&target, &st.db) |
| 160 | .await? | 174 | .await? |
| 161 | .ok_or(AppError::NotFound)?; | 175 | .ok_or(AppError::NotFound)?; |
| 162 | - Ok(Json(build_report(&target, &st.db).await?)) | 176 | + let viewer = (!teacher.get_role().at_least(Role::Manager)).then_some(&teacher); |
| 177 | + Ok(Json(build_report(&target, viewer, &st.db).await?)) | ||
| 163 | } | 178 | } |
| 164 | 179 | ||
| 165 | #[cfg(test)] | 180 | #[cfg(test)] |
src/web/sessions.rsmodified+22 -11
| @@ -20,7 +20,7 @@ use crate::domain::user::{User, UserId}; | |||
| 20 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 20 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 21 | use crate::state::AppState; | 21 | use crate::state::AppState; |
| 22 | 22 | ||
| 23 | -use super::courses::can_manage_course; | 23 | +use super::courses::{can_manage_course, can_view_course}; |
| 24 | use super::{ | 24 | use super::{ |
| 25 | CurrentUser, PersonRef, RequireTeacher, SessionResponse, check_not_past, check_time_range, | 25 | CurrentUser, PersonRef, RequireTeacher, SessionResponse, check_not_past, check_time_range, |
| 26 | person_map, set_or_clear, | 26 | person_map, set_or_clear, |
| @@ -131,7 +131,8 @@ fn can_roll_call(session: &CourseSession, course: &Course, user: &User) -> bool | |||
| 131 | 131 | ||
| 132 | // ---- sessions ------------------------------------------------------------- | 132 | // ---- sessions ------------------------------------------------------------- |
| 133 | 133 | ||
| 134 | -/// Fetch a single session by id. | 134 | +/// Fetch a single session by id. Visible to its course's enrolled users, the |
| 135 | +/// session's teacher, the course creator, and managers/admins. | ||
| 135 | #[utoipa::path( | 136 | #[utoipa::path( |
| 136 | get, | 137 | get, |
| 137 | path = "/{id}", | 138 | path = "/{id}", |
| @@ -141,17 +142,21 @@ fn can_roll_call(session: &CourseSession, course: &Course, user: &User) -> bool | |||
| 141 | responses( | 142 | responses( |
| 142 | (status = 200, description = "The session", body = SessionResponse), | 143 | (status = 200, description = "The session", body = SessionResponse), |
| 143 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 144 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 145 | + (status = 403, description = "Not enrolled, not the session teacher, and without course rights", body = ErrorResponse), | ||
| 144 | (status = 404, description = "Not found", body = ErrorResponse), | 146 | (status = 404, description = "Not found", body = ErrorResponse), |
| 145 | ), | 147 | ), |
| 146 | )] | 148 | )] |
| 147 | async fn get_session( | 149 | async fn get_session( |
| 148 | State(st): State<AppState>, | 150 | State(st): State<AppState>, |
| 149 | - _user: CurrentUser, | 151 | + CurrentUser(user): CurrentUser, |
| 150 | Path(id): Path<String>, | 152 | Path(id): Path<String>, |
| 151 | ) -> Result<Json<SessionResponse>, AppError> { | 153 | ) -> Result<Json<SessionResponse>, AppError> { |
| 152 | - let session = CourseSession::read(&CourseSessionId::from_key(&id), &st.db) | 154 | + let (session, course) = session_with_course(&id, &st.db).await?; |
| 153 | - .await? | 155 | + if !session.is_teacher(user.get_id()) && !can_view_course(&course, &user, &st.db).await? { |
| 154 | - .ok_or(AppError::NotFound)?; | 156 | + return Err(AppError::Forbidden( |
| 157 | + "only enrolled users, the session teacher, the course creator, or a manager/admin can view this session", | ||
| 158 | + )); | ||
| 159 | + } | ||
| 155 | let people = person_map([session.get_teacher().clone()], &st.db).await?; | 160 | let people = person_map([session.get_teacher().clone()], &st.db).await?; |
| 156 | Ok(Json(SessionResponse::new(&session, &people))) | 161 | Ok(Json(SessionResponse::new(&session, &people))) |
| 157 | } | 162 | } |
| @@ -325,7 +330,9 @@ async fn mark_roll_call( | |||
| 325 | Ok(Json(SessionAttendanceResponse::new(&attendance, &people))) | 330 | Ok(Json(SessionAttendanceResponse::new(&attendance, &people))) |
| 326 | } | 331 | } |
| 327 | 332 | ||
| 328 | -/// List a session's roll call. | 333 | +/// List a session's roll call. Same rights as taking it: the session's |
| 334 | +/// teacher or a course manager — students see their own tallies via | ||
| 335 | +/// `GET /attendance/me`. | ||
| 329 | #[utoipa::path( | 336 | #[utoipa::path( |
| 330 | get, | 337 | get, |
| 331 | path = "/{id}/attendance", | 338 | path = "/{id}/attendance", |
| @@ -335,17 +342,21 @@ async fn mark_roll_call( | |||
| 335 | responses( | 342 | responses( |
| 336 | (status = 200, description = "Roll-call roster", body = [SessionAttendanceResponse]), | 343 | (status = 200, description = "Roll-call roster", body = [SessionAttendanceResponse]), |
| 337 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 344 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 345 | + (status = 403, description = "Not the session teacher or a course manager", body = ErrorResponse), | ||
| 338 | (status = 404, description = "Session not found", body = ErrorResponse), | 346 | (status = 404, description = "Session not found", body = ErrorResponse), |
| 339 | ), | 347 | ), |
| 340 | )] | 348 | )] |
| 341 | async fn list_roll_call( | 349 | async fn list_roll_call( |
| 342 | State(st): State<AppState>, | 350 | State(st): State<AppState>, |
| 343 | - _user: CurrentUser, | 351 | + RequireTeacher(user): RequireTeacher, |
| 344 | Path(id): Path<String>, | 352 | Path(id): Path<String>, |
| 345 | ) -> Result<Json<Vec<SessionAttendanceResponse>>, AppError> { | 353 | ) -> Result<Json<Vec<SessionAttendanceResponse>>, AppError> { |
| 346 | - let session = CourseSession::read(&CourseSessionId::from_key(&id), &st.db) | 354 | + let (session, course) = session_with_course(&id, &st.db).await?; |
| 347 | - .await? | 355 | + if !can_roll_call(&session, &course, &user) { |
| 348 | - .ok_or(AppError::NotFound)?; | 356 | + return Err(AppError::Forbidden( |
| 357 | + "only the session's teacher or a course manager can list the roll call", | ||
| 358 | + )); | ||
| 359 | + } | ||
| 349 | let roster = SessionAttendance::list_for_session(session.get_id(), &st.db).await?; | 360 | let roster = SessionAttendance::list_for_session(session.get_id(), &st.db).await?; |
| 350 | let people = person_map( | 361 | let people = person_map( |
| 351 | roster | 362 | roster |
tests/e2e.rsmodified+21 -3
| @@ -159,7 +159,16 @@ async fn full_user_journey() { | |||
| 159 | .unwrap(); | 159 | .unwrap(); |
| 160 | assert_eq!(res.status(), StatusCode::OK); | 160 | assert_eq!(res.status(), StatusCode::OK); |
| 161 | 161 | ||
| 162 | - let roster: Value = veli | 162 | + // The roster is a teacher+ view — veli (a student) is refused … |
| 163 | + let res = veli | ||
| 164 | + .get(format!("{base}/events/{event_id}/attendance")) | ||
| 165 | + .send() | ||
| 166 | + .await | ||
| 167 | + .unwrap(); | ||
| 168 | + assert_eq!(res.status(), StatusCode::FORBIDDEN); | ||
| 169 | + | ||
| 170 | + // … while ali (the teacher) reads it in full. | ||
| 171 | + let roster: Value = ali | ||
| 163 | .get(format!("{base}/events/{event_id}/attendance")) | 172 | .get(format!("{base}/events/{event_id}/attendance")) |
| 164 | .send() | 173 | .send() |
| 165 | .await | 174 | .await |
| @@ -353,8 +362,17 @@ async fn attendance_rollup_across_users() { | |||
| 353 | .await | 362 | .await |
| 354 | .unwrap(); | 363 | .unwrap(); |
| 355 | 364 | ||
| 356 | - // Any attendee can read the full roster (3 people). | 365 | + // The roster is a teacher+ view: an attendee sees only their own tallies |
| 357 | - let roster: Value = b | 366 | + // (`/attendance/me`), so ben is refused … |
| 367 | + let res = b | ||
| 368 | + .get(format!("{base}/events/{event_id}/attendance")) | ||
| 369 | + .send() | ||
| 370 | + .await | ||
| 371 | + .unwrap(); | ||
| 372 | + assert_eq!(res.status(), StatusCode::FORBIDDEN); | ||
| 373 | + | ||
| 374 | + // … while the host reads the full roster (3 people). | ||
| 375 | + let roster: Value = host | ||
| 358 | .get(format!("{base}/events/{event_id}/attendance")) | 376 | .get(format!("{base}/events/{event_id}/attendance")) |
| 359 | .send() | 377 | .send() |
| 360 | .await | 378 | .await |
tests/integration.rsmodified+306 -12
| @@ -788,7 +788,7 @@ async fn event_timestamps_echo_and_validate() { | |||
| 788 | // --- exams + results ----------------------------------------------------- | 788 | // --- exams + results ----------------------------------------------------- |
| 789 | 789 | ||
| 790 | #[tokio::test] | 790 | #[tokio::test] |
| 791 | -async fn exams_are_shared_but_course_guarded() { | 791 | +async fn exams_are_course_scoped_and_course_guarded() { |
| 792 | let (app, db) = app_and_db().await; | 792 | let (app, db) = app_and_db().await; |
| 793 | let ali = login_as(&app, &db, "ali", "teacher").await; | 793 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 794 | let veli = login_as(&app, &db, "veli", "teacher").await; | 794 | let veli = login_as(&app, &db, "veli", "teacher").await; |
| @@ -808,12 +808,13 @@ async fn exams_are_shared_but_course_guarded() { | |||
| 808 | assert_eq!(ex.body["weight"], 2); | 808 | assert_eq!(ex.body["weight"], 2); |
| 809 | let exam_id = id_of(&ex.body); | 809 | let exam_id = id_of(&ex.body); |
| 810 | 810 | ||
| 811 | - // Any authenticated user can read the exam and the lists. | 811 | + // A teacher outside the course sees none of it: not the exam, not the |
| 812 | + // course's exam list, and an empty catalog. | ||
| 812 | assert_eq!( | 813 | assert_eq!( |
| 813 | send(&app, "GET", &format!("/exams/{exam_id}"), Some(&veli), None) | 814 | send(&app, "GET", &format!("/exams/{exam_id}"), Some(&veli), None) |
| 814 | .await | 815 | .await |
| 815 | .status, | 816 | .status, |
| 816 | - StatusCode::OK | 817 | + StatusCode::FORBIDDEN |
| 817 | ); | 818 | ); |
| 818 | assert_eq!( | 819 | assert_eq!( |
| 819 | send(&app, "GET", "/exams", Some(&veli), None) | 820 | send(&app, "GET", "/exams", Some(&veli), None) |
| @@ -822,7 +823,7 @@ async fn exams_are_shared_but_course_guarded() { | |||
| 822 | .as_array() | 823 | .as_array() |
| 823 | .unwrap() | 824 | .unwrap() |
| 824 | .len(), | 825 | .len(), |
| 825 | - 1 | 826 | + 0 |
| 826 | ); | 827 | ); |
| 827 | assert_eq!( | 828 | assert_eq!( |
| 828 | send( | 829 | send( |
| @@ -833,6 +834,35 @@ async fn exams_are_shared_but_course_guarded() { | |||
| 833 | None | 834 | None |
| 834 | ) | 835 | ) |
| 835 | .await | 836 | .await |
| 837 | + .status, | ||
| 838 | + StatusCode::FORBIDDEN | ||
| 839 | + ); | ||
| 840 | + | ||
| 841 | + // The course creator reads all three views. | ||
| 842 | + assert_eq!( | ||
| 843 | + send(&app, "GET", &format!("/exams/{exam_id}"), Some(&ali), None) | ||
| 844 | + .await | ||
| 845 | + .status, | ||
| 846 | + StatusCode::OK | ||
| 847 | + ); | ||
| 848 | + assert_eq!( | ||
| 849 | + send(&app, "GET", "/exams", Some(&ali), None) | ||
| 850 | + .await | ||
| 851 | + .body | ||
| 852 | + .as_array() | ||
| 853 | + .unwrap() | ||
| 854 | + .len(), | ||
| 855 | + 1 | ||
| 856 | + ); | ||
| 857 | + assert_eq!( | ||
| 858 | + send( | ||
| 859 | + &app, | ||
| 860 | + "GET", | ||
| 861 | + &format!("/courses/{course_id}/exams"), | ||
| 862 | + Some(&ali), | ||
| 863 | + None | ||
| 864 | + ) | ||
| 865 | + .await | ||
| 836 | .body | 866 | .body |
| 837 | .as_array() | 867 | .as_array() |
| 838 | .unwrap() | 868 | .unwrap() |
| @@ -1273,7 +1303,7 @@ async fn deleting_exam_cascades_results() { | |||
| 1273 | // --- courses + enrollments + marks ---------------------------------------- | 1303 | // --- courses + enrollments + marks ---------------------------------------- |
| 1274 | 1304 | ||
| 1275 | #[tokio::test] | 1305 | #[tokio::test] |
| 1276 | -async fn courses_are_shared_but_creator_guarded() { | 1306 | +async fn courses_are_owner_scoped_and_creator_guarded() { |
| 1277 | let (app, db) = app_and_db().await; | 1307 | let (app, db) = app_and_db().await; |
| 1278 | let ali = login_as(&app, &db, "ali", "teacher").await; | 1308 | let ali = login_as(&app, &db, "ali", "teacher").await; |
| 1279 | let veli = login_as(&app, &db, "veli", "teacher").await; | 1309 | let veli = login_as(&app, &db, "veli", "teacher").await; |
| @@ -1291,7 +1321,8 @@ async fn courses_are_shared_but_creator_guarded() { | |||
| 1291 | assert_eq!(res.body["title"], "algebra"); | 1321 | assert_eq!(res.body["title"], "algebra"); |
| 1292 | let course_id = id_of(&res.body); | 1322 | let course_id = id_of(&res.body); |
| 1293 | 1323 | ||
| 1294 | - // Any authenticated user can read the course and the list. | 1324 | + // Another teacher is not enrolled and doesn't manage it: no read, and the |
| 1325 | + // catalog shows them nothing. | ||
| 1295 | assert_eq!( | 1326 | assert_eq!( |
| 1296 | send( | 1327 | send( |
| 1297 | &app, | 1328 | &app, |
| @@ -1302,7 +1333,7 @@ async fn courses_are_shared_but_creator_guarded() { | |||
| 1302 | ) | 1333 | ) |
| 1303 | .await | 1334 | .await |
| 1304 | .status, | 1335 | .status, |
| 1305 | - StatusCode::OK | 1336 | + StatusCode::FORBIDDEN |
| 1306 | ); | 1337 | ); |
| 1307 | assert_eq!( | 1338 | assert_eq!( |
| 1308 | send(&app, "GET", "/courses", Some(&veli), None) | 1339 | send(&app, "GET", "/courses", Some(&veli), None) |
| @@ -1311,9 +1342,34 @@ async fn courses_are_shared_but_creator_guarded() { | |||
| 1311 | .as_array() | 1342 | .as_array() |
| 1312 | .unwrap() | 1343 | .unwrap() |
| 1313 | .len(), | 1344 | .len(), |
| 1314 | - 1 | 1345 | + 0 |
| 1315 | ); | 1346 | ); |
| 1316 | 1347 | ||
| 1348 | + // The creator and a manager see it — in the catalog too. | ||
| 1349 | + for caller in [&ali, &boss] { | ||
| 1350 | + assert_eq!( | ||
| 1351 | + send( | ||
| 1352 | + &app, | ||
| 1353 | + "GET", | ||
| 1354 | + &format!("/courses/{course_id}"), | ||
| 1355 | + Some(caller), | ||
| 1356 | + None | ||
| 1357 | + ) | ||
| 1358 | + .await | ||
| 1359 | + .status, | ||
| 1360 | + StatusCode::OK | ||
| 1361 | + ); | ||
| 1362 | + assert_eq!( | ||
| 1363 | + send(&app, "GET", "/courses", Some(caller), None) | ||
| 1364 | + .await | ||
| 1365 | + .body | ||
| 1366 | + .as_array() | ||
| 1367 | + .unwrap() | ||
| 1368 | + .len(), | ||
| 1369 | + 1 | ||
| 1370 | + ); | ||
| 1371 | + } | ||
| 1372 | + | ||
| 1317 | // Non-creator teacher cannot edit or delete. | 1373 | // Non-creator teacher cannot edit or delete. |
| 1318 | assert_eq!( | 1374 | assert_eq!( |
| 1319 | send( | 1375 | send( |
| @@ -1606,7 +1662,34 @@ async fn exam_creation_lives_under_courses() { | |||
| 1606 | StatusCode::FORBIDDEN | 1662 | StatusCode::FORBIDDEN |
| 1607 | ); | 1663 | ); |
| 1608 | 1664 | ||
| 1609 | - // Any authenticated user (a student) can list the course's exams. | 1665 | + // An unenrolled student cannot list the course's exams … |
| 1666 | + assert_eq!( | ||
| 1667 | + send( | ||
| 1668 | + &app, | ||
| 1669 | + "GET", | ||
| 1670 | + &format!("/courses/{course_id}/exams"), | ||
| 1671 | + Some(&alice), | ||
| 1672 | + None | ||
| 1673 | + ) | ||
| 1674 | + .await | ||
| 1675 | + .status, | ||
| 1676 | + StatusCode::FORBIDDEN | ||
| 1677 | + ); | ||
| 1678 | + | ||
| 1679 | + // … but an enrolled one can. | ||
| 1680 | + let alice_id = me_id(&app, &alice).await; | ||
| 1681 | + assert_eq!( | ||
| 1682 | + send( | ||
| 1683 | + &app, | ||
| 1684 | + "POST", | ||
| 1685 | + &format!("/courses/{course_id}/enrollments"), | ||
| 1686 | + Some(&teacher), | ||
| 1687 | + Some(json!({ "user_id": alice_id })) | ||
| 1688 | + ) | ||
| 1689 | + .await | ||
| 1690 | + .status, | ||
| 1691 | + StatusCode::OK | ||
| 1692 | + ); | ||
| 1610 | assert_eq!( | 1693 | assert_eq!( |
| 1611 | send( | 1694 | send( |
| 1612 | &app, | 1695 | &app, |
| @@ -1904,6 +1987,114 @@ async fn marks_reports_are_self_or_teacher_scoped() { | |||
| 1904 | ); | 1987 | ); |
| 1905 | } | 1988 | } |
| 1906 | 1989 | ||
| 1990 | +/// One teacher's course is a wall: another teacher can't read its roster, | ||
| 1991 | +/// results, statistics, live monitor, answer key, or answer sheets, and the | ||
| 1992 | +/// per-user reports narrow to the courses the caller manages. Managers see | ||
| 1993 | +/// through the wall; an enrolled student sees the course itself. | ||
| 1994 | +#[tokio::test] | ||
| 1995 | +async fn course_data_is_walled_off_from_other_teachers() { | ||
| 1996 | + let (app, db) = app_and_db().await; | ||
| 1997 | + let owner = login_as(&app, &db, "owner", "teacher").await; | ||
| 1998 | + let rival = login_as(&app, &db, "rival", "teacher").await; | ||
| 1999 | + let boss = login_as(&app, &db, "boss", "manager").await; | ||
| 2000 | + let alice = login(&app, "alice").await; | ||
| 2001 | + let alice_id = me_id(&app, &alice).await; | ||
| 2002 | + | ||
| 2003 | + let course_id = create_course(&app, &owner, "algebra").await; | ||
| 2004 | + enroll(&app, &owner, &course_id, &alice_id).await; | ||
| 2005 | + let exam_id = create_exam(&app, &owner, &course_id, "mt", "quiz", 2).await; | ||
| 2006 | + let res = send( | ||
| 2007 | + &app, | ||
| 2008 | + "POST", | ||
| 2009 | + &format!("/exams/{exam_id}/results"), | ||
| 2010 | + Some(&owner), | ||
| 2011 | + Some(json!({ "mark": 70, "user_id": alice_id })), | ||
| 2012 | + ) | ||
| 2013 | + .await; | ||
| 2014 | + assert_eq!(res.status, StatusCode::OK); | ||
| 2015 | + | ||
| 2016 | + // Every course-scoped teacher read is refused for the rival … | ||
| 2017 | + for uri in [ | ||
| 2018 | + format!("/courses/{course_id}/enrollments"), | ||
| 2019 | + format!("/exams/{exam_id}/results"), | ||
| 2020 | + format!("/exams/{exam_id}/statistics"), | ||
| 2021 | + format!("/exams/{exam_id}/live"), | ||
| 2022 | + format!("/exams/{exam_id}/live/stream"), | ||
| 2023 | + format!("/exams/{exam_id}/questions"), | ||
| 2024 | + format!("/exams/{exam_id}/attempts/{alice_id}/answers"), | ||
| 2025 | + ] { | ||
| 2026 | + let res = send(&app, "GET", &uri, Some(&rival), None).await; | ||
| 2027 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{uri}"); | ||
| 2028 | + } | ||
| 2029 | + | ||
| 2030 | + // … and open to the owner and a manager. (The answer sheet turns into a | ||
| 2031 | + // 404 once authorization clears: alice never sat the exam.) | ||
| 2032 | + for caller in [&owner, &boss] { | ||
| 2033 | + for uri in [ | ||
| 2034 | + format!("/courses/{course_id}/enrollments"), | ||
| 2035 | + format!("/exams/{exam_id}/results"), | ||
| 2036 | + format!("/exams/{exam_id}/statistics"), | ||
| 2037 | + format!("/exams/{exam_id}/live"), | ||
| 2038 | + format!("/exams/{exam_id}/questions"), | ||
| 2039 | + ] { | ||
| 2040 | + let res = send(&app, "GET", &uri, Some(caller), None).await; | ||
| 2041 | + assert_eq!(res.status, StatusCode::OK, "{uri}"); | ||
| 2042 | + } | ||
| 2043 | + let res = send( | ||
| 2044 | + &app, | ||
| 2045 | + "GET", | ||
| 2046 | + &format!("/exams/{exam_id}/attempts/{alice_id}/answers"), | ||
| 2047 | + Some(caller), | ||
| 2048 | + None, | ||
| 2049 | + ) | ||
| 2050 | + .await; | ||
| 2051 | + assert_eq!(res.status, StatusCode::NOT_FOUND); | ||
| 2052 | + } | ||
| 2053 | + | ||
| 2054 | + // The marks report narrows to the caller's courses: the rival gets an | ||
| 2055 | + // empty shell, the owner and the manager get the graded course. | ||
| 2056 | + let res = send( | ||
| 2057 | + &app, | ||
| 2058 | + "GET", | ||
| 2059 | + &format!("/marks/{alice_id}"), | ||
| 2060 | + Some(&rival), | ||
| 2061 | + None, | ||
| 2062 | + ) | ||
| 2063 | + .await; | ||
| 2064 | + assert_eq!(res.status, StatusCode::OK); | ||
| 2065 | + assert!(res.body["courses"].as_array().unwrap().is_empty()); | ||
| 2066 | + assert!(res.body["overall_average"].is_null()); | ||
| 2067 | + for caller in [&owner, &boss] { | ||
| 2068 | + let res = send( | ||
| 2069 | + &app, | ||
| 2070 | + "GET", | ||
| 2071 | + &format!("/marks/{alice_id}"), | ||
| 2072 | + Some(caller), | ||
| 2073 | + None, | ||
| 2074 | + ) | ||
| 2075 | + .await; | ||
| 2076 | + assert_eq!(res.body["courses"].as_array().unwrap().len(), 1); | ||
| 2077 | + assert_eq!(res.body["overall_average"], 70.0); | ||
| 2078 | + } | ||
| 2079 | + | ||
| 2080 | + // The enrolled student reads the course and its exam, and both catalogs | ||
| 2081 | + // include them; the rival's catalogs stay empty; a manager sees all. | ||
| 2082 | + for uri in [format!("/courses/{course_id}"), format!("/exams/{exam_id}")] { | ||
| 2083 | + let res = send(&app, "GET", &uri, Some(&alice), None).await; | ||
| 2084 | + assert_eq!(res.status, StatusCode::OK, "{uri}"); | ||
| 2085 | + } | ||
| 2086 | + for (caller, visible) in [(&alice, 1), (&rival, 0), (&boss, 1)] { | ||
| 2087 | + for uri in ["/courses", "/exams"] { | ||
| 2088 | + let res = send(&app, "GET", uri, Some(caller), None).await; | ||
| 2089 | + assert_eq!( | ||
| 2090 | + res.body.as_array().unwrap().len(), | ||
| 2091 | + visible, | ||
| 2092 | + "{uri} as seen by caller" | ||
| 2093 | + ); | ||
| 2094 | + } | ||
| 2095 | + } | ||
| 2096 | +} | ||
| 2097 | + | ||
| 1907 | #[tokio::test] | 2098 | #[tokio::test] |
| 1908 | async fn deleting_course_cascades_enrollments_exams_and_results() { | 2099 | async fn deleting_course_cascades_enrollments_exams_and_results() { |
| 1909 | let (app, db) = app_and_db().await; | 2100 | let (app, db) = app_and_db().await; |
| @@ -5354,7 +5545,27 @@ async fn session_crud_follows_course_management() { | |||
| 5354 | .await; | 5545 | .await; |
| 5355 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "past ends_at"); | 5546 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "past ends_at"); |
| 5356 | 5547 | ||
| 5357 | - // Reads are open to any logged-in user; parents must exist. | 5548 | + // Reads follow course visibility: an unenrolled student is refused … |
| 5549 | + let res = send( | ||
| 5550 | + &app, | ||
| 5551 | + "GET", | ||
| 5552 | + &format!("/courses/{course}/sessions"), | ||
| 5553 | + Some(&student), | ||
| 5554 | + None, | ||
| 5555 | + ) | ||
| 5556 | + .await; | ||
| 5557 | + assert_eq!(res.status, StatusCode::FORBIDDEN); | ||
| 5558 | + | ||
| 5559 | + // … an enrolled one reads; parents must exist. | ||
| 5560 | + let res = send( | ||
| 5561 | + &app, | ||
| 5562 | + "POST", | ||
| 5563 | + &format!("/courses/{course}/enrollments"), | ||
| 5564 | + Some(&owner), | ||
| 5565 | + Some(json!({ "user_id": ali_id })), | ||
| 5566 | + ) | ||
| 5567 | + .await; | ||
| 5568 | + assert_eq!(res.status, StatusCode::OK); | ||
| 5358 | let res = send( | 5569 | let res = send( |
| 5359 | &app, | 5570 | &app, |
| 5360 | "GET", | 5571 | "GET", |
| @@ -5379,6 +5590,26 @@ async fn session_crud_follows_course_management() { | |||
| 5379 | ) | 5590 | ) |
| 5380 | .await; | 5591 | .await; |
| 5381 | assert_eq!(res.status, StatusCode::OK); | 5592 | assert_eq!(res.status, StatusCode::OK); |
| 5593 | + // The session's own teacher reads it without course rights; a session of | ||
| 5594 | + // someone else's course stays out of reach. | ||
| 5595 | + let res = send( | ||
| 5596 | + &app, | ||
| 5597 | + "GET", | ||
| 5598 | + &format!("/sessions/{rival_session}"), | ||
| 5599 | + Some(&rival), | ||
| 5600 | + None, | ||
| 5601 | + ) | ||
| 5602 | + .await; | ||
| 5603 | + assert_eq!(res.status, StatusCode::OK); | ||
| 5604 | + let res = send( | ||
| 5605 | + &app, | ||
| 5606 | + "GET", | ||
| 5607 | + &format!("/sessions/{session}"), | ||
| 5608 | + Some(&rival), | ||
| 5609 | + None, | ||
| 5610 | + ) | ||
| 5611 | + .await; | ||
| 5612 | + assert_eq!(res.status, StatusCode::FORBIDDEN); | ||
| 5382 | let res = send(&app, "GET", "/sessions/nope", Some(&student), None).await; | 5613 | let res = send(&app, "GET", "/sessions/nope", Some(&student), None).await; |
| 5383 | assert_eq!(res.status, StatusCode::NOT_FOUND); | 5614 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 5384 | 5615 | ||
| @@ -5556,11 +5787,18 @@ async fn roll_call_rbac_and_upsert() { | |||
| 5556 | ) | 5787 | ) |
| 5557 | .await; | 5788 | .await; |
| 5558 | assert_eq!(res.status, StatusCode::OK); | 5789 | assert_eq!(res.status, StatusCode::OK); |
| 5559 | - let res = send(&app, "GET", &mark_uri, Some(&ali), None).await; | 5790 | + // The roster follows roll-call rights: the session teacher reads it, a |
| 5560 | - assert_eq!(res.status, StatusCode::OK, "roster is readable by students"); | 5791 | + // student (even a listed one) and an unrelated teacher do not — students |
| 5792 | + // get their own tallies via `/attendance/me`. | ||
| 5793 | + let res = send(&app, "GET", &mark_uri, Some(&hoca), None).await; | ||
| 5794 | + assert_eq!(res.status, StatusCode::OK); | ||
| 5561 | let roster = res.body.as_array().unwrap(); | 5795 | let roster = res.body.as_array().unwrap(); |
| 5562 | assert_eq!(roster.len(), 1); | 5796 | assert_eq!(roster.len(), 1); |
| 5563 | assert_eq!(roster[0]["status"], "absent"); | 5797 | assert_eq!(roster[0]["status"], "absent"); |
| 5798 | + let res = send(&app, "GET", &mark_uri, Some(&ali), None).await; | ||
| 5799 | + assert_eq!(res.status, StatusCode::FORBIDDEN); | ||
| 5800 | + let res = send(&app, "GET", &mark_uri, Some(&rival), None).await; | ||
| 5801 | + assert_eq!(res.status, StatusCode::FORBIDDEN); | ||
| 5564 | 5802 | ||
| 5565 | // Neither an unrelated teacher nor the student themselves may mark. | 5803 | // Neither an unrelated teacher nor the student themselves may mark. |
| 5566 | let res = send( | 5804 | let res = send( |
| @@ -6070,6 +6308,62 @@ async fn attendance_report_tallies_events_and_sessions_per_course() { | |||
| 6070 | .await; | 6308 | .await; |
| 6071 | assert_eq!(res.status, StatusCode::OK); | 6309 | assert_eq!(res.status, StatusCode::OK); |
| 6072 | assert_eq!(res.body["sessions"]["total"], 4); | 6310 | assert_eq!(res.body["sessions"]["total"], 4); |
| 6311 | + | ||
| 6312 | + // A teacher's view narrows to the courses they manage: rival runs only | ||
| 6313 | + // chemistry, so ali's report shows that block alone — the overall session | ||
| 6314 | + // tally follows, while event tallies stay school-wide. | ||
| 6315 | + let rival = login_as(&app, &db, "rival", "teacher").await; | ||
| 6316 | + let chemistry = create_course(&app, &rival, "chemistry").await; | ||
| 6317 | + enroll(&app, &rival, &chemistry, &ali_id).await; | ||
| 6318 | + let session = create_session( | ||
| 6319 | + &app, | ||
| 6320 | + &rival, | ||
| 6321 | + &chemistry, | ||
| 6322 | + Timestamp::now().as_millis() + 10 * 3_600_000, | ||
| 6323 | + ) | ||
| 6324 | + .await; | ||
| 6325 | + let res = send( | ||
| 6326 | + &app, | ||
| 6327 | + "POST", | ||
| 6328 | + &format!("/sessions/{session}/attendance"), | ||
| 6329 | + Some(&rival), | ||
| 6330 | + Some(json!({ "status": "present", "user_id": ali_id })), | ||
| 6331 | + ) | ||
| 6332 | + .await; | ||
| 6333 | + assert_eq!(res.status, StatusCode::OK); | ||
| 6334 | + | ||
| 6335 | + let res = send( | ||
| 6336 | + &app, | ||
| 6337 | + "GET", | ||
| 6338 | + &format!("/attendance/{ali_id}"), | ||
| 6339 | + Some(&rival), | ||
| 6340 | + None, | ||
| 6341 | + ) | ||
| 6342 | + .await; | ||
| 6343 | + assert_eq!(res.status, StatusCode::OK); | ||
| 6344 | + assert_eq!(res.body["events"]["total"], 2, "events stay school-wide"); | ||
| 6345 | + assert_eq!(res.body["sessions"]["total"], 1); | ||
| 6346 | + let blocks = res.body["courses"].as_array().unwrap(); | ||
| 6347 | + assert_eq!(blocks.len(), 1); | ||
| 6348 | + assert_eq!(blocks[0]["course"]["title"], "chemistry"); | ||
| 6349 | + | ||
| 6350 | + // The owner's view still carries only their own two courses … | ||
| 6351 | + let res = send( | ||
| 6352 | + &app, | ||
| 6353 | + "GET", | ||
| 6354 | + &format!("/attendance/{ali_id}"), | ||
| 6355 | + Some(&owner), | ||
| 6356 | + None, | ||
| 6357 | + ) | ||
| 6358 | + .await; | ||
| 6359 | + assert_eq!(res.body["courses"].as_array().unwrap().len(), 2); | ||
| 6360 | + assert_eq!(res.body["sessions"]["total"], 4); | ||
| 6361 | + | ||
| 6362 | + // … and the self view stays complete: all three courses, every row. | ||
| 6363 | + let res = send(&app, "GET", "/attendance/me", Some(&ali), None).await; | ||
| 6364 | + assert_eq!(res.body["courses"].as_array().unwrap().len(), 3); | ||
| 6365 | + assert_eq!(res.body["sessions"]["total"], 5); | ||
| 6366 | + | ||
| 6073 | let res = send(&app, "GET", "/attendance/01UNKNOWN", Some(&owner), None).await; | 6367 | let res = send(&app, "GET", "/attendance/01UNKNOWN", Some(&owner), None).await; |
| 6074 | assert_eq!(res.status, StatusCode::NOT_FOUND); | 6368 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 6075 | } | 6369 | } |