Validated newtypes and entity persistence
Browse files at this commitba2b9b11fc4318f566c2afe75a4f1bcc675e3d1fParent: 0b4bc10- feat
- validated newtypes and entity persistence
10 changed files +1394 -0
- src/domain/attendance.rs +145 -0
- src/domain/event.rs +176 -0
- src/domain/exam.rs +191 -0
- src/domain/exam_result.rs +162 -0
- src/domain/mod.rs +13 -0
- src/domain/note.rs +151 -0
- src/domain/role.rs +96 -0
- src/domain/session.rs +143 -0
- src/domain/timestamp.rs +51 -0
- src/domain/user.rs +266 -0
src/domain/attendance.rsadded+145 -0
| @@ -0,0 +1,145 @@ | |||
| 1 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | + | ||
| 3 | +use crate::database::{ATTENDANCE_TABLE, Database}; | ||
| 4 | +use crate::domain::event::EventId; | ||
| 5 | +use crate::domain::user::UserId; | ||
| 6 | +use crate::error::{AppError, ValidationError}; | ||
| 7 | +use crate::validate::validate_status; | ||
| 8 | + | ||
| 9 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 10 | +pub struct AttendanceId(RecordId); | ||
| 11 | + | ||
| 12 | +impl AttendanceId { | ||
| 13 | + /// A deterministic id for the (event, user) pair. Because the same pair | ||
| 14 | + /// always maps to the same record id, marking is a single atomic UPSERT with | ||
| 15 | + /// no find-then-insert race, and one-row-per-pair holds by construction. | ||
| 16 | + /// ULID keys are alphanumeric, so `_` is an unambiguous joiner. | ||
| 17 | + pub fn composite(event: &EventId, user: &UserId) -> Self { | ||
| 18 | + Self(RecordId::new( | ||
| 19 | + ATTENDANCE_TABLE, | ||
| 20 | + format!("{}_{}", event.key(), user.key()), | ||
| 21 | + )) | ||
| 22 | + } | ||
| 23 | + | ||
| 24 | + pub fn record(&self) -> RecordId { | ||
| 25 | + self.0.clone() | ||
| 26 | + } | ||
| 27 | + | ||
| 28 | + pub fn key(&self) -> &str { | ||
| 29 | + match &self.0.key { | ||
| 30 | + RecordIdKey::String(key) => key, | ||
| 31 | + _ => "", | ||
| 32 | + } | ||
| 33 | + } | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +/// A validated attendance state: present | absent | late | excused. | ||
| 37 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 38 | +pub struct AttendanceStatus(String); | ||
| 39 | + | ||
| 40 | +impl AttendanceStatus { | ||
| 41 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 42 | + validate_status(value)?; | ||
| 43 | + Ok(Self(value.to_string())) | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + pub fn as_str(&self) -> &str { | ||
| 47 | + &self.0 | ||
| 48 | + } | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 52 | +pub struct Attendance { | ||
| 53 | + id: AttendanceId, | ||
| 54 | + event: EventId, | ||
| 55 | + user: UserId, | ||
| 56 | + status: AttendanceStatus, | ||
| 57 | + marked_by: UserId, | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +impl Attendance { | ||
| 61 | + pub fn get_id(&self) -> &AttendanceId { | ||
| 62 | + &self.id | ||
| 63 | + } | ||
| 64 | + | ||
| 65 | + pub fn get_event(&self) -> &EventId { | ||
| 66 | + &self.event | ||
| 67 | + } | ||
| 68 | + | ||
| 69 | + pub fn get_user(&self) -> &UserId { | ||
| 70 | + &self.user | ||
| 71 | + } | ||
| 72 | + | ||
| 73 | + pub fn get_status(&self) -> &AttendanceStatus { | ||
| 74 | + &self.status | ||
| 75 | + } | ||
| 76 | + | ||
| 77 | + pub fn get_marked_by(&self) -> &UserId { | ||
| 78 | + &self.marked_by | ||
| 79 | + } | ||
| 80 | + | ||
| 81 | + /// Record (or overwrite) `user`'s status for `event`. One row per (event, | ||
| 82 | + /// user), keyed by a deterministic composite id so this is a single atomic | ||
| 83 | + /// UPSERT — concurrent marks for the same pair can no longer both insert and | ||
| 84 | + /// collide on the unique index (a 500); they converge on the one row. | ||
| 85 | + pub async fn mark( | ||
| 86 | + event: &EventId, | ||
| 87 | + user: &UserId, | ||
| 88 | + status: AttendanceStatus, | ||
| 89 | + marked_by: &UserId, | ||
| 90 | + db: &Database, | ||
| 91 | + ) -> Result<Attendance, AppError> { | ||
| 92 | + let attendance = Attendance { | ||
| 93 | + id: AttendanceId::composite(event, user), | ||
| 94 | + event: event.clone(), | ||
| 95 | + user: user.clone(), | ||
| 96 | + status, | ||
| 97 | + marked_by: marked_by.clone(), | ||
| 98 | + }; | ||
| 99 | + let saved: Option<Attendance> = db | ||
| 100 | + .upsert(attendance.id.record()) | ||
| 101 | + .content(attendance) | ||
| 102 | + .await?; | ||
| 103 | + saved.ok_or_else(|| AppError::Internal("failed to mark attendance".into())) | ||
| 104 | + } | ||
| 105 | + | ||
| 106 | + pub async fn list_for_event( | ||
| 107 | + event: &EventId, | ||
| 108 | + db: &Database, | ||
| 109 | + ) -> Result<Vec<Attendance>, AppError> { | ||
| 110 | + let mut result = db | ||
| 111 | + .query("SELECT * FROM attendance WHERE event = $ev ORDER BY id DESC") | ||
| 112 | + .bind(("ev", event.record())) | ||
| 113 | + .await? | ||
| 114 | + .check()?; | ||
| 115 | + Ok(result.take::<Vec<Attendance>>(0)?) | ||
| 116 | + } | ||
| 117 | + | ||
| 118 | + pub async fn remove( | ||
| 119 | + event: &EventId, | ||
| 120 | + user: &UserId, | ||
| 121 | + db: &Database, | ||
| 122 | + ) -> Result<Option<Attendance>, AppError> { | ||
| 123 | + let mut result = db | ||
| 124 | + .query("DELETE attendance WHERE event = $ev AND user = $usr RETURN BEFORE") | ||
| 125 | + .bind(("ev", event.record())) | ||
| 126 | + .bind(("usr", user.record())) | ||
| 127 | + .await? | ||
| 128 | + .check()?; | ||
| 129 | + Ok(result.take::<Vec<Attendance>>(0)?.into_iter().next()) | ||
| 130 | + } | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +#[cfg(test)] | ||
| 134 | +mod tests { | ||
| 135 | + use super::*; | ||
| 136 | + | ||
| 137 | + #[tokio::test] | ||
| 138 | + async fn status_must_be_known() { | ||
| 139 | + for status in ["present", "absent", "late", "excused"] { | ||
| 140 | + assert_eq!(AttendanceStatus::try_new(status).unwrap().as_str(), status); | ||
| 141 | + } | ||
| 142 | + assert!(AttendanceStatus::try_new("maybe").is_err()); | ||
| 143 | + assert!(AttendanceStatus::try_new("").is_err()); | ||
| 144 | + } | ||
| 145 | +} | ||
src/domain/event.rsadded+176 -0
| @@ -0,0 +1,176 @@ | |||
| 1 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | +use ulid::Ulid; | ||
| 3 | + | ||
| 4 | +use crate::constant::{MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; | ||
| 5 | +use crate::database::{Database, EVENT_TABLE}; | ||
| 6 | +use crate::domain::timestamp::Timestamp; | ||
| 7 | +use crate::domain::user::UserId; | ||
| 8 | +use crate::error::{AppError, ValidationError}; | ||
| 9 | +use crate::validate::{validate_optional, validate_required}; | ||
| 10 | + | ||
| 11 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 12 | +pub struct EventId(RecordId); | ||
| 13 | + | ||
| 14 | +impl EventId { | ||
| 15 | + pub fn generate() -> Self { | ||
| 16 | + Self(RecordId::new(EVENT_TABLE, Ulid::new().to_string())) | ||
| 17 | + } | ||
| 18 | + | ||
| 19 | + pub fn from_key(key: &str) -> Self { | ||
| 20 | + Self(RecordId::new(EVENT_TABLE, key)) | ||
| 21 | + } | ||
| 22 | + | ||
| 23 | + pub fn record(&self) -> RecordId { | ||
| 24 | + self.0.clone() | ||
| 25 | + } | ||
| 26 | + | ||
| 27 | + pub fn key(&self) -> &str { | ||
| 28 | + match &self.0.key { | ||
| 29 | + RecordIdKey::String(key) => key, | ||
| 30 | + _ => "", | ||
| 31 | + } | ||
| 32 | + } | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 36 | +pub struct EventTitle(String); | ||
| 37 | + | ||
| 38 | +impl EventTitle { | ||
| 39 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 40 | + validate_required("title", value, MAX_EVENT_TITLE_LEN)?; | ||
| 41 | + Ok(Self(value.to_string())) | ||
| 42 | + } | ||
| 43 | + | ||
| 44 | + pub fn as_str(&self) -> &str { | ||
| 45 | + &self.0 | ||
| 46 | + } | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 50 | +pub struct EventDescription(String); | ||
| 51 | + | ||
| 52 | +impl EventDescription { | ||
| 53 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 54 | + validate_optional("description", value, MAX_EVENT_DESCRIPTION_LEN)?; | ||
| 55 | + Ok(Self(value.to_string())) | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + pub fn as_str(&self) -> &str { | ||
| 59 | + &self.0 | ||
| 60 | + } | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 64 | +pub struct Event { | ||
| 65 | + id: EventId, | ||
| 66 | + creator: UserId, | ||
| 67 | + title: EventTitle, | ||
| 68 | + description: EventDescription, | ||
| 69 | + starts_at: Option<Timestamp>, | ||
| 70 | + ends_at: Option<Timestamp>, | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +impl Event { | ||
| 74 | + pub fn get_id(&self) -> &EventId { | ||
| 75 | + &self.id | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + pub fn get_creator(&self) -> &UserId { | ||
| 79 | + &self.creator | ||
| 80 | + } | ||
| 81 | + | ||
| 82 | + pub fn get_title(&self) -> &EventTitle { | ||
| 83 | + &self.title | ||
| 84 | + } | ||
| 85 | + | ||
| 86 | + pub fn get_description(&self) -> &EventDescription { | ||
| 87 | + &self.description | ||
| 88 | + } | ||
| 89 | + | ||
| 90 | + pub fn get_starts_at(&self) -> Option<Timestamp> { | ||
| 91 | + self.starts_at | ||
| 92 | + } | ||
| 93 | + | ||
| 94 | + pub fn get_ends_at(&self) -> Option<Timestamp> { | ||
| 95 | + self.ends_at | ||
| 96 | + } | ||
| 97 | + | ||
| 98 | + pub fn is_creator(&self, user: &UserId) -> bool { | ||
| 99 | + &self.creator == user | ||
| 100 | + } | ||
| 101 | + | ||
| 102 | + pub async fn create( | ||
| 103 | + creator: &UserId, | ||
| 104 | + title: EventTitle, | ||
| 105 | + description: EventDescription, | ||
| 106 | + starts_at: Option<Timestamp>, | ||
| 107 | + ends_at: Option<Timestamp>, | ||
| 108 | + db: &Database, | ||
| 109 | + ) -> Result<Event, AppError> { | ||
| 110 | + let event = Event { | ||
| 111 | + id: EventId::generate(), | ||
| 112 | + creator: creator.clone(), | ||
| 113 | + title, | ||
| 114 | + description, | ||
| 115 | + starts_at, | ||
| 116 | + ends_at, | ||
| 117 | + }; | ||
| 118 | + let created: Option<Event> = db.create(event.id.record()).content(event).await?; | ||
| 119 | + created.ok_or_else(|| AppError::Internal("failed to create event".into())) | ||
| 120 | + } | ||
| 121 | + | ||
| 122 | + pub async fn read(id: &EventId, db: &Database) -> Result<Option<Event>, AppError> { | ||
| 123 | + Ok(db.select(id.record()).await?) | ||
| 124 | + } | ||
| 125 | + | ||
| 126 | + pub async fn list_all(db: &Database) -> Result<Vec<Event>, AppError> { | ||
| 127 | + let mut result = db | ||
| 128 | + .query("SELECT * FROM event ORDER BY id DESC") | ||
| 129 | + .await? | ||
| 130 | + .check()?; | ||
| 131 | + Ok(result.take::<Vec<Event>>(0)?) | ||
| 132 | + } | ||
| 133 | + | ||
| 134 | + pub async fn update( | ||
| 135 | + mut self, | ||
| 136 | + title: EventTitle, | ||
| 137 | + description: EventDescription, | ||
| 138 | + starts_at: Option<Timestamp>, | ||
| 139 | + ends_at: Option<Timestamp>, | ||
| 140 | + db: &Database, | ||
| 141 | + ) -> Result<Event, AppError> { | ||
| 142 | + self.title = title; | ||
| 143 | + self.description = description; | ||
| 144 | + self.starts_at = starts_at; | ||
| 145 | + self.ends_at = ends_at; | ||
| 146 | + let updated: Option<Event> = db.update(self.id.record()).content(self).await?; | ||
| 147 | + updated.ok_or(AppError::NotFound) | ||
| 148 | + } | ||
| 149 | + | ||
| 150 | + /// Delete the event and cascade-remove its attendance rows. | ||
| 151 | + pub async fn delete(self, db: &Database) -> Result<Event, AppError> { | ||
| 152 | + db.query("DELETE attendance WHERE event = $ev") | ||
| 153 | + .bind(("ev", self.id.record())) | ||
| 154 | + .await? | ||
| 155 | + .check()?; | ||
| 156 | + let deleted: Option<Event> = db.delete(self.id.record()).await?; | ||
| 157 | + deleted.ok_or(AppError::NotFound) | ||
| 158 | + } | ||
| 159 | +} | ||
| 160 | + | ||
| 161 | +#[cfg(test)] | ||
| 162 | +mod tests { | ||
| 163 | + use super::*; | ||
| 164 | + | ||
| 165 | + #[tokio::test] | ||
| 166 | + async fn title_is_required() { | ||
| 167 | + assert!(EventTitle::try_new("standup").is_ok()); | ||
| 168 | + assert!(EventTitle::try_new("").is_err()); | ||
| 169 | + assert!(EventTitle::try_new(" ").is_err()); | ||
| 170 | + } | ||
| 171 | + | ||
| 172 | + #[tokio::test] | ||
| 173 | + async fn description_is_optional() { | ||
| 174 | + assert!(EventDescription::try_new("").is_ok()); | ||
| 175 | + } | ||
| 176 | +} | ||
src/domain/exam.rsadded+191 -0
| @@ -0,0 +1,191 @@ | |||
| 1 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | +use ulid::Ulid; | ||
| 3 | + | ||
| 4 | +use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN}; | ||
| 5 | +use crate::database::{Database, EXAM_TABLE}; | ||
| 6 | +use crate::domain::user::UserId; | ||
| 7 | +use crate::error::{AppError, ValidationError}; | ||
| 8 | +use crate::validate::{validate_exam_kind, validate_optional, validate_required}; | ||
| 9 | + | ||
| 10 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 11 | +pub struct ExamId(RecordId); | ||
| 12 | + | ||
| 13 | +impl ExamId { | ||
| 14 | + pub fn generate() -> Self { | ||
| 15 | + Self(RecordId::new(EXAM_TABLE, Ulid::new().to_string())) | ||
| 16 | + } | ||
| 17 | + | ||
| 18 | + pub fn from_key(key: &str) -> Self { | ||
| 19 | + Self(RecordId::new(EXAM_TABLE, key)) | ||
| 20 | + } | ||
| 21 | + | ||
| 22 | + pub fn record(&self) -> RecordId { | ||
| 23 | + self.0.clone() | ||
| 24 | + } | ||
| 25 | + | ||
| 26 | + pub fn key(&self) -> &str { | ||
| 27 | + match &self.0.key { | ||
| 28 | + RecordIdKey::String(key) => key, | ||
| 29 | + _ => "", | ||
| 30 | + } | ||
| 31 | + } | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 35 | +pub struct ExamTitle(String); | ||
| 36 | + | ||
| 37 | +impl ExamTitle { | ||
| 38 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 39 | + validate_required("title", value, MAX_EXAM_TITLE_LEN)?; | ||
| 40 | + Ok(Self(value.to_string())) | ||
| 41 | + } | ||
| 42 | + | ||
| 43 | + pub fn as_str(&self) -> &str { | ||
| 44 | + &self.0 | ||
| 45 | + } | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 49 | +pub struct ExamDescription(String); | ||
| 50 | + | ||
| 51 | +impl ExamDescription { | ||
| 52 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 53 | + validate_optional("description", value, MAX_EXAM_DESCRIPTION_LEN)?; | ||
| 54 | + Ok(Self(value.to_string())) | ||
| 55 | + } | ||
| 56 | + | ||
| 57 | + pub fn as_str(&self) -> &str { | ||
| 58 | + &self.0 | ||
| 59 | + } | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +/// A validated exam kind: `homework` | `quiz`. An exam is never a graded course | ||
| 63 | +/// mark — only one of these two assessment forms. | ||
| 64 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 65 | +pub struct ExamKind(String); | ||
| 66 | + | ||
| 67 | +impl ExamKind { | ||
| 68 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 69 | + validate_exam_kind(value)?; | ||
| 70 | + Ok(Self(value.to_string())) | ||
| 71 | + } | ||
| 72 | + | ||
| 73 | + pub fn as_str(&self) -> &str { | ||
| 74 | + &self.0 | ||
| 75 | + } | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 79 | +pub struct Exam { | ||
| 80 | + id: ExamId, | ||
| 81 | + creator: UserId, | ||
| 82 | + title: ExamTitle, | ||
| 83 | + description: ExamDescription, | ||
| 84 | + kind: ExamKind, | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +impl Exam { | ||
| 88 | + pub fn get_id(&self) -> &ExamId { | ||
| 89 | + &self.id | ||
| 90 | + } | ||
| 91 | + | ||
| 92 | + pub fn get_creator(&self) -> &UserId { | ||
| 93 | + &self.creator | ||
| 94 | + } | ||
| 95 | + | ||
| 96 | + pub fn get_title(&self) -> &ExamTitle { | ||
| 97 | + &self.title | ||
| 98 | + } | ||
| 99 | + | ||
| 100 | + pub fn get_description(&self) -> &ExamDescription { | ||
| 101 | + &self.description | ||
| 102 | + } | ||
| 103 | + | ||
| 104 | + pub fn get_kind(&self) -> &ExamKind { | ||
| 105 | + &self.kind | ||
| 106 | + } | ||
| 107 | + | ||
| 108 | + pub fn is_creator(&self, user: &UserId) -> bool { | ||
| 109 | + &self.creator == user | ||
| 110 | + } | ||
| 111 | + | ||
| 112 | + pub async fn create( | ||
| 113 | + creator: &UserId, | ||
| 114 | + title: ExamTitle, | ||
| 115 | + description: ExamDescription, | ||
| 116 | + kind: ExamKind, | ||
| 117 | + db: &Database, | ||
| 118 | + ) -> Result<Exam, AppError> { | ||
| 119 | + let exam = Exam { | ||
| 120 | + id: ExamId::generate(), | ||
| 121 | + creator: creator.clone(), | ||
| 122 | + title, | ||
| 123 | + description, | ||
| 124 | + kind, | ||
| 125 | + }; | ||
| 126 | + let created: Option<Exam> = db.create(exam.id.record()).content(exam).await?; | ||
| 127 | + created.ok_or_else(|| AppError::Internal("failed to create exam".into())) | ||
| 128 | + } | ||
| 129 | + | ||
| 130 | + pub async fn read(id: &ExamId, db: &Database) -> Result<Option<Exam>, AppError> { | ||
| 131 | + Ok(db.select(id.record()).await?) | ||
| 132 | + } | ||
| 133 | + | ||
| 134 | + pub async fn list_all(db: &Database) -> Result<Vec<Exam>, AppError> { | ||
| 135 | + let mut result = db | ||
| 136 | + .query("SELECT * FROM exam ORDER BY id DESC") | ||
| 137 | + .await? | ||
| 138 | + .check()?; | ||
| 139 | + Ok(result.take::<Vec<Exam>>(0)?) | ||
| 140 | + } | ||
| 141 | + | ||
| 142 | + pub async fn update( | ||
| 143 | + mut self, | ||
| 144 | + title: ExamTitle, | ||
| 145 | + description: ExamDescription, | ||
| 146 | + kind: ExamKind, | ||
| 147 | + db: &Database, | ||
| 148 | + ) -> Result<Exam, AppError> { | ||
| 149 | + self.title = title; | ||
| 150 | + self.description = description; | ||
| 151 | + self.kind = kind; | ||
| 152 | + let updated: Option<Exam> = db.update(self.id.record()).content(self).await?; | ||
| 153 | + updated.ok_or(AppError::NotFound) | ||
| 154 | + } | ||
| 155 | + | ||
| 156 | + /// Delete the exam and cascade-remove its result rows. | ||
| 157 | + pub async fn delete(self, db: &Database) -> Result<Exam, AppError> { | ||
| 158 | + db.query("DELETE exam_result WHERE exam = $ex") | ||
| 159 | + .bind(("ex", self.id.record())) | ||
| 160 | + .await? | ||
| 161 | + .check()?; | ||
| 162 | + let deleted: Option<Exam> = db.delete(self.id.record()).await?; | ||
| 163 | + deleted.ok_or(AppError::NotFound) | ||
| 164 | + } | ||
| 165 | +} | ||
| 166 | + | ||
| 167 | +#[cfg(test)] | ||
| 168 | +mod tests { | ||
| 169 | + use super::*; | ||
| 170 | + | ||
| 171 | + #[tokio::test] | ||
| 172 | + async fn title_is_required() { | ||
| 173 | + assert!(ExamTitle::try_new("midterm").is_ok()); | ||
| 174 | + assert!(ExamTitle::try_new("").is_err()); | ||
| 175 | + assert!(ExamTitle::try_new(" ").is_err()); | ||
| 176 | + } | ||
| 177 | + | ||
| 178 | + #[tokio::test] | ||
| 179 | + async fn description_is_optional() { | ||
| 180 | + assert!(ExamDescription::try_new("").is_ok()); | ||
| 181 | + } | ||
| 182 | + | ||
| 183 | + #[tokio::test] | ||
| 184 | + async fn kind_must_be_known() { | ||
| 185 | + for kind in ["homework", "quiz"] { | ||
| 186 | + assert_eq!(ExamKind::try_new(kind).unwrap().as_str(), kind); | ||
| 187 | + } | ||
| 188 | + assert!(ExamKind::try_new("final").is_err()); | ||
| 189 | + assert!(ExamKind::try_new("").is_err()); | ||
| 190 | + } | ||
| 191 | +} | ||
src/domain/exam_result.rsadded+162 -0
| @@ -0,0 +1,162 @@ | |||
| 1 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | + | ||
| 3 | +use crate::database::{Database, EXAM_RESULT_TABLE}; | ||
| 4 | +use crate::domain::exam::ExamId; | ||
| 5 | +use crate::domain::user::UserId; | ||
| 6 | +use crate::error::{AppError, ValidationError}; | ||
| 7 | +use crate::validate::validate_mark; | ||
| 8 | + | ||
| 9 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 10 | +pub struct ExamResultId(RecordId); | ||
| 11 | + | ||
| 12 | +impl ExamResultId { | ||
| 13 | + /// A deterministic id for the (exam, user) pair. The same pair always maps to | ||
| 14 | + /// the same record id, so grading is a single atomic UPSERT with no | ||
| 15 | + /// find-then-insert race and one-row-per-pair by construction. ULID keys are | ||
| 16 | + /// alphanumeric, so `_` is an unambiguous joiner. | ||
| 17 | + pub fn composite(exam: &ExamId, user: &UserId) -> Self { | ||
| 18 | + Self(RecordId::new( | ||
| 19 | + EXAM_RESULT_TABLE, | ||
| 20 | + format!("{}_{}", exam.key(), user.key()), | ||
| 21 | + )) | ||
| 22 | + } | ||
| 23 | + | ||
| 24 | + pub fn record(&self) -> RecordId { | ||
| 25 | + self.0.clone() | ||
| 26 | + } | ||
| 27 | + | ||
| 28 | + pub fn key(&self) -> &str { | ||
| 29 | + match &self.0.key { | ||
| 30 | + RecordIdKey::String(key) => key, | ||
| 31 | + _ => "", | ||
| 32 | + } | ||
| 33 | + } | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +/// A validated exam mark. Stored as an `int`, held to `[MIN_MARK, MAX_MARK]`. | ||
| 37 | +/// Kept in its own row — an exam result is never a course note. | ||
| 38 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] | ||
| 39 | +pub struct Mark(i64); | ||
| 40 | + | ||
| 41 | +impl Mark { | ||
| 42 | + pub fn try_new(value: i64) -> Result<Self, ValidationError> { | ||
| 43 | + validate_mark(value)?; | ||
| 44 | + Ok(Self(value)) | ||
| 45 | + } | ||
| 46 | + | ||
| 47 | + pub fn as_i64(&self) -> i64 { | ||
| 48 | + self.0 | ||
| 49 | + } | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 53 | +pub struct ExamResult { | ||
| 54 | + id: ExamResultId, | ||
| 55 | + exam: ExamId, | ||
| 56 | + user: UserId, | ||
| 57 | + mark: Mark, | ||
| 58 | + graded_by: UserId, | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +impl ExamResult { | ||
| 62 | + pub fn get_id(&self) -> &ExamResultId { | ||
| 63 | + &self.id | ||
| 64 | + } | ||
| 65 | + | ||
| 66 | + pub fn get_exam(&self) -> &ExamId { | ||
| 67 | + &self.exam | ||
| 68 | + } | ||
| 69 | + | ||
| 70 | + pub fn get_user(&self) -> &UserId { | ||
| 71 | + &self.user | ||
| 72 | + } | ||
| 73 | + | ||
| 74 | + pub fn get_mark(&self) -> Mark { | ||
| 75 | + self.mark | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + pub fn get_graded_by(&self) -> &UserId { | ||
| 79 | + &self.graded_by | ||
| 80 | + } | ||
| 81 | + | ||
| 82 | + async fn find( | ||
| 83 | + exam: &ExamId, | ||
| 84 | + user: &UserId, | ||
| 85 | + db: &Database, | ||
| 86 | + ) -> Result<Option<ExamResult>, AppError> { | ||
| 87 | + let mut result = db | ||
| 88 | + .query("SELECT * FROM exam_result WHERE exam = $ex AND user = $usr LIMIT 1") | ||
| 89 | + .bind(("ex", exam.record())) | ||
| 90 | + .bind(("usr", user.record())) | ||
| 91 | + .await? | ||
| 92 | + .check()?; | ||
| 93 | + Ok(result.take::<Vec<ExamResult>>(0)?.into_iter().next()) | ||
| 94 | + } | ||
| 95 | + | ||
| 96 | + /// A single user's result for an exam, if graded. | ||
| 97 | + pub async fn read_for_user( | ||
| 98 | + exam: &ExamId, | ||
| 99 | + user: &UserId, | ||
| 100 | + db: &Database, | ||
| 101 | + ) -> Result<Option<ExamResult>, AppError> { | ||
| 102 | + Self::find(exam, user, db).await | ||
| 103 | + } | ||
| 104 | + | ||
| 105 | + /// Record (or overwrite) `user`'s mark for `exam`. One row per (exam, user), | ||
| 106 | + /// keyed by a deterministic composite id so this is a single atomic UPSERT — | ||
| 107 | + /// concurrent grades for the same pair converge on one row instead of racing | ||
| 108 | + /// the unique index into a 500. | ||
| 109 | + pub async fn grade( | ||
| 110 | + exam: &ExamId, | ||
| 111 | + user: &UserId, | ||
| 112 | + mark: Mark, | ||
| 113 | + graded_by: &UserId, | ||
| 114 | + db: &Database, | ||
| 115 | + ) -> Result<ExamResult, AppError> { | ||
| 116 | + let result = ExamResult { | ||
| 117 | + id: ExamResultId::composite(exam, user), | ||
| 118 | + exam: exam.clone(), | ||
| 119 | + user: user.clone(), | ||
| 120 | + mark, | ||
| 121 | + graded_by: graded_by.clone(), | ||
| 122 | + }; | ||
| 123 | + let saved: Option<ExamResult> = db.upsert(result.id.record()).content(result).await?; | ||
| 124 | + saved.ok_or_else(|| AppError::Internal("failed to record exam result".into())) | ||
| 125 | + } | ||
| 126 | + | ||
| 127 | + pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<ExamResult>, AppError> { | ||
| 128 | + let mut result = db | ||
| 129 | + .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC") | ||
| 130 | + .bind(("ex", exam.record())) | ||
| 131 | + .await? | ||
| 132 | + .check()?; | ||
| 133 | + Ok(result.take::<Vec<ExamResult>>(0)?) | ||
| 134 | + } | ||
| 135 | + | ||
| 136 | + pub async fn remove( | ||
| 137 | + exam: &ExamId, | ||
| 138 | + user: &UserId, | ||
| 139 | + db: &Database, | ||
| 140 | + ) -> Result<Option<ExamResult>, AppError> { | ||
| 141 | + let mut result = db | ||
| 142 | + .query("DELETE exam_result WHERE exam = $ex AND user = $usr RETURN BEFORE") | ||
| 143 | + .bind(("ex", exam.record())) | ||
| 144 | + .bind(("usr", user.record())) | ||
| 145 | + .await? | ||
| 146 | + .check()?; | ||
| 147 | + Ok(result.take::<Vec<ExamResult>>(0)?.into_iter().next()) | ||
| 148 | + } | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +#[cfg(test)] | ||
| 152 | +mod tests { | ||
| 153 | + use super::*; | ||
| 154 | + | ||
| 155 | + #[tokio::test] | ||
| 156 | + async fn mark_range_is_enforced() { | ||
| 157 | + assert_eq!(Mark::try_new(0).unwrap().as_i64(), 0); | ||
| 158 | + assert_eq!(Mark::try_new(100).unwrap().as_i64(), 100); | ||
| 159 | + assert!(Mark::try_new(-1).is_err()); | ||
| 160 | + assert!(Mark::try_new(101).is_err()); | ||
| 161 | + } | ||
| 162 | +} | ||
src/domain/mod.rsadded+13 -0
| @@ -0,0 +1,13 @@ | |||
| 1 | +//! Domain layer: every value is a validated newtype, and each entity owns its | ||
| 2 | +//! own persistence. Types derive `surrealdb::types::SurrealValue` so the exact | ||
| 3 | +//! same typed value flows from HTTP input all the way into the database. | ||
| 4 | + | ||
| 5 | +pub mod attendance; | ||
| 6 | +pub mod event; | ||
| 7 | +pub mod exam; | ||
| 8 | +pub mod exam_result; | ||
| 9 | +pub mod note; | ||
| 10 | +pub mod role; | ||
| 11 | +pub mod session; | ||
| 12 | +pub mod timestamp; | ||
| 13 | +pub mod user; | ||
src/domain/note.rsadded+151 -0
| @@ -0,0 +1,151 @@ | |||
| 1 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | +use ulid::Ulid; | ||
| 3 | + | ||
| 4 | +use crate::constant::{MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN}; | ||
| 5 | +use crate::database::{Database, NOTE_TABLE}; | ||
| 6 | +use crate::domain::user::UserId; | ||
| 7 | +use crate::error::{AppError, ValidationError}; | ||
| 8 | +use crate::validate::{validate_optional, validate_required}; | ||
| 9 | + | ||
| 10 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 11 | +pub struct NoteId(RecordId); | ||
| 12 | + | ||
| 13 | +impl NoteId { | ||
| 14 | + pub fn generate() -> Self { | ||
| 15 | + Self(RecordId::new(NOTE_TABLE, Ulid::new().to_string())) | ||
| 16 | + } | ||
| 17 | + | ||
| 18 | + pub fn from_key(key: &str) -> Self { | ||
| 19 | + Self(RecordId::new(NOTE_TABLE, key)) | ||
| 20 | + } | ||
| 21 | + | ||
| 22 | + pub fn record(&self) -> RecordId { | ||
| 23 | + self.0.clone() | ||
| 24 | + } | ||
| 25 | + | ||
| 26 | + pub fn key(&self) -> &str { | ||
| 27 | + match &self.0.key { | ||
| 28 | + RecordIdKey::String(key) => key, | ||
| 29 | + _ => "", | ||
| 30 | + } | ||
| 31 | + } | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 35 | +pub struct NoteTitle(String); | ||
| 36 | + | ||
| 37 | +impl NoteTitle { | ||
| 38 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 39 | + validate_required("title", value, MAX_NOTE_TITLE_LEN)?; | ||
| 40 | + Ok(Self(value.to_string())) | ||
| 41 | + } | ||
| 42 | + | ||
| 43 | + pub fn as_str(&self) -> &str { | ||
| 44 | + &self.0 | ||
| 45 | + } | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 49 | +pub struct NoteContent(String); | ||
| 50 | + | ||
| 51 | +impl NoteContent { | ||
| 52 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 53 | + validate_optional("content", value, MAX_NOTE_CONTENT_LEN)?; | ||
| 54 | + Ok(Self(value.to_string())) | ||
| 55 | + } | ||
| 56 | + | ||
| 57 | + pub fn as_str(&self) -> &str { | ||
| 58 | + &self.0 | ||
| 59 | + } | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 63 | +pub struct Note { | ||
| 64 | + id: NoteId, | ||
| 65 | + user: UserId, | ||
| 66 | + title: NoteTitle, | ||
| 67 | + content: NoteContent, | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +impl Note { | ||
| 71 | + pub fn get_id(&self) -> &NoteId { | ||
| 72 | + &self.id | ||
| 73 | + } | ||
| 74 | + | ||
| 75 | + pub fn get_title(&self) -> &NoteTitle { | ||
| 76 | + &self.title | ||
| 77 | + } | ||
| 78 | + | ||
| 79 | + pub fn get_content(&self) -> &NoteContent { | ||
| 80 | + &self.content | ||
| 81 | + } | ||
| 82 | + | ||
| 83 | + pub async fn create( | ||
| 84 | + owner: &UserId, | ||
| 85 | + title: NoteTitle, | ||
| 86 | + content: NoteContent, | ||
| 87 | + db: &Database, | ||
| 88 | + ) -> Result<Note, AppError> { | ||
| 89 | + let note = Note { | ||
| 90 | + id: NoteId::generate(), | ||
| 91 | + user: owner.clone(), | ||
| 92 | + title, | ||
| 93 | + content, | ||
| 94 | + }; | ||
| 95 | + let created: Option<Note> = db.create(note.id.record()).content(note).await?; | ||
| 96 | + created.ok_or_else(|| AppError::Internal("failed to create note".into())) | ||
| 97 | + } | ||
| 98 | + | ||
| 99 | + /// Read a note only if it belongs to `owner`. | ||
| 100 | + pub async fn read_owned( | ||
| 101 | + id: &NoteId, | ||
| 102 | + owner: &UserId, | ||
| 103 | + db: &Database, | ||
| 104 | + ) -> Result<Option<Note>, AppError> { | ||
| 105 | + let note: Option<Note> = db.select(id.record()).await?; | ||
| 106 | + Ok(note.filter(|note| ¬e.user == owner)) | ||
| 107 | + } | ||
| 108 | + | ||
| 109 | + pub async fn list_for(owner: &UserId, db: &Database) -> Result<Vec<Note>, AppError> { | ||
| 110 | + let mut result = db | ||
| 111 | + .query("SELECT * FROM note WHERE user = $usr ORDER BY id DESC") | ||
| 112 | + .bind(("usr", owner.record())) | ||
| 113 | + .await? | ||
| 114 | + .check()?; | ||
| 115 | + Ok(result.take::<Vec<Note>>(0)?) | ||
| 116 | + } | ||
| 117 | + | ||
| 118 | + pub async fn update( | ||
| 119 | + mut self, | ||
| 120 | + title: NoteTitle, | ||
| 121 | + content: NoteContent, | ||
| 122 | + db: &Database, | ||
| 123 | + ) -> Result<Note, AppError> { | ||
| 124 | + self.title = title; | ||
| 125 | + self.content = content; | ||
| 126 | + let updated: Option<Note> = db.update(self.id.record()).content(self).await?; | ||
| 127 | + updated.ok_or(AppError::NotFound) | ||
| 128 | + } | ||
| 129 | + | ||
| 130 | + pub async fn delete(self, db: &Database) -> Result<Note, AppError> { | ||
| 131 | + let deleted: Option<Note> = db.delete(self.id.record()).await?; | ||
| 132 | + deleted.ok_or(AppError::NotFound) | ||
| 133 | + } | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +#[cfg(test)] | ||
| 137 | +mod tests { | ||
| 138 | + use super::*; | ||
| 139 | + | ||
| 140 | + #[tokio::test] | ||
| 141 | + async fn title_is_required() { | ||
| 142 | + assert_eq!(NoteTitle::try_new("hi").unwrap().as_str(), "hi"); | ||
| 143 | + assert!(NoteTitle::try_new(" ").is_err()); | ||
| 144 | + } | ||
| 145 | + | ||
| 146 | + #[tokio::test] | ||
| 147 | + async fn content_is_optional() { | ||
| 148 | + assert_eq!(NoteContent::try_new("").unwrap().as_str(), ""); | ||
| 149 | + assert_eq!(NoteContent::try_new("body").unwrap().as_str(), "body"); | ||
| 150 | + } | ||
| 151 | +} | ||
src/domain/role.rsadded+96 -0
| @@ -0,0 +1,96 @@ | |||
| 1 | +use surrealdb::types::SurrealValue; | ||
| 2 | + | ||
| 3 | +use crate::error::ValidationError; | ||
| 4 | + | ||
| 5 | +/// The four access levels, in ascending order of privilege. | ||
| 6 | +/// | ||
| 7 | +/// The variants are declared low-to-high, so the derived `Ord` matches the | ||
| 8 | +/// hierarchy: `Role::Admin > Role::Teacher`. That ordering is exactly what | ||
| 9 | +/// [`Role::at_least`] relies on — a higher role satisfies any lower requirement. | ||
| 10 | +/// | ||
| 11 | +/// `#[surreal(untagged, rename_all = "lowercase")]` makes each variant serialize | ||
| 12 | +/// to a bare lowercase string (`"student"`, `"teacher"`, …) instead of the | ||
| 13 | +/// default object-wrapped form, so it stores in the `role` column's `TYPE string` | ||
| 14 | +/// and round-trips straight back into the enum. | ||
| 15 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, SurrealValue)] | ||
| 16 | +#[surreal(untagged, rename_all = "lowercase")] | ||
| 17 | +pub enum Role { | ||
| 18 | + Student, | ||
| 19 | + Teacher, | ||
| 20 | + Manager, | ||
| 21 | + Admin, | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +impl Role { | ||
| 25 | + /// Every role, lowest privilege first. | ||
| 26 | + pub const ALL: [Role; 4] = [Role::Student, Role::Teacher, Role::Manager, Role::Admin]; | ||
| 27 | + | ||
| 28 | + /// The wire/storage form. Must stay in lockstep with `rename_all = "lowercase"`. | ||
| 29 | + pub fn as_str(self) -> &'static str { | ||
| 30 | + match self { | ||
| 31 | + Role::Student => "student", | ||
| 32 | + Role::Teacher => "teacher", | ||
| 33 | + Role::Manager => "manager", | ||
| 34 | + Role::Admin => "admin", | ||
| 35 | + } | ||
| 36 | + } | ||
| 37 | + | ||
| 38 | + /// Parse a wire string into a role — the inverse of [`Role::as_str`]. | ||
| 39 | + pub fn try_from_str(value: &str) -> Result<Self, ValidationError> { | ||
| 40 | + Self::ALL | ||
| 41 | + .into_iter() | ||
| 42 | + .find(|role| role.as_str() == value) | ||
| 43 | + .ok_or(ValidationError::Invalid { | ||
| 44 | + field: "role", | ||
| 45 | + reason: "must be one of: student, teacher, manager, admin", | ||
| 46 | + }) | ||
| 47 | + } | ||
| 48 | + | ||
| 49 | + /// True when `self` is at least as privileged as `min` (the hierarchy check). | ||
| 50 | + pub fn at_least(self, min: Role) -> bool { | ||
| 51 | + self >= min | ||
| 52 | + } | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +#[cfg(test)] | ||
| 56 | +mod tests { | ||
| 57 | + use super::*; | ||
| 58 | + use surrealdb::types::Value; | ||
| 59 | + | ||
| 60 | + #[tokio::test] | ||
| 61 | + async fn hierarchy_orders_low_to_high() { | ||
| 62 | + assert!(Role::Student < Role::Teacher); | ||
| 63 | + assert!(Role::Teacher < Role::Manager); | ||
| 64 | + assert!(Role::Manager < Role::Admin); | ||
| 65 | + } | ||
| 66 | + | ||
| 67 | + #[tokio::test] | ||
| 68 | + async fn at_least_is_inclusive_and_upward() { | ||
| 69 | + // A teacher clears the teacher bar and everything below it. | ||
| 70 | + assert!(Role::Teacher.at_least(Role::Teacher)); | ||
| 71 | + assert!(Role::Teacher.at_least(Role::Student)); | ||
| 72 | + assert!(!Role::Teacher.at_least(Role::Manager)); | ||
| 73 | + // Admin clears every bar. | ||
| 74 | + assert!(Role::ALL.iter().all(|&r| Role::Admin.at_least(r))); | ||
| 75 | + } | ||
| 76 | + | ||
| 77 | + #[tokio::test] | ||
| 78 | + async fn str_round_trips() { | ||
| 79 | + for role in Role::ALL { | ||
| 80 | + assert_eq!(Role::try_from_str(role.as_str()).unwrap(), role); | ||
| 81 | + } | ||
| 82 | + assert!(Role::try_from_str("wizard").is_err()); | ||
| 83 | + assert!(Role::try_from_str("").is_err()); | ||
| 84 | + } | ||
| 85 | + | ||
| 86 | + #[tokio::test] | ||
| 87 | + async fn surreal_value_is_a_plain_string() { | ||
| 88 | + // The whole point of `untagged`: the stored value is a bare string, so a | ||
| 89 | + // `TYPE string` column accepts it. Guard that the encoding never regresses. | ||
| 90 | + for role in Role::ALL { | ||
| 91 | + let value = role.into_value(); | ||
| 92 | + assert_eq!(value, Value::String(role.as_str().to_string())); | ||
| 93 | + assert_eq!(Role::from_value(value).unwrap(), role); | ||
| 94 | + } | ||
| 95 | + } | ||
| 96 | +} | ||
src/domain/session.rsadded+143 -0
| @@ -0,0 +1,143 @@ | |||
| 1 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | +use ulid::Ulid; | ||
| 3 | + | ||
| 4 | +use crate::constant::SESSION_DURATION_DAYS; | ||
| 5 | +use crate::database::{Database, SESSION_TABLE}; | ||
| 6 | +use crate::domain::timestamp::Timestamp; | ||
| 7 | +use crate::domain::user::UserId; | ||
| 8 | +use crate::error::AppError; | ||
| 9 | + | ||
| 10 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 11 | +pub struct SessionId(RecordId); | ||
| 12 | + | ||
| 13 | +impl SessionId { | ||
| 14 | + pub fn generate() -> Self { | ||
| 15 | + Self(RecordId::new(SESSION_TABLE, Ulid::new().to_string())) | ||
| 16 | + } | ||
| 17 | + | ||
| 18 | + pub fn record(&self) -> RecordId { | ||
| 19 | + self.0.clone() | ||
| 20 | + } | ||
| 21 | + | ||
| 22 | + #[allow(dead_code)] | ||
| 23 | + pub fn key(&self) -> &str { | ||
| 24 | + match &self.0.key { | ||
| 25 | + RecordIdKey::String(key) => key, | ||
| 26 | + _ => "", | ||
| 27 | + } | ||
| 28 | + } | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +/// A random, opaque session token (64 hex chars). | ||
| 32 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 33 | +pub struct SessionToken(String); | ||
| 34 | + | ||
| 35 | +impl SessionToken { | ||
| 36 | + pub fn generate() -> Result<Self, AppError> { | ||
| 37 | + let mut bytes = [0u8; 32]; | ||
| 38 | + getrandom::fill(&mut bytes).map_err(|e| AppError::Internal(format!("rng: {e}")))?; | ||
| 39 | + Ok(Self(hex::encode(bytes))) | ||
| 40 | + } | ||
| 41 | + | ||
| 42 | + pub fn as_str(&self) -> &str { | ||
| 43 | + &self.0 | ||
| 44 | + } | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 48 | +pub struct Session { | ||
| 49 | + id: SessionId, | ||
| 50 | + user: UserId, | ||
| 51 | + token: SessionToken, | ||
| 52 | + expires_at: Timestamp, | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +impl Session { | ||
| 56 | + pub async fn create(user: &UserId, db: &Database) -> Result<Session, AppError> { | ||
| 57 | + let session = Session { | ||
| 58 | + id: SessionId::generate(), | ||
| 59 | + user: user.clone(), | ||
| 60 | + token: SessionToken::generate()?, | ||
| 61 | + expires_at: Timestamp::in_days(SESSION_DURATION_DAYS), | ||
| 62 | + }; | ||
| 63 | + let created: Option<Session> = db.create(session.id.record()).content(session).await?; | ||
| 64 | + created.ok_or_else(|| AppError::Internal("failed to create session".into())) | ||
| 65 | + } | ||
| 66 | + | ||
| 67 | + pub fn token(&self) -> &SessionToken { | ||
| 68 | + &self.token | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + pub fn user(&self) -> &UserId { | ||
| 72 | + &self.user | ||
| 73 | + } | ||
| 74 | + | ||
| 75 | + pub fn is_expired(&self) -> bool { | ||
| 76 | + self.expires_at.is_past() | ||
| 77 | + } | ||
| 78 | + | ||
| 79 | + pub async fn find_by_token(token: &str, db: &Database) -> Result<Option<Session>, AppError> { | ||
| 80 | + let mut result = db | ||
| 81 | + .query("SELECT * FROM session WHERE token = $tok LIMIT 1") | ||
| 82 | + .bind(("tok", token.to_string())) | ||
| 83 | + .await? | ||
| 84 | + .check()?; | ||
| 85 | + Ok(result.take::<Vec<Session>>(0)?.into_iter().next()) | ||
| 86 | + } | ||
| 87 | + | ||
| 88 | + pub async fn delete_by_token(token: &str, db: &Database) -> Result<(), AppError> { | ||
| 89 | + db.query("DELETE session WHERE token = $tok") | ||
| 90 | + .bind(("tok", token.to_string())) | ||
| 91 | + .await? | ||
| 92 | + .check()?; | ||
| 93 | + Ok(()) | ||
| 94 | + } | ||
| 95 | + | ||
| 96 | + /// Delete every session whose expiry is in the past, returning how many were | ||
| 97 | + /// removed. Expired sessions are already rejected at auth, but nothing else | ||
| 98 | + /// deletes their rows — without this sweep the `session` table grows forever. | ||
| 99 | + pub async fn purge_expired(db: &Database) -> Result<u64, AppError> { | ||
| 100 | + let now = Timestamp::now().as_millis(); | ||
| 101 | + let mut result = db | ||
| 102 | + .query("DELETE session WHERE expires_at < $now RETURN BEFORE") | ||
| 103 | + .bind(("now", now)) | ||
| 104 | + .await? | ||
| 105 | + .check()?; | ||
| 106 | + Ok(result.take::<Vec<Session>>(0)?.len() as u64) | ||
| 107 | + } | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +#[cfg(test)] | ||
| 111 | +mod tests { | ||
| 112 | + use super::*; | ||
| 113 | + | ||
| 114 | + #[tokio::test] | ||
| 115 | + async fn token_is_64_hex_and_unique() { | ||
| 116 | + let token = SessionToken::generate().unwrap(); | ||
| 117 | + assert_eq!(token.as_str().len(), 64); | ||
| 118 | + assert!(token.as_str().chars().all(|c| c.is_ascii_hexdigit())); | ||
| 119 | + assert_ne!(SessionToken::generate().unwrap().as_str(), token.as_str()); | ||
| 120 | + } | ||
| 121 | + | ||
| 122 | + #[tokio::test] | ||
| 123 | + async fn purge_expired_removes_only_past_sessions() { | ||
| 124 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 125 | + db.query( | ||
| 126 | + "CREATE session SET user = type::record('user', 'u'), token = 'past', expires_at = 1; | ||
| 127 | + CREATE session SET user = type::record('user', 'u'), token = 'future', expires_at = 99999999999999;", | ||
| 128 | + ) | ||
| 129 | + .await | ||
| 130 | + .unwrap() | ||
| 131 | + .check() | ||
| 132 | + .unwrap(); | ||
| 133 | + | ||
| 134 | + assert_eq!(Session::purge_expired(&db).await.unwrap(), 1); | ||
| 135 | + assert!(Session::find_by_token("past", &db).await.unwrap().is_none()); | ||
| 136 | + assert!( | ||
| 137 | + Session::find_by_token("future", &db) | ||
| 138 | + .await | ||
| 139 | + .unwrap() | ||
| 140 | + .is_some() | ||
| 141 | + ); | ||
| 142 | + } | ||
| 143 | +} | ||
src/domain/timestamp.rsadded+51 -0
| @@ -0,0 +1,51 @@ | |||
| 1 | +use surrealdb::types::SurrealValue; | ||
| 2 | + | ||
| 3 | +/// A unix-millisecond instant. Stored as an `int`. | ||
| 4 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, SurrealValue)] | ||
| 5 | +pub struct Timestamp(i64); | ||
| 6 | + | ||
| 7 | +impl Timestamp { | ||
| 8 | + pub fn now() -> Self { | ||
| 9 | + Self(chrono::Utc::now().timestamp_millis()) | ||
| 10 | + } | ||
| 11 | + | ||
| 12 | + pub fn in_days(days: i64) -> Self { | ||
| 13 | + Self((chrono::Utc::now() + chrono::Duration::days(days)).timestamp_millis()) | ||
| 14 | + } | ||
| 15 | + | ||
| 16 | + pub fn from_millis(millis: i64) -> Self { | ||
| 17 | + Self(millis) | ||
| 18 | + } | ||
| 19 | + | ||
| 20 | + pub fn as_millis(&self) -> i64 { | ||
| 21 | + self.0 | ||
| 22 | + } | ||
| 23 | + | ||
| 24 | + pub fn is_past(&self) -> bool { | ||
| 25 | + self.0 < Self::now().0 | ||
| 26 | + } | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +#[cfg(test)] | ||
| 30 | +mod tests { | ||
| 31 | + use super::*; | ||
| 32 | + | ||
| 33 | + #[tokio::test] | ||
| 34 | + async fn millis_roundtrip() { | ||
| 35 | + assert_eq!( | ||
| 36 | + Timestamp::from_millis(1_700_000_000_000).as_millis(), | ||
| 37 | + 1_700_000_000_000 | ||
| 38 | + ); | ||
| 39 | + } | ||
| 40 | + | ||
| 41 | + #[tokio::test] | ||
| 42 | + async fn ordering() { | ||
| 43 | + assert!(Timestamp::from_millis(1) < Timestamp::from_millis(2)); | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + #[tokio::test] | ||
| 47 | + async fn expiry_direction() { | ||
| 48 | + assert!(!Timestamp::in_days(1).is_past()); | ||
| 49 | + assert!(Timestamp::in_days(-1).is_past()); | ||
| 50 | + } | ||
| 51 | +} | ||
src/domain/user.rsadded+266 -0
| @@ -0,0 +1,266 @@ | |||
| 1 | +use std::sync::OnceLock; | ||
| 2 | + | ||
| 3 | +use argon2::password_hash::SaltString; | ||
| 4 | +use argon2::{Argon2, PasswordHasher, PasswordVerifier}; | ||
| 5 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 6 | +use ulid::Ulid; | ||
| 7 | + | ||
| 8 | +use crate::database::{Database, USER_TABLE}; | ||
| 9 | +use crate::domain::role::Role; | ||
| 10 | +use crate::error::{AppError, ValidationError}; | ||
| 11 | +use crate::validate::{validate_password, validate_username}; | ||
| 12 | + | ||
| 13 | +/// Typed user record id (`user:<ulid>`). | ||
| 14 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 15 | +pub struct UserId(RecordId); | ||
| 16 | + | ||
| 17 | +impl UserId { | ||
| 18 | + pub fn generate() -> Self { | ||
| 19 | + Self(RecordId::new(USER_TABLE, Ulid::new().to_string())) | ||
| 20 | + } | ||
| 21 | + | ||
| 22 | + pub fn from_key(key: &str) -> Self { | ||
| 23 | + Self(RecordId::new(USER_TABLE, key)) | ||
| 24 | + } | ||
| 25 | + | ||
| 26 | + pub fn record(&self) -> RecordId { | ||
| 27 | + self.0.clone() | ||
| 28 | + } | ||
| 29 | + | ||
| 30 | + pub fn key(&self) -> &str { | ||
| 31 | + match &self.0.key { | ||
| 32 | + RecordIdKey::String(key) => key, | ||
| 33 | + _ => "", | ||
| 34 | + } | ||
| 35 | + } | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// A validated username. Construction guarantees the restrictions hold and | ||
| 39 | +/// canonicalizes the value: the stored string is trimmed, since the unique | ||
| 40 | +/// index and the login lookup key on it — `"ali "` must be `"ali"`, not a | ||
| 41 | +/// second, visually identical account. | ||
| 42 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 43 | +pub struct Username(String); | ||
| 44 | + | ||
| 45 | +impl Username { | ||
| 46 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 47 | + validate_username(value)?; | ||
| 48 | + Ok(Self(value.trim().to_string())) | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + pub fn as_str(&self) -> &str { | ||
| 52 | + &self.0 | ||
| 53 | + } | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +/// A validated plaintext password. Never stored — only hashed or verified. | ||
| 57 | +pub struct Password(String); | ||
| 58 | + | ||
| 59 | +impl Password { | ||
| 60 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 61 | + validate_password(value)?; | ||
| 62 | + Ok(Self(value.to_string())) | ||
| 63 | + } | ||
| 64 | + | ||
| 65 | + pub fn hash(&self) -> Result<PasswordHash, AppError> { | ||
| 66 | + let mut salt_bytes = [0u8; 16]; | ||
| 67 | + getrandom::fill(&mut salt_bytes).map_err(|e| AppError::Internal(format!("rng: {e}")))?; | ||
| 68 | + let salt = SaltString::encode_b64(&salt_bytes) | ||
| 69 | + .map_err(|e| AppError::Internal(format!("salt: {e}")))?; | ||
| 70 | + let hash = Argon2::default() | ||
| 71 | + .hash_password(self.0.as_bytes(), &salt)? | ||
| 72 | + .to_string(); | ||
| 73 | + Ok(PasswordHash(hash)) | ||
| 74 | + } | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +/// An argon2 PHC hash, safe to persist. | ||
| 78 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 79 | +pub struct PasswordHash(String); | ||
| 80 | + | ||
| 81 | +/// A fixed password whose hash is the login decoy (see [`PasswordHash::verify_decoy`]). | ||
| 82 | +/// Not a secret — it never matches a real account. | ||
| 83 | +const DECOY_PASSWORD: &str = "decoy-password-not-a-secret"; | ||
| 84 | + | ||
| 85 | +/// A process-wide decoy hash, computed once on first use. Verifying against it | ||
| 86 | +/// performs the full argon2 work while matching no real account. | ||
| 87 | +fn decoy_hash() -> &'static PasswordHash { | ||
| 88 | + static DECOY: OnceLock<PasswordHash> = OnceLock::new(); | ||
| 89 | + DECOY.get_or_init(|| { | ||
| 90 | + Password::try_new(DECOY_PASSWORD) | ||
| 91 | + .expect("decoy password satisfies the password rules") | ||
| 92 | + .hash() | ||
| 93 | + .expect("decoy password hashes") | ||
| 94 | + }) | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +impl PasswordHash { | ||
| 98 | + pub fn as_str(&self) -> &str { | ||
| 99 | + &self.0 | ||
| 100 | + } | ||
| 101 | + | ||
| 102 | + pub fn verify(&self, password: &Password) -> bool { | ||
| 103 | + match argon2::password_hash::PasswordHash::new(&self.0) { | ||
| 104 | + Ok(parsed) => Argon2::default() | ||
| 105 | + .verify_password(password.0.as_bytes(), &parsed) | ||
| 106 | + .is_ok(), | ||
| 107 | + Err(_) => false, | ||
| 108 | + } | ||
| 109 | + } | ||
| 110 | + | ||
| 111 | + /// Run a throwaway verification against the decoy hash. Login calls this when | ||
| 112 | + /// the username is unknown, so a missing user costs the same argon2 time as a | ||
| 113 | + /// real (wrong-password) check — otherwise the faster reply would let an | ||
| 114 | + /// attacker enumerate valid usernames by timing. | ||
| 115 | + pub fn verify_decoy(password: &Password) { | ||
| 116 | + let _ = decoy_hash().verify(password); | ||
| 117 | + } | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 121 | +pub struct User { | ||
| 122 | + id: UserId, | ||
| 123 | + username: Username, | ||
| 124 | + password_hash: PasswordHash, | ||
| 125 | + role: Role, | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +impl User { | ||
| 129 | + pub fn get_id(&self) -> &UserId { | ||
| 130 | + &self.id | ||
| 131 | + } | ||
| 132 | + | ||
| 133 | + pub fn get_username(&self) -> &Username { | ||
| 134 | + &self.username | ||
| 135 | + } | ||
| 136 | + | ||
| 137 | + pub fn get_password_hash(&self) -> &PasswordHash { | ||
| 138 | + &self.password_hash | ||
| 139 | + } | ||
| 140 | + | ||
| 141 | + pub fn get_role(&self) -> Role { | ||
| 142 | + self.role | ||
| 143 | + } | ||
| 144 | + | ||
| 145 | + /// Register a new account. New users always start as [`Role::Student`]; | ||
| 146 | + /// elevation is a separate, admin-only action (see [`User::set_role`]). | ||
| 147 | + pub async fn create( | ||
| 148 | + username: Username, | ||
| 149 | + password_hash: PasswordHash, | ||
| 150 | + db: &Database, | ||
| 151 | + ) -> Result<User, AppError> { | ||
| 152 | + if Self::find_by_username(username.as_str(), db) | ||
| 153 | + .await? | ||
| 154 | + .is_some() | ||
| 155 | + { | ||
| 156 | + return Err(AppError::Conflict("username already taken")); | ||
| 157 | + } | ||
| 158 | + let user = User { | ||
| 159 | + id: UserId::generate(), | ||
| 160 | + username, | ||
| 161 | + password_hash, | ||
| 162 | + role: Role::Student, | ||
| 163 | + }; | ||
| 164 | + let created: Result<Option<User>, surrealdb::Error> = | ||
| 165 | + db.create(user.id.record()).content(user.clone()).await; | ||
| 166 | + match created { | ||
| 167 | + Ok(Some(created)) => Ok(created), | ||
| 168 | + Ok(None) => Err(AppError::Internal("failed to create user".into())), | ||
| 169 | + // The availability pre-check above is not atomic with the insert: | ||
| 170 | + // two concurrent registrations can both pass it, and the loser then | ||
| 171 | + // trips the unique username index. That loss is the same condition | ||
| 172 | + // as the sequential duplicate, so report the same 409 — not a 500. | ||
| 173 | + Err(err) => { | ||
| 174 | + if Self::find_by_username(user.username.as_str(), db) | ||
| 175 | + .await? | ||
| 176 | + .is_some() | ||
| 177 | + { | ||
| 178 | + Err(AppError::Conflict("username already taken")) | ||
| 179 | + } else { | ||
| 180 | + Err(err.into()) | ||
| 181 | + } | ||
| 182 | + } | ||
| 183 | + } | ||
| 184 | + } | ||
| 185 | + | ||
| 186 | + pub async fn read(id: &UserId, db: &Database) -> Result<Option<User>, AppError> { | ||
| 187 | + Ok(db.select(id.record()).await?) | ||
| 188 | + } | ||
| 189 | + | ||
| 190 | + pub async fn list_all(db: &Database) -> Result<Vec<User>, AppError> { | ||
| 191 | + let mut result = db | ||
| 192 | + .query("SELECT * FROM user ORDER BY id DESC") | ||
| 193 | + .await? | ||
| 194 | + .check()?; | ||
| 195 | + Ok(result.take::<Vec<User>>(0)?) | ||
| 196 | + } | ||
| 197 | + | ||
| 198 | + /// Overwrite this user's role. The caller is responsible for authorizing it. | ||
| 199 | + pub async fn set_role(mut self, role: Role, db: &Database) -> Result<User, AppError> { | ||
| 200 | + self.role = role; | ||
| 201 | + let updated: Option<User> = db.update(self.id.record()).content(self).await?; | ||
| 202 | + updated.ok_or(AppError::NotFound) | ||
| 203 | + } | ||
| 204 | + | ||
| 205 | + pub async fn find_by_username(username: &str, db: &Database) -> Result<Option<User>, AppError> { | ||
| 206 | + let mut result = db | ||
| 207 | + .query("SELECT * FROM user WHERE username = $username LIMIT 1") | ||
| 208 | + .bind(("username", username.to_string())) | ||
| 209 | + .await? | ||
| 210 | + .check()?; | ||
| 211 | + Ok(result.take::<Vec<User>>(0)?.into_iter().next()) | ||
| 212 | + } | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +#[cfg(test)] | ||
| 216 | +mod tests { | ||
| 217 | + use super::*; | ||
| 218 | + | ||
| 219 | + #[tokio::test] | ||
| 220 | + async fn username_newtype_validates() { | ||
| 221 | + assert_eq!(Username::try_new("ali").unwrap().as_str(), "ali"); | ||
| 222 | + assert!(Username::try_new("").is_err()); | ||
| 223 | + assert!(Username::try_new("ab").is_err()); | ||
| 224 | + } | ||
| 225 | + | ||
| 226 | + #[tokio::test] | ||
| 227 | + async fn username_is_stored_trimmed() { | ||
| 228 | + // The unique index and the login lookup key on the *stored* string, so | ||
| 229 | + // padding must not survive construction — otherwise "ali " and "ali" | ||
| 230 | + // become two distinct, visually identical accounts. | ||
| 231 | + assert_eq!(Username::try_new(" ali ").unwrap().as_str(), "ali"); | ||
| 232 | + } | ||
| 233 | + | ||
| 234 | + #[tokio::test] | ||
| 235 | + async fn short_password_rejected() { | ||
| 236 | + assert!(Password::try_new("123").is_err()); | ||
| 237 | + assert!(Password::try_new("secret1").is_ok()); | ||
| 238 | + } | ||
| 239 | + | ||
| 240 | + #[tokio::test] | ||
| 241 | + async fn password_hash_roundtrips() { | ||
| 242 | + let hash = Password::try_new("secret1").unwrap().hash().unwrap(); | ||
| 243 | + assert!(hash.verify(&Password::try_new("secret1").unwrap())); | ||
| 244 | + assert!(!hash.verify(&Password::try_new("wrongpw").unwrap())); | ||
| 245 | + } | ||
| 246 | + | ||
| 247 | + #[tokio::test] | ||
| 248 | + async fn decoy_hash_is_valid_and_nonmatching() { | ||
| 249 | + // The decoy must be a real, parseable argon2 hash. If it ever became | ||
| 250 | + // malformed, verify() would early-return without doing the hashing work | ||
| 251 | + // and the login timing-equalization would silently disappear. | ||
| 252 | + assert!( | ||
| 253 | + decoy_hash().verify(&Password::try_new(DECOY_PASSWORD).unwrap()), | ||
| 254 | + "decoy hash must verify its own password" | ||
| 255 | + ); | ||
| 256 | + assert!(!decoy_hash().verify(&Password::try_new("some-other-pw").unwrap())); | ||
| 257 | + } | ||
| 258 | + | ||
| 259 | + #[tokio::test] | ||
| 260 | + async fn user_id_key_roundtrips() { | ||
| 261 | + let id = UserId::generate(); | ||
| 262 | + let key = id.key().to_string(); | ||
| 263 | + assert!(!key.is_empty()); | ||
| 264 | + assert_eq!(UserId::from_key(&key).key(), key); | ||
| 265 | + } | ||
| 266 | +} | ||