From 3c4822c253dbff83ddb5e91727889c4dc86f2524 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 11 Jul 2026 21:39:14 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(web):=20axum=20handlers,=20DTO?= =?UTF-8?q?s,=20and=20auth=20extractors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The HTTP layer over the domain. DTOs are plain strings on the wire; handlers parse them into validated newtypes before touching the database. Responses share one UserResponse shape (id, username, role). Auth is a session cookie: login sets an HttpOnly, SameSite=Lax `session` cookie (Secure when configured) backed by a server-side row; logout is idempotent. Extractors encode access control by type — CurrentUser for any logged-in caller, RequireTeacher / RequireAdmin for role-gated routes — with the role re-read every request so a change takes effect on the next call. Routers: auth (register/login/logout/me), users (admin listing + role changes), notes (per-user CRUD), events + attendance, and exams + results. Ownership and role rules live in the handlers: event/exam edits are creator-or-manager+, grading is teacher+ and never targets oneself, and admins can't change their own role. --- src/web/auth.rs | 149 +++++++++++++++ src/web/dto.rs | 52 ++++++ src/web/events.rs | 424 +++++++++++++++++++++++++++++++++++++++++++ src/web/exams.rs | 388 +++++++++++++++++++++++++++++++++++++++ src/web/extractor.rs | 95 ++++++++++ src/web/mod.rs | 16 ++ src/web/notes.rs | 180 ++++++++++++++++++ src/web/users.rs | 84 +++++++++ 8 files changed, 1388 insertions(+) create mode 100644 src/web/auth.rs create mode 100644 src/web/dto.rs create mode 100644 src/web/events.rs create mode 100644 src/web/exams.rs create mode 100644 src/web/extractor.rs create mode 100644 src/web/mod.rs create mode 100644 src/web/notes.rs create mode 100644 src/web/users.rs diff --git a/src/web/auth.rs b/src/web/auth.rs new file mode 100644 index 0000000..f276f38 --- /dev/null +++ b/src/web/auth.rs @@ -0,0 +1,149 @@ +use axum::Json; +use axum::extract::{Request, State}; +use axum::http::StatusCode; +use axum::middleware::{self, Next}; +use axum_extra::extract::CookieJar; +use axum_extra::extract::cookie::{Cookie, SameSite}; +use serde::Deserialize; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::constant::SESSION_DURATION_DAYS; +use crate::domain::session::Session; +use crate::domain::user::{Password, PasswordHash, User, Username}; +use crate::error::{AppError, ErrorResponse}; +use crate::rate_limit::{RateLimitConfig, RateLimiter}; +use crate::state::AppState; + +use super::{CurrentUser, UserResponse}; + +pub fn routes(rate_limit: &RateLimitConfig) -> OpenApiRouter { + // Strict per-IP limit on the two credential endpoints only — the + // brute-force and username-enumeration surface. `me` and `logout` stay + // outside it: browser frontends poll `me` on every page load, and being + // over the auth limit must never block an intentional logout. + let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy); + OpenApiRouter::new() + .routes(routes!(register)) + .routes(routes!(login)) + // `route_layer` wraps only the routes registered above it. + .route_layer(middleware::from_fn(move |req: Request, next: Next| { + let limiter = limiter.clone(); + async move { limiter.enforce(req, next).await } + })) + .routes(routes!(logout)) + .routes(routes!(me)) +} + +#[derive(Deserialize, ToSchema)] +struct Credentials { + #[schema(example = "ada")] + username: String, + #[schema(example = "correct horse battery")] + password: String, +} + +/// Register a new user account. +#[utoipa::path( + post, + path = "/register", + tag = "auth", + request_body = Credentials, + responses( + (status = 201, description = "Account created", body = UserResponse), + (status = 400, description = "Invalid username or password", body = ErrorResponse), + (status = 409, description = "Username already taken", body = ErrorResponse), + (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), + ), +)] +async fn register( + State(st): State, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let username = Username::try_new(&req.username)?; + let password_hash = Password::try_new(&req.password)?.hash()?; + let user = User::create(username, password_hash, &st.db).await?; + Ok((StatusCode::CREATED, Json(UserResponse::new(&user)))) +} + +/// Log in with username + password. Sets a `session` cookie on success. +#[utoipa::path( + post, + path = "/login", + tag = "auth", + request_body = Credentials, + responses( + (status = 200, description = "Logged in; session cookie set", body = UserResponse), + (status = 401, description = "Bad credentials", body = ErrorResponse), + (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), + ), +)] +async fn login( + State(st): State, + jar: CookieJar, + Json(req): Json, +) -> Result<(CookieJar, Json), AppError> { + let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?; + // Usernames are stored trimmed (see `Username::try_new`); trim the lookup + // the same way so a padded login attempt matches the canonical name. + let user = match User::find_by_username(req.username.trim(), &st.db).await? { + Some(user) if user.get_password_hash().verify(&password) => user, + Some(_) => return Err(AppError::Unauthorized), + None => { + // No such user. Still do the argon2 work against a decoy so the reply + // takes as long as a real (wrong-password) check — otherwise the + // timing difference leaks which usernames exist. + PasswordHash::verify_decoy(&password); + return Err(AppError::Unauthorized); + } + }; + + // The caller is genuine; opportunistically drop any expired session rows. + let _ = Session::purge_expired(&st.db).await; + + let session = Session::create(user.get_id(), &st.db).await?; + let cookie = Cookie::build(("session", session.token().as_str().to_string())) + .path("/") + .http_only(true) + .secure(st.cookie_secure) + .same_site(SameSite::Lax) + .max_age(time::Duration::days(SESSION_DURATION_DAYS)) + .build(); + + Ok((jar.add(cookie), Json(UserResponse::new(&user)))) +} + +/// Log out: revoke the current session (if any) and clear the cookie. +/// Idempotent — no session required; answers `204` either way. +#[utoipa::path( + post, + path = "/logout", + tag = "auth", + responses((status = 204, description = "Logged out (no-op without a session)")), +)] +async fn logout( + State(st): State, + jar: CookieJar, +) -> Result<(CookieJar, StatusCode), AppError> { + if let Some(cookie) = jar.get("session") { + Session::delete_by_token(cookie.value(), &st.db).await?; + } + let jar = jar.remove(Cookie::build(("session", "")).path("/").build()); + Ok((jar, StatusCode::NO_CONTENT)) +} + +/// Return the currently authenticated user. +#[utoipa::path( + get, + path = "/me", + tag = "auth", + security(("session_cookie" = [])), + responses( + (status = 200, description = "The current user", body = UserResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn me(CurrentUser(user): CurrentUser) -> Json { + Json(UserResponse::new(&user)) +} diff --git a/src/web/dto.rs b/src/web/dto.rs new file mode 100644 index 0000000..f8e9d77 --- /dev/null +++ b/src/web/dto.rs @@ -0,0 +1,52 @@ +//! Response DTOs shared across more than one handler module. + +use serde::Serialize; +use utoipa::ToSchema; + +use crate::domain::role::Role as DomainRole; +use crate::domain::user::User; + +/// The four access roles, lowest to highest privilege. The web-facing mirror of +/// [`crate::domain::role::Role`] — it carries the serde + OpenAPI derives (which +/// the domain type deliberately omits), so it renders as a proper `enum` in the +/// docs. Serializes to the same lowercase strings the domain stores. +#[derive(Serialize, Clone, Copy, ToSchema)] +#[serde(rename_all = "lowercase")] +pub enum Role { + Student, + Teacher, + Manager, + Admin, +} + +impl From for Role { + fn from(role: DomainRole) -> Self { + match role { + DomainRole::Student => Role::Student, + DomainRole::Teacher => Role::Teacher, + DomainRole::Manager => Role::Manager, + DomainRole::Admin => Role::Admin, + } + } +} + +/// Public shape of a user: id, username, role. Never carries the password hash. +/// Shared by `auth` (register/login/me) and `users` (admin listing/role changes). +#[derive(Serialize, ToSchema)] +pub struct UserResponse { + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + pub id: String, + #[schema(example = "ada")] + pub username: String, + pub role: Role, +} + +impl UserResponse { + pub fn new(user: &User) -> Self { + Self { + id: user.get_id().key().to_string(), + username: user.get_username().as_str().to_string(), + role: user.get_role().into(), + } + } +} diff --git a/src/web/events.rs b/src/web/events.rs new file mode 100644 index 0000000..34dfbee --- /dev/null +++ b/src/web/events.rs @@ -0,0 +1,424 @@ +use axum::Json; +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use serde::{Deserialize, Deserializer, Serialize}; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::domain::attendance::{Attendance, AttendanceStatus}; +use crate::domain::event::{Event, EventDescription, EventId, EventTitle}; +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::{CurrentUser, RequireTeacher}; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(create_event, list_events)) + .routes(routes!(get_event, update_event, delete_event)) + .routes(routes!(mark, list_attendance)) + .routes(routes!(remove_attendance)) +} + +#[derive(Deserialize, ToSchema)] +struct CreateEvent { + #[schema(example = "Sprint demo")] + title: String, + description: Option, + /// Unix-millisecond timestamps. + #[schema(example = 1_700_000_000_000_i64)] + starts_at: Option, + ends_at: Option, +} + +/// Distinguishes an *absent* field from an explicit `null`: absent never +/// reaches the deserializer and stays `None` via `#[serde(default)]` (keep the +/// stored value); `null` or a number lands here as `Some(inner)` (clear or set). +fn set_or_clear<'de, D>(de: D) -> Result>, D::Error> +where + D: Deserializer<'de>, +{ + Option::::deserialize(de).map(Some) +} + +#[derive(Deserialize, ToSchema)] +struct UpdateEvent { + title: Option, + description: Option, + /// Unix-millisecond timestamp. Omit to keep the current value; send `null` + /// to clear it. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option)] + starts_at: Option>, + /// Unix-millisecond timestamp. Omit to keep the current value; send `null` + /// to clear it. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option)] + ends_at: Option>, +} + +#[derive(Deserialize, ToSchema)] +struct MarkAttendance { + /// One of the accepted attendance statuses (e.g. `present`, `absent`). + #[schema(example = "present")] + status: String, + /// Target user id. Defaults to the caller when omitted. + user_id: Option, +} + +#[derive(Serialize, ToSchema)] +struct EventResponse { + id: String, + creator: String, + title: String, + description: String, + starts_at: Option, + ends_at: Option, +} + +impl EventResponse { + fn new(event: &Event) -> Self { + Self { + id: event.get_id().key().to_string(), + creator: event.get_creator().key().to_string(), + title: event.get_title().as_str().to_string(), + description: event.get_description().as_str().to_string(), + starts_at: event.get_starts_at().map(|t| t.as_millis()), + ends_at: event.get_ends_at().map(|t| t.as_millis()), + } + } +} + +/// Who may edit/delete a specific event: its creator, or anyone `manager` and +/// above (who can manage any event regardless of ownership). Callers have +/// already cleared the `teacher` bar via the `RequireTeacher` extractor. +fn can_manage(event: &Event, user: &User) -> bool { + event.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager) +} + +/// If both ends are present, `ends_at` must not precede `starts_at`. +fn check_time_range( + starts_at: Option, + ends_at: Option, +) -> Result<(), AppError> { + if let (Some(starts), Some(ends)) = (starts_at, ends_at) + && ends < starts + { + return Err(AppError::Validation(ValidationError::Invalid { + field: "ends_at", + reason: "must be at or after starts_at", + })); + } + Ok(()) +} + +#[derive(Serialize, ToSchema)] +struct AttendanceResponse { + id: String, + event: String, + user: String, + status: String, + marked_by: String, +} + +impl AttendanceResponse { + fn new(attendance: &Attendance) -> Self { + Self { + id: attendance.get_id().key().to_string(), + event: attendance.get_event().key().to_string(), + user: attendance.get_user().key().to_string(), + status: attendance.get_status().as_str().to_string(), + marked_by: attendance.get_marked_by().key().to_string(), + } + } +} + +// ---- events ------------------------------------------------------------- + +/// Create an event owned by the current user. Requires the `teacher` role or higher. +#[utoipa::path( + post, + path = "/", + tag = "events", + security(("session_cookie" = [])), + request_body = CreateEvent, + responses( + (status = 201, description = "Event created", body = EventResponse), + (status = 400, description = "Invalid fields or time range", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + ), +)] +async fn create_event( + State(st): State, + RequireTeacher(user): RequireTeacher, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let title = EventTitle::try_new(&req.title)?; + let description = EventDescription::try_new(&req.description.unwrap_or_default())?; + let starts_at = req.starts_at.map(Timestamp::from_millis); + let ends_at = req.ends_at.map(Timestamp::from_millis); + check_time_range(starts_at, ends_at)?; + let event = Event::create( + user.get_id(), + title, + description, + starts_at, + ends_at, + &st.db, + ) + .await?; + Ok((StatusCode::CREATED, Json(EventResponse::new(&event)))) +} + +/// List all events. +#[utoipa::path( + get, + path = "/", + tag = "events", + security(("session_cookie" = [])), + responses( + (status = 200, description = "All events", body = [EventResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn list_events( + State(st): State, + _user: CurrentUser, +) -> Result>, AppError> { + let events = Event::list_all(&st.db).await?; + Ok(Json(events.iter().map(EventResponse::new).collect())) +} + +/// Fetch a single event by id. +#[utoipa::path( + get, + path = "/{id}", + tag = "events", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Event id")), + responses( + (status = 200, description = "The event", body = EventResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn get_event( + State(st): State, + _user: CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let event = Event::read(&EventId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + Ok(Json(EventResponse::new(&event))) +} + +/// Update an event. Requires teacher+; the creator may edit their own event and +/// managers/admins may edit anyone's. Omitted fields keep their value; an +/// explicit `null` clears `starts_at`/`ends_at`. +#[utoipa::path( + patch, + path = "/{id}", + tag = "events", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Event id")), + request_body = UpdateEvent, + responses( + (status = 200, description = "Updated event", body = EventResponse), + (status = 400, description = "Invalid fields or time range", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn update_event( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let event = Event::read(&EventId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if !can_manage(&event, &user) { + return Err(AppError::Forbidden( + "only the creator or a manager/admin can edit this event", + )); + } + + let title = match req.title { + Some(ref title) => EventTitle::try_new(title)?, + None => event.get_title().clone(), + }; + let description = match req.description { + Some(ref description) => EventDescription::try_new(description)?, + None => event.get_description().clone(), + }; + // A provided value sets the field, an explicit `null` clears it, and an + // omitted one keeps the current value. + let starts_at = match req.starts_at { + Some(update) => update.map(Timestamp::from_millis), + None => event.get_starts_at(), + }; + let ends_at = match req.ends_at { + Some(update) => update.map(Timestamp::from_millis), + None => event.get_ends_at(), + }; + check_time_range(starts_at, ends_at)?; + + let updated = event + .update(title, description, starts_at, ends_at, &st.db) + .await?; + Ok(Json(EventResponse::new(&updated))) +} + +/// Delete an event. Requires teacher+; the creator may delete their own event +/// and managers/admins may delete anyone's. +#[utoipa::path( + delete, + path = "/{id}", + tag = "events", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Event id")), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn delete_event( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, +) -> Result { + let event = Event::read(&EventId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if !can_manage(&event, &user) { + return Err(AppError::Forbidden( + "only the creator or a manager/admin can delete this event", + )); + } + event.delete(&st.db).await?; + Ok(StatusCode::NO_CONTENT) +} + +// ---- attendance --------------------------------------------------------- + +/// Mark attendance for a user on an event (defaults to the caller). Anyone may +/// mark their own attendance; marking someone else requires the `teacher` role +/// or higher. +#[utoipa::path( + post, + path = "/{id}/attendance", + tag = "events", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Event id")), + request_body = MarkAttendance, + responses( + (status = 200, description = "Attendance recorded", body = AttendanceResponse), + (status = 400, description = "Invalid status or unknown user", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Marking another user requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "Event not found", body = ErrorResponse), + ), +)] +async fn mark( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let event_id = EventId::from_key(&id); + // Event must exist. + Event::read(&event_id, &st.db) + .await? + .ok_or(AppError::NotFound)?; + + let status = AttendanceStatus::try_new(&req.status)?; + let target = match req.user_id { + Some(ref key) => UserId::from_key(key), + None => user.get_id().clone(), + }; + + // Marking anyone other than yourself is a teacher+ action. + if &target != user.get_id() && !user.get_role().at_least(Role::Teacher) { + return Err(AppError::Forbidden( + "only teachers can mark attendance for other users", + )); + } + + // Target user must exist. + if User::read(&target, &st.db).await?.is_none() { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user does not exist", + })); + } + + let attendance = Attendance::mark(&event_id, &target, status, user.get_id(), &st.db).await?; + Ok(Json(AttendanceResponse::new(&attendance))) +} + +/// List the attendance roster for an event. +#[utoipa::path( + get, + path = "/{id}/attendance", + tag = "events", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Event id")), + responses( + (status = 200, description = "Attendance roster", body = [AttendanceResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Event not found", body = ErrorResponse), + ), +)] +async fn list_attendance( + State(st): State, + _user: CurrentUser, + Path(id): Path, +) -> Result>, AppError> { + let event_id = EventId::from_key(&id); + // Event must exist — a missing event is a 404, not an empty roster. + Event::read(&event_id, &st.db) + .await? + .ok_or(AppError::NotFound)?; + let roster = Attendance::list_for_event(&event_id, &st.db).await?; + Ok(Json(roster.iter().map(AttendanceResponse::new).collect())) +} + +/// Remove a user's attendance record from an event. Requires teacher+. +#[utoipa::path( + delete, + path = "/{id}/attendance/{user}", + tag = "events", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Event id"), + ("user" = String, Path, description = "User id"), + ), + responses( + (status = 204, description = "Removed"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn remove_attendance( + State(st): State, + _teacher: RequireTeacher, + Path((id, target)): Path<(String, String)>, +) -> Result { + let removed = + Attendance::remove(&EventId::from_key(&id), &UserId::from_key(&target), &st.db).await?; + if removed.is_none() { + return Err(AppError::NotFound); + } + Ok(StatusCode::NO_CONTENT) +} diff --git a/src/web/exams.rs b/src/web/exams.rs new file mode 100644 index 0000000..137a578 --- /dev/null +++ b/src/web/exams.rs @@ -0,0 +1,388 @@ +use axum::Json; +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::domain::exam::{Exam, ExamDescription, ExamId, ExamKind, ExamTitle}; +use crate::domain::exam_result::{ExamResult, Mark}; +use crate::domain::role::Role; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::state::AppState; + +use super::{CurrentUser, RequireTeacher}; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(create_exam, list_exams)) + .routes(routes!(get_exam, update_exam, delete_exam)) + .routes(routes!(grade, list_results)) + .routes(routes!(my_result)) + .routes(routes!(remove_result)) +} + +#[derive(Deserialize, ToSchema)] +struct CreateExam { + #[schema(example = "Chapter 3 quiz")] + title: String, + description: Option, + /// The assessment form: `homework` or `quiz`. + #[schema(example = "quiz")] + kind: String, +} + +#[derive(Deserialize, ToSchema)] +struct UpdateExam { + title: Option, + description: Option, + kind: Option, +} + +#[derive(Deserialize, ToSchema)] +struct GradeResult { + /// The mark to record, `0`–`100`. + #[schema(example = 85)] + mark: i64, + /// The student being graded. + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + user_id: String, +} + +#[derive(Serialize, ToSchema)] +struct ExamResponse { + id: String, + creator: String, + title: String, + description: String, + kind: String, +} + +impl ExamResponse { + fn new(exam: &Exam) -> Self { + Self { + id: exam.get_id().key().to_string(), + creator: exam.get_creator().key().to_string(), + title: exam.get_title().as_str().to_string(), + description: exam.get_description().as_str().to_string(), + kind: exam.get_kind().as_str().to_string(), + } + } +} + +#[derive(Serialize, ToSchema)] +struct ExamResultResponse { + id: String, + exam: String, + user: String, + mark: i64, + graded_by: String, +} + +impl ExamResultResponse { + fn new(result: &ExamResult) -> Self { + Self { + id: result.get_id().key().to_string(), + exam: result.get_exam().key().to_string(), + user: result.get_user().key().to_string(), + mark: result.get_mark().as_i64(), + graded_by: result.get_graded_by().key().to_string(), + } + } +} + +/// Who may edit/delete a specific exam: its creator, or anyone `manager` and +/// above. Callers have already cleared the `teacher` bar via `RequireTeacher`. +fn can_manage(exam: &Exam, user: &User) -> bool { + exam.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager) +} + +// ---- exams -------------------------------------------------------------- + +/// Create an exam owned by the current user. Requires the `teacher` role or higher. +#[utoipa::path( + post, + path = "/", + tag = "exams", + security(("session_cookie" = [])), + request_body = CreateExam, + responses( + (status = 201, description = "Exam created", body = ExamResponse), + (status = 400, description = "Invalid fields or kind", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + ), +)] +async fn create_exam( + State(st): State, + RequireTeacher(user): RequireTeacher, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let title = ExamTitle::try_new(&req.title)?; + let description = ExamDescription::try_new(&req.description.unwrap_or_default())?; + let kind = ExamKind::try_new(&req.kind)?; + let exam = Exam::create(user.get_id(), title, description, kind, &st.db).await?; + Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam)))) +} + +/// List all exams. +#[utoipa::path( + get, + path = "/", + tag = "exams", + security(("session_cookie" = [])), + responses( + (status = 200, description = "All exams", body = [ExamResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn list_exams( + State(st): State, + _user: CurrentUser, +) -> Result>, AppError> { + let exams = Exam::list_all(&st.db).await?; + Ok(Json(exams.iter().map(ExamResponse::new).collect())) +} + +/// Fetch a single exam by id. +#[utoipa::path( + get, + path = "/{id}", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 200, description = "The exam", body = ExamResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn get_exam( + State(st): State, + _user: CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + Ok(Json(ExamResponse::new(&exam))) +} + +/// Update an exam. Requires teacher+; the creator may edit their own exam and +/// managers/admins may edit anyone's. Omitted fields keep their value. +#[utoipa::path( + patch, + path = "/{id}", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + request_body = UpdateExam, + responses( + (status = 200, description = "Updated exam", body = ExamResponse), + (status = 400, description = "Invalid fields or kind", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn update_exam( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if !can_manage(&exam, &user) { + return Err(AppError::Forbidden( + "only the creator or a manager/admin can edit this exam", + )); + } + + let title = match req.title { + Some(ref title) => ExamTitle::try_new(title)?, + None => exam.get_title().clone(), + }; + let description = match req.description { + Some(ref description) => ExamDescription::try_new(description)?, + None => exam.get_description().clone(), + }; + let kind = match req.kind { + Some(ref kind) => ExamKind::try_new(kind)?, + None => exam.get_kind().clone(), + }; + + let updated = exam.update(title, description, kind, &st.db).await?; + Ok(Json(ExamResponse::new(&updated))) +} + +/// Delete an exam. Requires teacher+; the creator may delete their own exam and +/// managers/admins may delete anyone's. Cascades the exam's result rows. +#[utoipa::path( + delete, + path = "/{id}", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn delete_exam( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, +) -> Result { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if !can_manage(&exam, &user) { + return Err(AppError::Forbidden( + "only the creator or a manager/admin can delete this exam", + )); + } + exam.delete(&st.db).await?; + Ok(StatusCode::NO_CONTENT) +} + +// ---- results ------------------------------------------------------------ + +/// Record (or overwrite) a student's mark for an exam. Requires teacher+. +/// Students never grade — including themselves. +#[utoipa::path( + post, + path = "/{id}/results", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + request_body = GradeResult, + responses( + (status = 200, description = "Result recorded", body = ExamResultResponse), + (status = 400, description = "Invalid mark or unknown user", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher, or attempted to grade yourself", body = ErrorResponse), + (status = 404, description = "Exam not found", body = ErrorResponse), + ), +)] +async fn grade( + State(st): State, + RequireTeacher(teacher): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let exam_id = ExamId::from_key(&id); + // Exam must exist. + Exam::read(&exam_id, &st.db) + .await? + .ok_or(AppError::NotFound)?; + + let mark = Mark::try_new(req.mark)?; + let target = UserId::from_key(&req.user_id); + + // Grading never targets oneself — no grader, whatever their role, may + // write their own mark. + if &target == teacher.get_id() { + return Err(AppError::Forbidden("grading yourself is not allowed")); + } + + // Target user must exist. + if User::read(&target, &st.db).await?.is_none() { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user does not exist", + })); + } + + let result = ExamResult::grade(&exam_id, &target, mark, teacher.get_id(), &st.db).await?; + Ok(Json(ExamResultResponse::new(&result))) +} + +/// List every result for an exam. Requires teacher+ — students read only their +/// own via `GET /exams/{id}/result`. +#[utoipa::path( + get, + path = "/{id}/results", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + 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 = 404, description = "Exam not found", body = ErrorResponse), + ), +)] +async fn list_results( + State(st): State, + _teacher: 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) + .await? + .ok_or(AppError::NotFound)?; + let results = ExamResult::list_for_exam(&exam_id, &st.db).await?; + Ok(Json(results.iter().map(ExamResultResponse::new).collect())) +} + +/// The current user's own result for an exam. Any authenticated user may read +/// their own mark; `404` while ungraded (or when the exam doesn't exist). +#[utoipa::path( + get, + path = "/{id}/result", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 200, description = "The caller's result", body = ExamResultResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "No such exam, or not graded yet", body = ErrorResponse), + ), +)] +async fn my_result( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let result = ExamResult::read_for_user(&ExamId::from_key(&id), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + Ok(Json(ExamResultResponse::new(&result))) +} + +/// Remove a student's result from an exam. Requires teacher+. +#[utoipa::path( + delete, + path = "/{id}/results/{user}", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("user" = String, Path, description = "User id"), + ), + responses( + (status = 204, description = "Removed"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn remove_result( + State(st): State, + _teacher: RequireTeacher, + Path((id, target)): Path<(String, String)>, +) -> Result { + let removed = + ExamResult::remove(&ExamId::from_key(&id), &UserId::from_key(&target), &st.db).await?; + if removed.is_none() { + return Err(AppError::NotFound); + } + Ok(StatusCode::NO_CONTENT) +} diff --git a/src/web/extractor.rs b/src/web/extractor.rs new file mode 100644 index 0000000..7cfca48 --- /dev/null +++ b/src/web/extractor.rs @@ -0,0 +1,95 @@ +use axum::extract::{FromRef, FromRequestParts}; +use axum::http::request::Parts; +use axum_extra::extract::CookieJar; + +use crate::domain::role::Role; +use crate::domain::session::Session; +use crate::domain::user::User; +use crate::error::AppError; +use crate::state::AppState; + +/// Resolve the user behind the `session` cookie, or `401`. The role is read +/// fresh from the row on every request, so a role change takes effect on the +/// user's next call — no re-login required. +async fn authed_user(parts: &mut Parts, state: &S) -> Result +where + S: Send + Sync, + AppState: FromRef, +{ + let jar = CookieJar::from_request_parts(parts, state) + .await + .map_err(|_| AppError::Unauthorized)?; + let token = jar + .get("session") + .map(|cookie| cookie.value().to_owned()) + .ok_or(AppError::Unauthorized)?; + + let app = AppState::from_ref(state); + + let session = Session::find_by_token(&token, &app.db) + .await? + .ok_or(AppError::Unauthorized)?; + if session.is_expired() { + return Err(AppError::Unauthorized); + } + + User::read(session.user(), &app.db) + .await? + .ok_or(AppError::Unauthorized) +} + +/// The authenticated user, resolved from the `session` cookie. Add it as a +/// handler argument to require authentication; missing/expired → `401`. +pub struct CurrentUser(pub User); + +impl FromRequestParts for CurrentUser +where + S: Send + Sync, + AppState: FromRef, +{ + type Rejection = AppError; + + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { + Ok(CurrentUser(authed_user(parts, state).await?)) + } +} + +/// Like [`CurrentUser`], but also requires at least the `teacher` role. +/// Authenticated-but-under-privileged callers get `403`. +pub struct RequireTeacher(pub User); + +impl FromRequestParts for RequireTeacher +where + S: Send + Sync, + AppState: FromRef, +{ + type Rejection = AppError; + + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { + let user = authed_user(parts, state).await?; + if !user.get_role().at_least(Role::Teacher) { + return Err(AppError::Forbidden("requires teacher role or higher")); + } + Ok(RequireTeacher(user)) + } +} + +/// Like [`CurrentUser`], but also requires the `admin` role. Anyone below admin +/// gets `403`. +pub struct RequireAdmin(pub User); + +impl FromRequestParts for RequireAdmin +where + S: Send + Sync, + AppState: FromRef, +{ + type Rejection = AppError; + + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { + let user = authed_user(parts, state).await?; + if !user.get_role().at_least(Role::Admin) { + return Err(AppError::Forbidden("requires admin role")); + } + Ok(RequireAdmin(user)) + } +} diff --git a/src/web/mod.rs b/src/web/mod.rs new file mode 100644 index 0000000..19ceb54 --- /dev/null +++ b/src/web/mod.rs @@ -0,0 +1,16 @@ +//! HTTP layer: axum routers, request/response DTOs (serde), and the auth +//! extractors. DTOs are plain strings on the wire; handlers parse them into +//! validated domain newtypes before doing anything. Role-gated endpoints take a +//! `RequireTeacher` / `RequireAdmin` extractor instead of `CurrentUser`. + +pub mod auth; +pub mod events; +pub mod exams; +pub mod notes; +pub mod users; + +mod dto; +mod extractor; + +pub use dto::UserResponse; +pub use extractor::{CurrentUser, RequireAdmin, RequireTeacher}; diff --git a/src/web/notes.rs b/src/web/notes.rs new file mode 100644 index 0000000..df4b44a --- /dev/null +++ b/src/web/notes.rs @@ -0,0 +1,180 @@ +use axum::Json; +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle}; +use crate::error::{AppError, ErrorResponse}; +use crate::state::AppState; + +use super::CurrentUser; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(create, list)) + .routes(routes!(get_one, update, delete_one)) +} + +#[derive(Deserialize, ToSchema)] +struct CreateNote { + #[schema(example = "Groceries")] + title: String, + #[schema(example = "milk, eggs")] + content: Option, +} + +#[derive(Deserialize, ToSchema)] +struct UpdateNote { + title: Option, + content: Option, +} + +#[derive(Serialize, ToSchema)] +struct NoteResponse { + id: String, + title: String, + content: String, +} + +impl NoteResponse { + fn new(note: &Note) -> Self { + Self { + id: note.get_id().key().to_string(), + title: note.get_title().as_str().to_string(), + content: note.get_content().as_str().to_string(), + } + } +} + +/// Create a note owned by the current user. +#[utoipa::path( + post, + path = "/", + tag = "notes", + security(("session_cookie" = [])), + request_body = CreateNote, + responses( + (status = 201, description = "Note created", body = NoteResponse), + (status = 400, description = "Invalid title or content", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn create( + State(st): State, + CurrentUser(user): CurrentUser, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let title = NoteTitle::try_new(&req.title)?; + let content = NoteContent::try_new(&req.content.unwrap_or_default())?; + let note = Note::create(user.get_id(), title, content, &st.db).await?; + Ok((StatusCode::CREATED, Json(NoteResponse::new(¬e)))) +} + +/// List all notes owned by the current user. +#[utoipa::path( + get, + path = "/", + tag = "notes", + security(("session_cookie" = [])), + responses( + (status = 200, description = "The user's notes", body = [NoteResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn list( + State(st): State, + CurrentUser(user): CurrentUser, +) -> Result>, AppError> { + let notes = Note::list_for(user.get_id(), &st.db).await?; + Ok(Json(notes.iter().map(NoteResponse::new).collect())) +} + +/// Fetch a single note by id (must be owned by the current user). +#[utoipa::path( + get, + path = "/{id}", + tag = "notes", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Note id")), + responses( + (status = 200, description = "The note", body = NoteResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn get_one( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + Ok(Json(NoteResponse::new(¬e))) +} + +/// Update a note's title and/or content. Omitted fields keep their value. +#[utoipa::path( + patch, + path = "/{id}", + tag = "notes", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Note id")), + request_body = UpdateNote, + responses( + (status = 200, description = "Updated note", body = NoteResponse), + (status = 400, description = "Invalid title or content", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn update( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + + let title = match req.title { + Some(ref title) => NoteTitle::try_new(title)?, + None => note.get_title().clone(), + }; + let content = match req.content { + Some(ref content) => NoteContent::try_new(content)?, + None => note.get_content().clone(), + }; + + let updated = note.update(title, content, &st.db).await?; + Ok(Json(NoteResponse::new(&updated))) +} + +/// Delete a note owned by the current user. +#[utoipa::path( + delete, + path = "/{id}", + tag = "notes", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Note id")), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn delete_one( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result { + let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + note.delete(&st.db).await?; + Ok(StatusCode::NO_CONTENT) +} diff --git a/src/web/users.rs b/src/web/users.rs new file mode 100644 index 0000000..7f532d5 --- /dev/null +++ b/src/web/users.rs @@ -0,0 +1,84 @@ +use axum::Json; +use axum::extract::{Path, State}; +use serde::Deserialize; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::domain::role::Role; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ErrorResponse}; +use crate::state::AppState; + +use super::dto::Role as RoleSchema; +use super::{RequireAdmin, UserResponse}; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(list_users)) + .routes(routes!(set_role)) +} + +#[derive(Deserialize, ToSchema)] +struct SetRole { + /// The role to assign. Deserialized as a string so an unknown value returns a + /// uniform `400`; documented as the `Role` enum so the docs list the choices. + #[schema(value_type = RoleSchema, example = "teacher")] + role: String, +} + +/// List every user with their role. Admin only. +#[utoipa::path( + get, + path = "/", + tag = "users", + security(("session_cookie" = [])), + responses( + (status = 200, description = "All users", body = [UserResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires admin role", body = ErrorResponse), + ), +)] +async fn list_users( + State(st): State, + _admin: RequireAdmin, +) -> Result>, AppError> { + let users = User::list_all(&st.db).await?; + Ok(Json(users.iter().map(UserResponse::new).collect())) +} + +/// Set a user's role. Admin only. An admin cannot change their own role — that +/// guard keeps a sole admin from accidentally locking everyone out of role +/// management (recover such a lockout with the SurrealQL in the README). +#[utoipa::path( + patch, + path = "/{id}/role", + tag = "users", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "User id")), + request_body = SetRole, + responses( + (status = 200, description = "Updated user", body = UserResponse), + (status = 400, description = "Invalid role", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires admin, or attempted to change own role", body = ErrorResponse), + (status = 404, description = "User not found", body = ErrorResponse), + ), +)] +async fn set_role( + State(st): State, + RequireAdmin(admin): RequireAdmin, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let role = Role::try_from_str(&req.role)?; + let target = UserId::from_key(&id); + if &target == admin.get_id() { + return Err(AppError::Forbidden("cannot change your own role")); + } + let user = User::read(&target, &st.db) + .await? + .ok_or(AppError::NotFound)?; + let updated = user.set_role(role, &st.db).await?; + Ok(Json(UserResponse::new(&updated))) +}