forge
Explore
Log in

Don't you dare go Hollow

Axum handlers, DTOs, and auth extractors

Browse files at this commit

3c4822c253dbff83ddb5e91727889c4dc86f2524Ahmet Kaan GümüşParent: ba2b9b1
  • feat
    • axum handlers, DTOs, and auth extractors
Show full message
✨ feat(web): axum handlers, DTOs, and auth extractors

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.rsadded+149 -0
@@ -0,0 +1,149 @@
1+use axum::Json;
2+use axum::extract::{Request, State};
3+use axum::http::StatusCode;
4+use axum::middleware::{self, Next};
5+use axum_extra::extract::CookieJar;
6+use axum_extra::extract::cookie::{Cookie, SameSite};
7+use serde::Deserialize;
8+use utoipa::ToSchema;
9+use utoipa_axum::router::OpenApiRouter;
10+use utoipa_axum::routes;
11+
12+use crate::constant::SESSION_DURATION_DAYS;
13+use crate::domain::session::Session;
14+use crate::domain::user::{Password, PasswordHash, User, Username};
15+use crate::error::{AppError, ErrorResponse};
16+use crate::rate_limit::{RateLimitConfig, RateLimiter};
17+use crate::state::AppState;
18+
19+use super::{CurrentUser, UserResponse};
20+
21+pub fn routes(rate_limit: &RateLimitConfig) -> OpenApiRouter<AppState> {
22+ // Strict per-IP limit on the two credential endpoints only — the
23+ // brute-force and username-enumeration surface. `me` and `logout` stay
24+ // outside it: browser frontends poll `me` on every page load, and being
25+ // over the auth limit must never block an intentional logout.
26+ let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy);
27+ OpenApiRouter::new()
28+ .routes(routes!(register))
29+ .routes(routes!(login))
30+ // `route_layer` wraps only the routes registered above it.
31+ .route_layer(middleware::from_fn(move |req: Request, next: Next| {
32+ let limiter = limiter.clone();
33+ async move { limiter.enforce(req, next).await }
34+ }))
35+ .routes(routes!(logout))
36+ .routes(routes!(me))
37+}
38+
39+#[derive(Deserialize, ToSchema)]
40+struct Credentials {
41+ #[schema(example = "ada")]
42+ username: String,
43+ #[schema(example = "correct horse battery")]
44+ password: String,
45+}
46+
47+/// Register a new user account.
48+#[utoipa::path(
49+ post,
50+ path = "/register",
51+ tag = "auth",
52+ request_body = Credentials,
53+ responses(
54+ (status = 201, description = "Account created", body = UserResponse),
55+ (status = 400, description = "Invalid username or password", body = ErrorResponse),
56+ (status = 409, description = "Username already taken", body = ErrorResponse),
57+ (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse),
58+ ),
59+)]
60+async fn register(
61+ State(st): State<AppState>,
62+ Json(req): Json<Credentials>,
63+) -> Result<(StatusCode, Json<UserResponse>), AppError> {
64+ let username = Username::try_new(&req.username)?;
65+ let password_hash = Password::try_new(&req.password)?.hash()?;
66+ let user = User::create(username, password_hash, &st.db).await?;
67+ Ok((StatusCode::CREATED, Json(UserResponse::new(&user))))
68+}
69+
70+/// Log in with username + password. Sets a `session` cookie on success.
71+#[utoipa::path(
72+ post,
73+ path = "/login",
74+ tag = "auth",
75+ request_body = Credentials,
76+ responses(
77+ (status = 200, description = "Logged in; session cookie set", body = UserResponse),
78+ (status = 401, description = "Bad credentials", body = ErrorResponse),
79+ (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse),
80+ ),
81+)]
82+async fn login(
83+ State(st): State<AppState>,
84+ jar: CookieJar,
85+ Json(req): Json<Credentials>,
86+) -> Result<(CookieJar, Json<UserResponse>), AppError> {
87+ let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?;
88+ // Usernames are stored trimmed (see `Username::try_new`); trim the lookup
89+ // the same way so a padded login attempt matches the canonical name.
90+ let user = match User::find_by_username(req.username.trim(), &st.db).await? {
91+ Some(user) if user.get_password_hash().verify(&password) => user,
92+ Some(_) => return Err(AppError::Unauthorized),
93+ None => {
94+ // No such user. Still do the argon2 work against a decoy so the reply
95+ // takes as long as a real (wrong-password) check — otherwise the
96+ // timing difference leaks which usernames exist.
97+ PasswordHash::verify_decoy(&password);
98+ return Err(AppError::Unauthorized);
99+ }
100+ };
101+
102+ // The caller is genuine; opportunistically drop any expired session rows.
103+ let _ = Session::purge_expired(&st.db).await;
104+
105+ let session = Session::create(user.get_id(), &st.db).await?;
106+ let cookie = Cookie::build(("session", session.token().as_str().to_string()))
107+ .path("/")
108+ .http_only(true)
109+ .secure(st.cookie_secure)
110+ .same_site(SameSite::Lax)
111+ .max_age(time::Duration::days(SESSION_DURATION_DAYS))
112+ .build();
113+
114+ Ok((jar.add(cookie), Json(UserResponse::new(&user))))
115+}
116+
117+/// Log out: revoke the current session (if any) and clear the cookie.
118+/// Idempotent — no session required; answers `204` either way.
119+#[utoipa::path(
120+ post,
121+ path = "/logout",
122+ tag = "auth",
123+ responses((status = 204, description = "Logged out (no-op without a session)")),
124+)]
125+async fn logout(
126+ State(st): State<AppState>,
127+ jar: CookieJar,
128+) -> Result<(CookieJar, StatusCode), AppError> {
129+ if let Some(cookie) = jar.get("session") {
130+ Session::delete_by_token(cookie.value(), &st.db).await?;
131+ }
132+ let jar = jar.remove(Cookie::build(("session", "")).path("/").build());
133+ Ok((jar, StatusCode::NO_CONTENT))
134+}
135+
136+/// Return the currently authenticated user.
137+#[utoipa::path(
138+ get,
139+ path = "/me",
140+ tag = "auth",
141+ security(("session_cookie" = [])),
142+ responses(
143+ (status = 200, description = "The current user", body = UserResponse),
144+ (status = 401, description = "Not authenticated", body = ErrorResponse),
145+ ),
146+)]
147+async fn me(CurrentUser(user): CurrentUser) -> Json<UserResponse> {
148+ Json(UserResponse::new(&user))
149+}
src/web/dto.rsadded+52 -0
@@ -0,0 +1,52 @@
1+//! Response DTOs shared across more than one handler module.
2+
3+use serde::Serialize;
4+use utoipa::ToSchema;
5+
6+use crate::domain::role::Role as DomainRole;
7+use crate::domain::user::User;
8+
9+/// The four access roles, lowest to highest privilege. The web-facing mirror of
10+/// [`crate::domain::role::Role`] — it carries the serde + OpenAPI derives (which
11+/// the domain type deliberately omits), so it renders as a proper `enum` in the
12+/// docs. Serializes to the same lowercase strings the domain stores.
13+#[derive(Serialize, Clone, Copy, ToSchema)]
14+#[serde(rename_all = "lowercase")]
15+pub enum Role {
16+ Student,
17+ Teacher,
18+ Manager,
19+ Admin,
20+}
21+
22+impl From<DomainRole> for Role {
23+ fn from(role: DomainRole) -> Self {
24+ match role {
25+ DomainRole::Student => Role::Student,
26+ DomainRole::Teacher => Role::Teacher,
27+ DomainRole::Manager => Role::Manager,
28+ DomainRole::Admin => Role::Admin,
29+ }
30+ }
31+}
32+
33+/// Public shape of a user: id, username, role. Never carries the password hash.
34+/// Shared by `auth` (register/login/me) and `users` (admin listing/role changes).
35+#[derive(Serialize, ToSchema)]
36+pub struct UserResponse {
37+ #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
38+ pub id: String,
39+ #[schema(example = "ada")]
40+ pub username: String,
41+ pub role: Role,
42+}
43+
44+impl UserResponse {
45+ pub fn new(user: &User) -> Self {
46+ Self {
47+ id: user.get_id().key().to_string(),
48+ username: user.get_username().as_str().to_string(),
49+ role: user.get_role().into(),
50+ }
51+ }
52+}
src/web/events.rsadded+424 -0
@@ -0,0 +1,424 @@
1+use axum::Json;
2+use axum::extract::{Path, State};
3+use axum::http::StatusCode;
4+use serde::{Deserialize, Deserializer, Serialize};
5+use utoipa::ToSchema;
6+use utoipa_axum::router::OpenApiRouter;
7+use utoipa_axum::routes;
8+
9+use crate::domain::attendance::{Attendance, AttendanceStatus};
10+use crate::domain::event::{Event, EventDescription, EventId, EventTitle};
11+use crate::domain::role::Role;
12+use crate::domain::timestamp::Timestamp;
13+use crate::domain::user::{User, UserId};
14+use crate::error::{AppError, ErrorResponse, ValidationError};
15+use crate::state::AppState;
16+
17+use super::{CurrentUser, RequireTeacher};
18+
19+pub fn routes() -> OpenApiRouter<AppState> {
20+ OpenApiRouter::new()
21+ .routes(routes!(create_event, list_events))
22+ .routes(routes!(get_event, update_event, delete_event))
23+ .routes(routes!(mark, list_attendance))
24+ .routes(routes!(remove_attendance))
25+}
26+
27+#[derive(Deserialize, ToSchema)]
28+struct CreateEvent {
29+ #[schema(example = "Sprint demo")]
30+ title: String,
31+ description: Option<String>,
32+ /// Unix-millisecond timestamps.
33+ #[schema(example = 1_700_000_000_000_i64)]
34+ starts_at: Option<i64>,
35+ ends_at: Option<i64>,
36+}
37+
38+/// Distinguishes an *absent* field from an explicit `null`: absent never
39+/// reaches the deserializer and stays `None` via `#[serde(default)]` (keep the
40+/// stored value); `null` or a number lands here as `Some(inner)` (clear or set).
41+fn set_or_clear<'de, D>(de: D) -> Result<Option<Option<i64>>, D::Error>
42+where
43+ D: Deserializer<'de>,
44+{
45+ Option::<i64>::deserialize(de).map(Some)
46+}
47+
48+#[derive(Deserialize, ToSchema)]
49+struct UpdateEvent {
50+ title: Option<String>,
51+ description: Option<String>,
52+ /// Unix-millisecond timestamp. Omit to keep the current value; send `null`
53+ /// to clear it.
54+ #[serde(default, deserialize_with = "set_or_clear")]
55+ #[schema(value_type = Option<i64>)]
56+ starts_at: Option<Option<i64>>,
57+ /// Unix-millisecond timestamp. Omit to keep the current value; send `null`
58+ /// to clear it.
59+ #[serde(default, deserialize_with = "set_or_clear")]
60+ #[schema(value_type = Option<i64>)]
61+ ends_at: Option<Option<i64>>,
62+}
63+
64+#[derive(Deserialize, ToSchema)]
65+struct MarkAttendance {
66+ /// One of the accepted attendance statuses (e.g. `present`, `absent`).
67+ #[schema(example = "present")]
68+ status: String,
69+ /// Target user id. Defaults to the caller when omitted.
70+ user_id: Option<String>,
71+}
72+
73+#[derive(Serialize, ToSchema)]
74+struct EventResponse {
75+ id: String,
76+ creator: String,
77+ title: String,
78+ description: String,
79+ starts_at: Option<i64>,
80+ ends_at: Option<i64>,
81+}
82+
83+impl EventResponse {
84+ fn new(event: &Event) -> Self {
85+ Self {
86+ id: event.get_id().key().to_string(),
87+ creator: event.get_creator().key().to_string(),
88+ title: event.get_title().as_str().to_string(),
89+ description: event.get_description().as_str().to_string(),
90+ starts_at: event.get_starts_at().map(|t| t.as_millis()),
91+ ends_at: event.get_ends_at().map(|t| t.as_millis()),
92+ }
93+ }
94+}
95+
96+/// Who may edit/delete a specific event: its creator, or anyone `manager` and
97+/// above (who can manage any event regardless of ownership). Callers have
98+/// already cleared the `teacher` bar via the `RequireTeacher` extractor.
99+fn can_manage(event: &Event, user: &User) -> bool {
100+ event.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager)
101+}
102+
103+/// If both ends are present, `ends_at` must not precede `starts_at`.
104+fn check_time_range(
105+ starts_at: Option<Timestamp>,
106+ ends_at: Option<Timestamp>,
107+) -> Result<(), AppError> {
108+ if let (Some(starts), Some(ends)) = (starts_at, ends_at)
109+ && ends < starts
110+ {
111+ return Err(AppError::Validation(ValidationError::Invalid {
112+ field: "ends_at",
113+ reason: "must be at or after starts_at",
114+ }));
115+ }
116+ Ok(())
117+}
118+
119+#[derive(Serialize, ToSchema)]
120+struct AttendanceResponse {
121+ id: String,
122+ event: String,
123+ user: String,
124+ status: String,
125+ marked_by: String,
126+}
127+
128+impl AttendanceResponse {
129+ fn new(attendance: &Attendance) -> Self {
130+ Self {
131+ id: attendance.get_id().key().to_string(),
132+ event: attendance.get_event().key().to_string(),
133+ user: attendance.get_user().key().to_string(),
134+ status: attendance.get_status().as_str().to_string(),
135+ marked_by: attendance.get_marked_by().key().to_string(),
136+ }
137+ }
138+}
139+
140+// ---- events -------------------------------------------------------------
141+
142+/// Create an event owned by the current user. Requires the `teacher` role or higher.
143+#[utoipa::path(
144+ post,
145+ path = "/",
146+ tag = "events",
147+ security(("session_cookie" = [])),
148+ request_body = CreateEvent,
149+ responses(
150+ (status = 201, description = "Event created", body = EventResponse),
151+ (status = 400, description = "Invalid fields or time range", body = ErrorResponse),
152+ (status = 401, description = "Not authenticated", body = ErrorResponse),
153+ (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
154+ ),
155+)]
156+async fn create_event(
157+ State(st): State<AppState>,
158+ RequireTeacher(user): RequireTeacher,
159+ Json(req): Json<CreateEvent>,
160+) -> Result<(StatusCode, Json<EventResponse>), AppError> {
161+ let title = EventTitle::try_new(&req.title)?;
162+ let description = EventDescription::try_new(&req.description.unwrap_or_default())?;
163+ let starts_at = req.starts_at.map(Timestamp::from_millis);
164+ let ends_at = req.ends_at.map(Timestamp::from_millis);
165+ check_time_range(starts_at, ends_at)?;
166+ let event = Event::create(
167+ user.get_id(),
168+ title,
169+ description,
170+ starts_at,
171+ ends_at,
172+ &st.db,
173+ )
174+ .await?;
175+ Ok((StatusCode::CREATED, Json(EventResponse::new(&event))))
176+}
177+
178+/// List all events.
179+#[utoipa::path(
180+ get,
181+ path = "/",
182+ tag = "events",
183+ security(("session_cookie" = [])),
184+ responses(
185+ (status = 200, description = "All events", body = [EventResponse]),
186+ (status = 401, description = "Not authenticated", body = ErrorResponse),
187+ ),
188+)]
189+async fn list_events(
190+ State(st): State<AppState>,
191+ _user: CurrentUser,
192+) -> Result<Json<Vec<EventResponse>>, AppError> {
193+ let events = Event::list_all(&st.db).await?;
194+ Ok(Json(events.iter().map(EventResponse::new).collect()))
195+}
196+
197+/// Fetch a single event by id.
198+#[utoipa::path(
199+ get,
200+ path = "/{id}",
201+ tag = "events",
202+ security(("session_cookie" = [])),
203+ params(("id" = String, Path, description = "Event id")),
204+ responses(
205+ (status = 200, description = "The event", body = EventResponse),
206+ (status = 401, description = "Not authenticated", body = ErrorResponse),
207+ (status = 404, description = "Not found", body = ErrorResponse),
208+ ),
209+)]
210+async fn get_event(
211+ State(st): State<AppState>,
212+ _user: CurrentUser,
213+ Path(id): Path<String>,
214+) -> Result<Json<EventResponse>, AppError> {
215+ let event = Event::read(&EventId::from_key(&id), &st.db)
216+ .await?
217+ .ok_or(AppError::NotFound)?;
218+ Ok(Json(EventResponse::new(&event)))
219+}
220+
221+/// Update an event. Requires teacher+; the creator may edit their own event and
222+/// managers/admins may edit anyone's. Omitted fields keep their value; an
223+/// explicit `null` clears `starts_at`/`ends_at`.
224+#[utoipa::path(
225+ patch,
226+ path = "/{id}",
227+ tag = "events",
228+ security(("session_cookie" = [])),
229+ params(("id" = String, Path, description = "Event id")),
230+ request_body = UpdateEvent,
231+ responses(
232+ (status = 200, description = "Updated event", body = EventResponse),
233+ (status = 400, description = "Invalid fields or time range", body = ErrorResponse),
234+ (status = 401, description = "Not authenticated", body = ErrorResponse),
235+ (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse),
236+ (status = 404, description = "Not found", body = ErrorResponse),
237+ ),
238+)]
239+async fn update_event(
240+ State(st): State<AppState>,
241+ RequireTeacher(user): RequireTeacher,
242+ Path(id): Path<String>,
243+ Json(req): Json<UpdateEvent>,
244+) -> Result<Json<EventResponse>, AppError> {
245+ let event = Event::read(&EventId::from_key(&id), &st.db)
246+ .await?
247+ .ok_or(AppError::NotFound)?;
248+ if !can_manage(&event, &user) {
249+ return Err(AppError::Forbidden(
250+ "only the creator or a manager/admin can edit this event",
251+ ));
252+ }
253+
254+ let title = match req.title {
255+ Some(ref title) => EventTitle::try_new(title)?,
256+ None => event.get_title().clone(),
257+ };
258+ let description = match req.description {
259+ Some(ref description) => EventDescription::try_new(description)?,
260+ None => event.get_description().clone(),
261+ };
262+ // A provided value sets the field, an explicit `null` clears it, and an
263+ // omitted one keeps the current value.
264+ let starts_at = match req.starts_at {
265+ Some(update) => update.map(Timestamp::from_millis),
266+ None => event.get_starts_at(),
267+ };
268+ let ends_at = match req.ends_at {
269+ Some(update) => update.map(Timestamp::from_millis),
270+ None => event.get_ends_at(),
271+ };
272+ check_time_range(starts_at, ends_at)?;
273+
274+ let updated = event
275+ .update(title, description, starts_at, ends_at, &st.db)
276+ .await?;
277+ Ok(Json(EventResponse::new(&updated)))
278+}
279+
280+/// Delete an event. Requires teacher+; the creator may delete their own event
281+/// and managers/admins may delete anyone's.
282+#[utoipa::path(
283+ delete,
284+ path = "/{id}",
285+ tag = "events",
286+ security(("session_cookie" = [])),
287+ params(("id" = String, Path, description = "Event id")),
288+ responses(
289+ (status = 204, description = "Deleted"),
290+ (status = 401, description = "Not authenticated", body = ErrorResponse),
291+ (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse),
292+ (status = 404, description = "Not found", body = ErrorResponse),
293+ ),
294+)]
295+async fn delete_event(
296+ State(st): State<AppState>,
297+ RequireTeacher(user): RequireTeacher,
298+ Path(id): Path<String>,
299+) -> Result<StatusCode, AppError> {
300+ let event = Event::read(&EventId::from_key(&id), &st.db)
301+ .await?
302+ .ok_or(AppError::NotFound)?;
303+ if !can_manage(&event, &user) {
304+ return Err(AppError::Forbidden(
305+ "only the creator or a manager/admin can delete this event",
306+ ));
307+ }
308+ event.delete(&st.db).await?;
309+ Ok(StatusCode::NO_CONTENT)
310+}
311+
312+// ---- attendance ---------------------------------------------------------
313+
314+/// Mark attendance for a user on an event (defaults to the caller). Anyone may
315+/// mark their own attendance; marking someone else requires the `teacher` role
316+/// or higher.
317+#[utoipa::path(
318+ post,
319+ path = "/{id}/attendance",
320+ tag = "events",
321+ security(("session_cookie" = [])),
322+ params(("id" = String, Path, description = "Event id")),
323+ request_body = MarkAttendance,
324+ responses(
325+ (status = 200, description = "Attendance recorded", body = AttendanceResponse),
326+ (status = 400, description = "Invalid status or unknown user", body = ErrorResponse),
327+ (status = 401, description = "Not authenticated", body = ErrorResponse),
328+ (status = 403, description = "Marking another user requires teacher role or higher", body = ErrorResponse),
329+ (status = 404, description = "Event not found", body = ErrorResponse),
330+ ),
331+)]
332+async fn mark(
333+ State(st): State<AppState>,
334+ CurrentUser(user): CurrentUser,
335+ Path(id): Path<String>,
336+ Json(req): Json<MarkAttendance>,
337+) -> Result<Json<AttendanceResponse>, AppError> {
338+ let event_id = EventId::from_key(&id);
339+ // Event must exist.
340+ Event::read(&event_id, &st.db)
341+ .await?
342+ .ok_or(AppError::NotFound)?;
343+
344+ let status = AttendanceStatus::try_new(&req.status)?;
345+ let target = match req.user_id {
346+ Some(ref key) => UserId::from_key(key),
347+ None => user.get_id().clone(),
348+ };
349+
350+ // Marking anyone other than yourself is a teacher+ action.
351+ if &target != user.get_id() && !user.get_role().at_least(Role::Teacher) {
352+ return Err(AppError::Forbidden(
353+ "only teachers can mark attendance for other users",
354+ ));
355+ }
356+
357+ // Target user must exist.
358+ if User::read(&target, &st.db).await?.is_none() {
359+ return Err(AppError::Validation(ValidationError::Invalid {
360+ field: "user_id",
361+ reason: "target user does not exist",
362+ }));
363+ }
364+
365+ let attendance = Attendance::mark(&event_id, &target, status, user.get_id(), &st.db).await?;
366+ Ok(Json(AttendanceResponse::new(&attendance)))
367+}
368+
369+/// List the attendance roster for an event.
370+#[utoipa::path(
371+ get,
372+ path = "/{id}/attendance",
373+ tag = "events",
374+ security(("session_cookie" = [])),
375+ params(("id" = String, Path, description = "Event id")),
376+ responses(
377+ (status = 200, description = "Attendance roster", body = [AttendanceResponse]),
378+ (status = 401, description = "Not authenticated", body = ErrorResponse),
379+ (status = 404, description = "Event not found", body = ErrorResponse),
380+ ),
381+)]
382+async fn list_attendance(
383+ State(st): State<AppState>,
384+ _user: CurrentUser,
385+ Path(id): Path<String>,
386+) -> Result<Json<Vec<AttendanceResponse>>, AppError> {
387+ let event_id = EventId::from_key(&id);
388+ // Event must exist — a missing event is a 404, not an empty roster.
389+ Event::read(&event_id, &st.db)
390+ .await?
391+ .ok_or(AppError::NotFound)?;
392+ let roster = Attendance::list_for_event(&event_id, &st.db).await?;
393+ Ok(Json(roster.iter().map(AttendanceResponse::new).collect()))
394+}
395+
396+/// Remove a user's attendance record from an event. Requires teacher+.
397+#[utoipa::path(
398+ delete,
399+ path = "/{id}/attendance/{user}",
400+ tag = "events",
401+ security(("session_cookie" = [])),
402+ params(
403+ ("id" = String, Path, description = "Event id"),
404+ ("user" = String, Path, description = "User id"),
405+ ),
406+ responses(
407+ (status = 204, description = "Removed"),
408+ (status = 401, description = "Not authenticated", body = ErrorResponse),
409+ (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
410+ (status = 404, description = "Not found", body = ErrorResponse),
411+ ),
412+)]
413+async fn remove_attendance(
414+ State(st): State<AppState>,
415+ _teacher: RequireTeacher,
416+ Path((id, target)): Path<(String, String)>,
417+) -> Result<StatusCode, AppError> {
418+ let removed =
419+ Attendance::remove(&EventId::from_key(&id), &UserId::from_key(&target), &st.db).await?;
420+ if removed.is_none() {
421+ return Err(AppError::NotFound);
422+ }
423+ Ok(StatusCode::NO_CONTENT)
424+}
src/web/exams.rsadded+388 -0
@@ -0,0 +1,388 @@
1+use axum::Json;
2+use axum::extract::{Path, State};
3+use axum::http::StatusCode;
4+use serde::{Deserialize, Serialize};
5+use utoipa::ToSchema;
6+use utoipa_axum::router::OpenApiRouter;
7+use utoipa_axum::routes;
8+
9+use crate::domain::exam::{Exam, ExamDescription, ExamId, ExamKind, ExamTitle};
10+use crate::domain::exam_result::{ExamResult, Mark};
11+use crate::domain::role::Role;
12+use crate::domain::user::{User, UserId};
13+use crate::error::{AppError, ErrorResponse, ValidationError};
14+use crate::state::AppState;
15+
16+use super::{CurrentUser, RequireTeacher};
17+
18+pub fn routes() -> OpenApiRouter<AppState> {
19+ OpenApiRouter::new()
20+ .routes(routes!(create_exam, list_exams))
21+ .routes(routes!(get_exam, update_exam, delete_exam))
22+ .routes(routes!(grade, list_results))
23+ .routes(routes!(my_result))
24+ .routes(routes!(remove_result))
25+}
26+
27+#[derive(Deserialize, ToSchema)]
28+struct CreateExam {
29+ #[schema(example = "Chapter 3 quiz")]
30+ title: String,
31+ description: Option<String>,
32+ /// The assessment form: `homework` or `quiz`.
33+ #[schema(example = "quiz")]
34+ kind: String,
35+}
36+
37+#[derive(Deserialize, ToSchema)]
38+struct UpdateExam {
39+ title: Option<String>,
40+ description: Option<String>,
41+ kind: Option<String>,
42+}
43+
44+#[derive(Deserialize, ToSchema)]
45+struct GradeResult {
46+ /// The mark to record, `0`–`100`.
47+ #[schema(example = 85)]
48+ mark: i64,
49+ /// The student being graded.
50+ #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
51+ user_id: String,
52+}
53+
54+#[derive(Serialize, ToSchema)]
55+struct ExamResponse {
56+ id: String,
57+ creator: String,
58+ title: String,
59+ description: String,
60+ kind: String,
61+}
62+
63+impl ExamResponse {
64+ fn new(exam: &Exam) -> Self {
65+ Self {
66+ id: exam.get_id().key().to_string(),
67+ creator: exam.get_creator().key().to_string(),
68+ title: exam.get_title().as_str().to_string(),
69+ description: exam.get_description().as_str().to_string(),
70+ kind: exam.get_kind().as_str().to_string(),
71+ }
72+ }
73+}
74+
75+#[derive(Serialize, ToSchema)]
76+struct ExamResultResponse {
77+ id: String,
78+ exam: String,
79+ user: String,
80+ mark: i64,
81+ graded_by: String,
82+}
83+
84+impl ExamResultResponse {
85+ fn new(result: &ExamResult) -> Self {
86+ Self {
87+ id: result.get_id().key().to_string(),
88+ exam: result.get_exam().key().to_string(),
89+ user: result.get_user().key().to_string(),
90+ mark: result.get_mark().as_i64(),
91+ graded_by: result.get_graded_by().key().to_string(),
92+ }
93+ }
94+}
95+
96+/// Who may edit/delete a specific exam: its creator, or anyone `manager` and
97+/// above. Callers have already cleared the `teacher` bar via `RequireTeacher`.
98+fn can_manage(exam: &Exam, user: &User) -> bool {
99+ exam.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager)
100+}
101+
102+// ---- exams --------------------------------------------------------------
103+
104+/// Create an exam owned by the current user. Requires the `teacher` role or higher.
105+#[utoipa::path(
106+ post,
107+ path = "/",
108+ tag = "exams",
109+ security(("session_cookie" = [])),
110+ request_body = CreateExam,
111+ responses(
112+ (status = 201, description = "Exam created", body = ExamResponse),
113+ (status = 400, description = "Invalid fields or kind", body = ErrorResponse),
114+ (status = 401, description = "Not authenticated", body = ErrorResponse),
115+ (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
116+ ),
117+)]
118+async fn create_exam(
119+ State(st): State<AppState>,
120+ RequireTeacher(user): RequireTeacher,
121+ Json(req): Json<CreateExam>,
122+) -> Result<(StatusCode, Json<ExamResponse>), AppError> {
123+ let title = ExamTitle::try_new(&req.title)?;
124+ let description = ExamDescription::try_new(&req.description.unwrap_or_default())?;
125+ let kind = ExamKind::try_new(&req.kind)?;
126+ let exam = Exam::create(user.get_id(), title, description, kind, &st.db).await?;
127+ Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam))))
128+}
129+
130+/// List all exams.
131+#[utoipa::path(
132+ get,
133+ path = "/",
134+ tag = "exams",
135+ security(("session_cookie" = [])),
136+ responses(
137+ (status = 200, description = "All exams", body = [ExamResponse]),
138+ (status = 401, description = "Not authenticated", body = ErrorResponse),
139+ ),
140+)]
141+async fn list_exams(
142+ State(st): State<AppState>,
143+ _user: CurrentUser,
144+) -> Result<Json<Vec<ExamResponse>>, AppError> {
145+ let exams = Exam::list_all(&st.db).await?;
146+ Ok(Json(exams.iter().map(ExamResponse::new).collect()))
147+}
148+
149+/// Fetch a single exam by id.
150+#[utoipa::path(
151+ get,
152+ path = "/{id}",
153+ tag = "exams",
154+ security(("session_cookie" = [])),
155+ params(("id" = String, Path, description = "Exam id")),
156+ responses(
157+ (status = 200, description = "The exam", body = ExamResponse),
158+ (status = 401, description = "Not authenticated", body = ErrorResponse),
159+ (status = 404, description = "Not found", body = ErrorResponse),
160+ ),
161+)]
162+async fn get_exam(
163+ State(st): State<AppState>,
164+ _user: CurrentUser,
165+ Path(id): Path<String>,
166+) -> Result<Json<ExamResponse>, AppError> {
167+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
168+ .await?
169+ .ok_or(AppError::NotFound)?;
170+ Ok(Json(ExamResponse::new(&exam)))
171+}
172+
173+/// Update an exam. Requires teacher+; the creator may edit their own exam and
174+/// managers/admins may edit anyone's. Omitted fields keep their value.
175+#[utoipa::path(
176+ patch,
177+ path = "/{id}",
178+ tag = "exams",
179+ security(("session_cookie" = [])),
180+ params(("id" = String, Path, description = "Exam id")),
181+ request_body = UpdateExam,
182+ responses(
183+ (status = 200, description = "Updated exam", body = ExamResponse),
184+ (status = 400, description = "Invalid fields or kind", body = ErrorResponse),
185+ (status = 401, description = "Not authenticated", body = ErrorResponse),
186+ (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse),
187+ (status = 404, description = "Not found", body = ErrorResponse),
188+ ),
189+)]
190+async fn update_exam(
191+ State(st): State<AppState>,
192+ RequireTeacher(user): RequireTeacher,
193+ Path(id): Path<String>,
194+ Json(req): Json<UpdateExam>,
195+) -> Result<Json<ExamResponse>, AppError> {
196+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
197+ .await?
198+ .ok_or(AppError::NotFound)?;
199+ if !can_manage(&exam, &user) {
200+ return Err(AppError::Forbidden(
201+ "only the creator or a manager/admin can edit this exam",
202+ ));
203+ }
204+
205+ let title = match req.title {
206+ Some(ref title) => ExamTitle::try_new(title)?,
207+ None => exam.get_title().clone(),
208+ };
209+ let description = match req.description {
210+ Some(ref description) => ExamDescription::try_new(description)?,
211+ None => exam.get_description().clone(),
212+ };
213+ let kind = match req.kind {
214+ Some(ref kind) => ExamKind::try_new(kind)?,
215+ None => exam.get_kind().clone(),
216+ };
217+
218+ let updated = exam.update(title, description, kind, &st.db).await?;
219+ Ok(Json(ExamResponse::new(&updated)))
220+}
221+
222+/// Delete an exam. Requires teacher+; the creator may delete their own exam and
223+/// managers/admins may delete anyone's. Cascades the exam's result rows.
224+#[utoipa::path(
225+ delete,
226+ path = "/{id}",
227+ tag = "exams",
228+ security(("session_cookie" = [])),
229+ params(("id" = String, Path, description = "Exam id")),
230+ responses(
231+ (status = 204, description = "Deleted"),
232+ (status = 401, description = "Not authenticated", body = ErrorResponse),
233+ (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse),
234+ (status = 404, description = "Not found", body = ErrorResponse),
235+ ),
236+)]
237+async fn delete_exam(
238+ State(st): State<AppState>,
239+ RequireTeacher(user): RequireTeacher,
240+ Path(id): Path<String>,
241+) -> Result<StatusCode, AppError> {
242+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
243+ .await?
244+ .ok_or(AppError::NotFound)?;
245+ if !can_manage(&exam, &user) {
246+ return Err(AppError::Forbidden(
247+ "only the creator or a manager/admin can delete this exam",
248+ ));
249+ }
250+ exam.delete(&st.db).await?;
251+ Ok(StatusCode::NO_CONTENT)
252+}
253+
254+// ---- results ------------------------------------------------------------
255+
256+/// Record (or overwrite) a student's mark for an exam. Requires teacher+.
257+/// Students never grade — including themselves.
258+#[utoipa::path(
259+ post,
260+ path = "/{id}/results",
261+ tag = "exams",
262+ security(("session_cookie" = [])),
263+ params(("id" = String, Path, description = "Exam id")),
264+ request_body = GradeResult,
265+ responses(
266+ (status = 200, description = "Result recorded", body = ExamResultResponse),
267+ (status = 400, description = "Invalid mark or unknown user", body = ErrorResponse),
268+ (status = 401, description = "Not authenticated", body = ErrorResponse),
269+ (status = 403, description = "Requires teacher role or higher, or attempted to grade yourself", body = ErrorResponse),
270+ (status = 404, description = "Exam not found", body = ErrorResponse),
271+ ),
272+)]
273+async fn grade(
274+ State(st): State<AppState>,
275+ RequireTeacher(teacher): RequireTeacher,
276+ Path(id): Path<String>,
277+ Json(req): Json<GradeResult>,
278+) -> Result<Json<ExamResultResponse>, AppError> {
279+ let exam_id = ExamId::from_key(&id);
280+ // Exam must exist.
281+ Exam::read(&exam_id, &st.db)
282+ .await?
283+ .ok_or(AppError::NotFound)?;
284+
285+ let mark = Mark::try_new(req.mark)?;
286+ let target = UserId::from_key(&req.user_id);
287+
288+ // Grading never targets oneself — no grader, whatever their role, may
289+ // write their own mark.
290+ if &target == teacher.get_id() {
291+ return Err(AppError::Forbidden("grading yourself is not allowed"));
292+ }
293+
294+ // Target user must exist.
295+ if User::read(&target, &st.db).await?.is_none() {
296+ return Err(AppError::Validation(ValidationError::Invalid {
297+ field: "user_id",
298+ reason: "target user does not exist",
299+ }));
300+ }
301+
302+ let result = ExamResult::grade(&exam_id, &target, mark, teacher.get_id(), &st.db).await?;
303+ Ok(Json(ExamResultResponse::new(&result)))
304+}
305+
306+/// List every result for an exam. Requires teacher+ — students read only their
307+/// own via `GET /exams/{id}/result`.
308+#[utoipa::path(
309+ get,
310+ path = "/{id}/results",
311+ tag = "exams",
312+ security(("session_cookie" = [])),
313+ params(("id" = String, Path, description = "Exam id")),
314+ responses(
315+ (status = 200, description = "All results", body = [ExamResultResponse]),
316+ (status = 401, description = "Not authenticated", body = ErrorResponse),
317+ (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
318+ (status = 404, description = "Exam not found", body = ErrorResponse),
319+ ),
320+)]
321+async fn list_results(
322+ State(st): State<AppState>,
323+ _teacher: RequireTeacher,
324+ Path(id): Path<String>,
325+) -> Result<Json<Vec<ExamResultResponse>>, AppError> {
326+ let exam_id = ExamId::from_key(&id);
327+ // Exam must exist — a missing exam is a 404, not an empty result list.
328+ Exam::read(&exam_id, &st.db)
329+ .await?
330+ .ok_or(AppError::NotFound)?;
331+ let results = ExamResult::list_for_exam(&exam_id, &st.db).await?;
332+ Ok(Json(results.iter().map(ExamResultResponse::new).collect()))
333+}
334+
335+/// The current user's own result for an exam. Any authenticated user may read
336+/// their own mark; `404` while ungraded (or when the exam doesn't exist).
337+#[utoipa::path(
338+ get,
339+ path = "/{id}/result",
340+ tag = "exams",
341+ security(("session_cookie" = [])),
342+ params(("id" = String, Path, description = "Exam id")),
343+ responses(
344+ (status = 200, description = "The caller's result", body = ExamResultResponse),
345+ (status = 401, description = "Not authenticated", body = ErrorResponse),
346+ (status = 404, description = "No such exam, or not graded yet", body = ErrorResponse),
347+ ),
348+)]
349+async fn my_result(
350+ State(st): State<AppState>,
351+ CurrentUser(user): CurrentUser,
352+ Path(id): Path<String>,
353+) -> Result<Json<ExamResultResponse>, AppError> {
354+ let result = ExamResult::read_for_user(&ExamId::from_key(&id), user.get_id(), &st.db)
355+ .await?
356+ .ok_or(AppError::NotFound)?;
357+ Ok(Json(ExamResultResponse::new(&result)))
358+}
359+
360+/// Remove a student's result from an exam. Requires teacher+.
361+#[utoipa::path(
362+ delete,
363+ path = "/{id}/results/{user}",
364+ tag = "exams",
365+ security(("session_cookie" = [])),
366+ params(
367+ ("id" = String, Path, description = "Exam id"),
368+ ("user" = String, Path, description = "User id"),
369+ ),
370+ responses(
371+ (status = 204, description = "Removed"),
372+ (status = 401, description = "Not authenticated", body = ErrorResponse),
373+ (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
374+ (status = 404, description = "Not found", body = ErrorResponse),
375+ ),
376+)]
377+async fn remove_result(
378+ State(st): State<AppState>,
379+ _teacher: RequireTeacher,
380+ Path((id, target)): Path<(String, String)>,
381+) -> Result<StatusCode, AppError> {
382+ let removed =
383+ ExamResult::remove(&ExamId::from_key(&id), &UserId::from_key(&target), &st.db).await?;
384+ if removed.is_none() {
385+ return Err(AppError::NotFound);
386+ }
387+ Ok(StatusCode::NO_CONTENT)
388+}
src/web/extractor.rsadded+95 -0
@@ -0,0 +1,95 @@
1+use axum::extract::{FromRef, FromRequestParts};
2+use axum::http::request::Parts;
3+use axum_extra::extract::CookieJar;
4+
5+use crate::domain::role::Role;
6+use crate::domain::session::Session;
7+use crate::domain::user::User;
8+use crate::error::AppError;
9+use crate::state::AppState;
10+
11+/// Resolve the user behind the `session` cookie, or `401`. The role is read
12+/// fresh from the row on every request, so a role change takes effect on the
13+/// user's next call — no re-login required.
14+async fn authed_user<S>(parts: &mut Parts, state: &S) -> Result<User, AppError>
15+where
16+ S: Send + Sync,
17+ AppState: FromRef<S>,
18+{
19+ let jar = CookieJar::from_request_parts(parts, state)
20+ .await
21+ .map_err(|_| AppError::Unauthorized)?;
22+ let token = jar
23+ .get("session")
24+ .map(|cookie| cookie.value().to_owned())
25+ .ok_or(AppError::Unauthorized)?;
26+
27+ let app = AppState::from_ref(state);
28+
29+ let session = Session::find_by_token(&token, &app.db)
30+ .await?
31+ .ok_or(AppError::Unauthorized)?;
32+ if session.is_expired() {
33+ return Err(AppError::Unauthorized);
34+ }
35+
36+ User::read(session.user(), &app.db)
37+ .await?
38+ .ok_or(AppError::Unauthorized)
39+}
40+
41+/// The authenticated user, resolved from the `session` cookie. Add it as a
42+/// handler argument to require authentication; missing/expired → `401`.
43+pub struct CurrentUser(pub User);
44+
45+impl<S> FromRequestParts<S> for CurrentUser
46+where
47+ S: Send + Sync,
48+ AppState: FromRef<S>,
49+{
50+ type Rejection = AppError;
51+
52+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
53+ Ok(CurrentUser(authed_user(parts, state).await?))
54+ }
55+}
56+
57+/// Like [`CurrentUser`], but also requires at least the `teacher` role.
58+/// Authenticated-but-under-privileged callers get `403`.
59+pub struct RequireTeacher(pub User);
60+
61+impl<S> FromRequestParts<S> for RequireTeacher
62+where
63+ S: Send + Sync,
64+ AppState: FromRef<S>,
65+{
66+ type Rejection = AppError;
67+
68+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
69+ let user = authed_user(parts, state).await?;
70+ if !user.get_role().at_least(Role::Teacher) {
71+ return Err(AppError::Forbidden("requires teacher role or higher"));
72+ }
73+ Ok(RequireTeacher(user))
74+ }
75+}
76+
77+/// Like [`CurrentUser`], but also requires the `admin` role. Anyone below admin
78+/// gets `403`.
79+pub struct RequireAdmin(pub User);
80+
81+impl<S> FromRequestParts<S> for RequireAdmin
82+where
83+ S: Send + Sync,
84+ AppState: FromRef<S>,
85+{
86+ type Rejection = AppError;
87+
88+ async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
89+ let user = authed_user(parts, state).await?;
90+ if !user.get_role().at_least(Role::Admin) {
91+ return Err(AppError::Forbidden("requires admin role"));
92+ }
93+ Ok(RequireAdmin(user))
94+ }
95+}
src/web/mod.rsadded+16 -0
@@ -0,0 +1,16 @@
1+//! HTTP layer: axum routers, request/response DTOs (serde), and the auth
2+//! extractors. DTOs are plain strings on the wire; handlers parse them into
3+//! validated domain newtypes before doing anything. Role-gated endpoints take a
4+//! `RequireTeacher` / `RequireAdmin` extractor instead of `CurrentUser`.
5+
6+pub mod auth;
7+pub mod events;
8+pub mod exams;
9+pub mod notes;
10+pub mod users;
11+
12+mod dto;
13+mod extractor;
14+
15+pub use dto::UserResponse;
16+pub use extractor::{CurrentUser, RequireAdmin, RequireTeacher};
src/web/notes.rsadded+180 -0
@@ -0,0 +1,180 @@
1+use axum::Json;
2+use axum::extract::{Path, State};
3+use axum::http::StatusCode;
4+use serde::{Deserialize, Serialize};
5+use utoipa::ToSchema;
6+use utoipa_axum::router::OpenApiRouter;
7+use utoipa_axum::routes;
8+
9+use crate::domain::note::{Note, NoteContent, NoteId, NoteTitle};
10+use crate::error::{AppError, ErrorResponse};
11+use crate::state::AppState;
12+
13+use super::CurrentUser;
14+
15+pub fn routes() -> OpenApiRouter<AppState> {
16+ OpenApiRouter::new()
17+ .routes(routes!(create, list))
18+ .routes(routes!(get_one, update, delete_one))
19+}
20+
21+#[derive(Deserialize, ToSchema)]
22+struct CreateNote {
23+ #[schema(example = "Groceries")]
24+ title: String,
25+ #[schema(example = "milk, eggs")]
26+ content: Option<String>,
27+}
28+
29+#[derive(Deserialize, ToSchema)]
30+struct UpdateNote {
31+ title: Option<String>,
32+ content: Option<String>,
33+}
34+
35+#[derive(Serialize, ToSchema)]
36+struct NoteResponse {
37+ id: String,
38+ title: String,
39+ content: String,
40+}
41+
42+impl NoteResponse {
43+ fn new(note: &Note) -> Self {
44+ Self {
45+ id: note.get_id().key().to_string(),
46+ title: note.get_title().as_str().to_string(),
47+ content: note.get_content().as_str().to_string(),
48+ }
49+ }
50+}
51+
52+/// Create a note owned by the current user.
53+#[utoipa::path(
54+ post,
55+ path = "/",
56+ tag = "notes",
57+ security(("session_cookie" = [])),
58+ request_body = CreateNote,
59+ responses(
60+ (status = 201, description = "Note created", body = NoteResponse),
61+ (status = 400, description = "Invalid title or content", body = ErrorResponse),
62+ (status = 401, description = "Not authenticated", body = ErrorResponse),
63+ ),
64+)]
65+async fn create(
66+ State(st): State<AppState>,
67+ CurrentUser(user): CurrentUser,
68+ Json(req): Json<CreateNote>,
69+) -> Result<(StatusCode, Json<NoteResponse>), AppError> {
70+ let title = NoteTitle::try_new(&req.title)?;
71+ let content = NoteContent::try_new(&req.content.unwrap_or_default())?;
72+ let note = Note::create(user.get_id(), title, content, &st.db).await?;
73+ Ok((StatusCode::CREATED, Json(NoteResponse::new(&note))))
74+}
75+
76+/// List all notes owned by the current user.
77+#[utoipa::path(
78+ get,
79+ path = "/",
80+ tag = "notes",
81+ security(("session_cookie" = [])),
82+ responses(
83+ (status = 200, description = "The user's notes", body = [NoteResponse]),
84+ (status = 401, description = "Not authenticated", body = ErrorResponse),
85+ ),
86+)]
87+async fn list(
88+ State(st): State<AppState>,
89+ CurrentUser(user): CurrentUser,
90+) -> Result<Json<Vec<NoteResponse>>, AppError> {
91+ let notes = Note::list_for(user.get_id(), &st.db).await?;
92+ Ok(Json(notes.iter().map(NoteResponse::new).collect()))
93+}
94+
95+/// Fetch a single note by id (must be owned by the current user).
96+#[utoipa::path(
97+ get,
98+ path = "/{id}",
99+ tag = "notes",
100+ security(("session_cookie" = [])),
101+ params(("id" = String, Path, description = "Note id")),
102+ responses(
103+ (status = 200, description = "The note", body = NoteResponse),
104+ (status = 401, description = "Not authenticated", body = ErrorResponse),
105+ (status = 404, description = "Not found", body = ErrorResponse),
106+ ),
107+)]
108+async fn get_one(
109+ State(st): State<AppState>,
110+ CurrentUser(user): CurrentUser,
111+ Path(id): Path<String>,
112+) -> Result<Json<NoteResponse>, AppError> {
113+ let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)
114+ .await?
115+ .ok_or(AppError::NotFound)?;
116+ Ok(Json(NoteResponse::new(&note)))
117+}
118+
119+/// Update a note's title and/or content. Omitted fields keep their value.
120+#[utoipa::path(
121+ patch,
122+ path = "/{id}",
123+ tag = "notes",
124+ security(("session_cookie" = [])),
125+ params(("id" = String, Path, description = "Note id")),
126+ request_body = UpdateNote,
127+ responses(
128+ (status = 200, description = "Updated note", body = NoteResponse),
129+ (status = 400, description = "Invalid title or content", body = ErrorResponse),
130+ (status = 401, description = "Not authenticated", body = ErrorResponse),
131+ (status = 404, description = "Not found", body = ErrorResponse),
132+ ),
133+)]
134+async fn update(
135+ State(st): State<AppState>,
136+ CurrentUser(user): CurrentUser,
137+ Path(id): Path<String>,
138+ Json(req): Json<UpdateNote>,
139+) -> Result<Json<NoteResponse>, AppError> {
140+ let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)
141+ .await?
142+ .ok_or(AppError::NotFound)?;
143+
144+ let title = match req.title {
145+ Some(ref title) => NoteTitle::try_new(title)?,
146+ None => note.get_title().clone(),
147+ };
148+ let content = match req.content {
149+ Some(ref content) => NoteContent::try_new(content)?,
150+ None => note.get_content().clone(),
151+ };
152+
153+ let updated = note.update(title, content, &st.db).await?;
154+ Ok(Json(NoteResponse::new(&updated)))
155+}
156+
157+/// Delete a note owned by the current user.
158+#[utoipa::path(
159+ delete,
160+ path = "/{id}",
161+ tag = "notes",
162+ security(("session_cookie" = [])),
163+ params(("id" = String, Path, description = "Note id")),
164+ responses(
165+ (status = 204, description = "Deleted"),
166+ (status = 401, description = "Not authenticated", body = ErrorResponse),
167+ (status = 404, description = "Not found", body = ErrorResponse),
168+ ),
169+)]
170+async fn delete_one(
171+ State(st): State<AppState>,
172+ CurrentUser(user): CurrentUser,
173+ Path(id): Path<String>,
174+) -> Result<StatusCode, AppError> {
175+ let note = Note::read_owned(&NoteId::from_key(&id), user.get_id(), &st.db)
176+ .await?
177+ .ok_or(AppError::NotFound)?;
178+ note.delete(&st.db).await?;
179+ Ok(StatusCode::NO_CONTENT)
180+}
src/web/users.rsadded+84 -0
@@ -0,0 +1,84 @@
1+use axum::Json;
2+use axum::extract::{Path, State};
3+use serde::Deserialize;
4+use utoipa::ToSchema;
5+use utoipa_axum::router::OpenApiRouter;
6+use utoipa_axum::routes;
7+
8+use crate::domain::role::Role;
9+use crate::domain::user::{User, UserId};
10+use crate::error::{AppError, ErrorResponse};
11+use crate::state::AppState;
12+
13+use super::dto::Role as RoleSchema;
14+use super::{RequireAdmin, UserResponse};
15+
16+pub fn routes() -> OpenApiRouter<AppState> {
17+ OpenApiRouter::new()
18+ .routes(routes!(list_users))
19+ .routes(routes!(set_role))
20+}
21+
22+#[derive(Deserialize, ToSchema)]
23+struct SetRole {
24+ /// The role to assign. Deserialized as a string so an unknown value returns a
25+ /// uniform `400`; documented as the `Role` enum so the docs list the choices.
26+ #[schema(value_type = RoleSchema, example = "teacher")]
27+ role: String,
28+}
29+
30+/// List every user with their role. Admin only.
31+#[utoipa::path(
32+ get,
33+ path = "/",
34+ tag = "users",
35+ security(("session_cookie" = [])),
36+ responses(
37+ (status = 200, description = "All users", body = [UserResponse]),
38+ (status = 401, description = "Not authenticated", body = ErrorResponse),
39+ (status = 403, description = "Requires admin role", body = ErrorResponse),
40+ ),
41+)]
42+async fn list_users(
43+ State(st): State<AppState>,
44+ _admin: RequireAdmin,
45+) -> Result<Json<Vec<UserResponse>>, AppError> {
46+ let users = User::list_all(&st.db).await?;
47+ Ok(Json(users.iter().map(UserResponse::new).collect()))
48+}
49+
50+/// Set a user's role. Admin only. An admin cannot change their own role — that
51+/// guard keeps a sole admin from accidentally locking everyone out of role
52+/// management (recover such a lockout with the SurrealQL in the README).
53+#[utoipa::path(
54+ patch,
55+ path = "/{id}/role",
56+ tag = "users",
57+ security(("session_cookie" = [])),
58+ params(("id" = String, Path, description = "User id")),
59+ request_body = SetRole,
60+ responses(
61+ (status = 200, description = "Updated user", body = UserResponse),
62+ (status = 400, description = "Invalid role", body = ErrorResponse),
63+ (status = 401, description = "Not authenticated", body = ErrorResponse),
64+ (status = 403, description = "Requires admin, or attempted to change own role", body = ErrorResponse),
65+ (status = 404, description = "User not found", body = ErrorResponse),
66+ ),
67+)]
68+async fn set_role(
69+ State(st): State<AppState>,
70+ RequireAdmin(admin): RequireAdmin,
71+ Path(id): Path<String>,
72+ Json(req): Json<SetRole>,
73+) -> Result<Json<UserResponse>, AppError> {
74+ let role = Role::try_from_str(&req.role)?;
75+ let target = UserId::from_key(&id);
76+ if &target == admin.get_id() {
77+ return Err(AppError::Forbidden("cannot change your own role"));
78+ }
79+ let user = User::read(&target, &st.db)
80+ .await?
81+ .ok_or(AppError::NotFound)?;
82+ let updated = user.set_role(role, &st.db).await?;
83+ Ok(Json(UserResponse::new(&updated)))
84+}