forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

subjects.rs161 lines, 6.6 KiBHistoryRawDownload
1use crate::web::tenant_state::State;
2use axum::Json;
3use axum::extract::Path;
4use axum::http::StatusCode;
5use serde::Deserialize;
6use utoipa::ToSchema;
7use utoipa_axum::router::OpenApiRouter;
8use utoipa_axum::routes;
9
10use crate::database::Database;
11use crate::domain::course::Course;
12use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName};
13use crate::error::{AppError, ErrorResponse};
14use crate::service::course::{can_manage_course, can_view_course};
15use crate::service::subject;
16use crate::state::AppState;
17
18use super::{CurrentUser, RequireTeacher, SubjectResponse};
19
20pub fn routes() -> OpenApiRouter<AppState> {
21 OpenApiRouter::new().routes(routes!(get_subject, update_subject, delete_subject))
22}
23
24#[derive(Deserialize, ToSchema)]
25struct UpdateSubject {
26 #[schema(max_length = 200)]
27 name: Option<String>,
28 #[schema(max_length = 2000)]
29 description: Option<String>,
30}
31
32/// The subject plus its course, or a 404 — every handler here gates on the
33/// parent course, so they always travel together.
34async fn subject_with_course(id: &str, db: &Database) -> Result<(Subject, Course), AppError> {
35 let subject = subject::read(db, &SubjectId::from_key(id))
36 .await?
37 .ok_or(AppError::NotFound)?;
38 let course = crate::service::course::read(db, subject.get_course())
39 .await?
40 .ok_or(AppError::NotFound)?;
41 Ok((subject, course))
42}
43
44/// Fetch a single subject by id. Visible to whoever can view its course: its
45/// creator, a manager/admin, or anyone the course reaches.
46#[utoipa::path(
47 get,
48 path = "/{id}",
49 tag = "subjects",
50 security(("session_cookie" = [])),
51 params(("id" = String, Path, description = "Subject id")),
52 responses(
53 (status = 200, description = "The subject", body = SubjectResponse),
54 (status = 401, description = "Not authenticated", body = ErrorResponse),
55 (status = 403, description = "Not reached by the course, and not its creator or a manager/admin", body = ErrorResponse),
56 (status = 404, description = "Not found", body = ErrorResponse),
57 ),
58)]
59async fn get_subject(
60 State(st): State<AppState>,
61 CurrentUser(user): CurrentUser,
62 Path(id): Path<String>,
63) -> Result<Json<SubjectResponse>, AppError> {
64 let (subject, course) = subject_with_course(&id, &st.db).await?;
65 if !can_view_course(&course, &user, &st.db).await? {
66 return Err(AppError::Forbidden(
67 "only a user this course reaches, its creator, or a manager/admin can view this subject",
68 ));
69 }
70 Ok(Json(SubjectResponse::new(&subject)))
71}
72
73/// Update a subject's name or description. Requires teacher+ and management
74/// rights over its course. Omitted fields keep their value; the course link is
75/// fixed at creation.
76#[utoipa::path(
77 patch,
78 path = "/{id}",
79 tag = "subjects",
80 security(("session_cookie" = [])),
81 params(("id" = String, Path, description = "Subject id")),
82 request_body = UpdateSubject,
83 responses(
84 (status = 200, description = "Updated subject", body = SubjectResponse),
85 (status = 400, description = "Invalid name or description", body = ErrorResponse),
86 (status = 401, description = "Not authenticated", body = ErrorResponse),
87 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
88 (status = 404, description = "Not found", body = ErrorResponse),
89 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
90 ),
91)]
92async fn update_subject(
93 State(st): State<AppState>,
94 RequireTeacher(user): RequireTeacher,
95 Path(id): Path<String>,
96 Json(req): Json<UpdateSubject>,
97) -> Result<Json<SubjectResponse>, AppError> {
98 let (subject, course) = subject_with_course(&id, &st.db).await?;
99 if !can_manage_course(&course, &user) {
100 return Err(AppError::Forbidden(
101 "only the course creator or a manager/admin can edit this subject",
102 ));
103 }
104
105 // Only what the request actually carried is validated and written — an
106 // omitted field stays `None` so the save never re-sends this snapshot's
107 // value over a concurrent PATCH of the other field.
108 let name = req.name.as_deref().map(SubjectName::try_new).transpose()?;
109 let description = req
110 .description
111 .as_deref()
112 .map(SubjectDescription::try_new)
113 .transpose()?;
114
115 let updated = subject::update(&st.db, subject, name, description).await?;
116 Ok(Json(SubjectResponse::new(&updated)))
117}
118
119/// Delete a subject. Requires teacher+ and management rights over its course.
120/// Refused with a 409 while any exam question or homework still references it —
121/// re-tag or delete those first, so nothing is left pointing at a subject that
122/// no longer exists.
123///
124/// Bank templates are the exception: their `subject` is optional origin
125/// metadata, so the delete simply clears it on every template that carried it
126/// instead of refusing. Blocking there was unresolvable (only a template's
127/// owner may re-tag it, so a manager could not clear their own 409) and leaked
128/// the existence of other teachers' private templates.
129#[utoipa::path(
130 delete,
131 path = "/{id}",
132 tag = "subjects",
133 security(("session_cookie" = [])),
134 params(("id" = String, Path, description = "Subject id")),
135 responses(
136 (status = 204, description = "Deleted"),
137 (status = 401, description = "Not authenticated", body = ErrorResponse),
138 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
139 (status = 404, description = "Not found", body = ErrorResponse),
140 (status = 409, description = "Exam questions or homework still reference this subject", body = ErrorResponse),
141 ),
142)]
143async fn delete_subject(
144 State(st): State<AppState>,
145 RequireTeacher(user): RequireTeacher,
146 Path(id): Path<String>,
147) -> Result<StatusCode, AppError> {
148 let (subject, course) = subject_with_course(&id, &st.db).await?;
149 if !can_manage_course(&course, &user) {
150 return Err(AppError::Forbidden(
151 "only the course creator or a manager/admin can delete this subject",
152 ));
153 }
154 // No locks: the two checks *are* the delete's `WHERE`, decided against the
155 // subject's own reference counters inside one statement. This used to be
156 // three process-wide locks (the only site that held more than one) around
157 // two cross-table counts, which were stale by the time the delete landed and
158 // let a concurrent request create a question on a subject being deleted.
159 subject::delete(&st.db, subject).await?;
160 Ok(StatusCode::NO_CONTENT)
161}