From ba2b9b11fc4318f566c2afe75a4f1bcc675e3d1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 11 Jul 2026 21:39:14 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(domain):=20validated=20newtype?= =?UTF-8?q?s=20and=20entity=20persistence?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every value is a newtype constructed only after its validator passes (Username, Password, NoteTitle, Mark, ...), so an invalid value can't be represented. Each type derives SurrealValue, so one typed value flows unchanged from HTTP input into the SCHEMAFULL store, and each entity module owns its own persistence. - user/role: argon2-hashed passwords; four hierarchical roles (student < teacher < manager < admin) with at_least() checks. - session: an opaque random token, 7-day expiry, server-side lookup. - note: per-user notes. - event/attendance: events own attendance rows keyed by event+user; optional unix-millisecond starts_at/ends_at with ends >= starts. - exam/exam_result: homework|quiz exams; one 0-100 mark per exam+user in its own row, never on a note. - timestamp: the unix-millisecond instant shared across entities. Record ids are ULIDs — time-sortable and safe to expose. --- src/domain/attendance.rs | 145 +++++++++++++++++++++ src/domain/event.rs | 176 +++++++++++++++++++++++++ src/domain/exam.rs | 191 +++++++++++++++++++++++++++ src/domain/exam_result.rs | 162 +++++++++++++++++++++++ src/domain/mod.rs | 13 ++ src/domain/note.rs | 151 ++++++++++++++++++++++ src/domain/role.rs | 96 ++++++++++++++ src/domain/session.rs | 143 ++++++++++++++++++++ src/domain/timestamp.rs | 51 ++++++++ src/domain/user.rs | 266 ++++++++++++++++++++++++++++++++++++++ 10 files changed, 1394 insertions(+) create mode 100644 src/domain/attendance.rs create mode 100644 src/domain/event.rs create mode 100644 src/domain/exam.rs create mode 100644 src/domain/exam_result.rs create mode 100644 src/domain/mod.rs create mode 100644 src/domain/note.rs create mode 100644 src/domain/role.rs create mode 100644 src/domain/session.rs create mode 100644 src/domain/timestamp.rs create mode 100644 src/domain/user.rs diff --git a/src/domain/attendance.rs b/src/domain/attendance.rs new file mode 100644 index 0000000..42a78e8 --- /dev/null +++ b/src/domain/attendance.rs @@ -0,0 +1,145 @@ +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; + +use crate::database::{ATTENDANCE_TABLE, Database}; +use crate::domain::event::EventId; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::validate_status; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct AttendanceId(RecordId); + +impl AttendanceId { + /// A deterministic id for the (event, user) pair. Because the same pair + /// always maps to the same record id, marking is a single atomic UPSERT with + /// no find-then-insert race, and one-row-per-pair holds by construction. + /// ULID keys are alphanumeric, so `_` is an unambiguous joiner. + pub fn composite(event: &EventId, user: &UserId) -> Self { + Self(RecordId::new( + ATTENDANCE_TABLE, + format!("{}_{}", event.key(), user.key()), + )) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// A validated attendance state: present | absent | late | excused. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct AttendanceStatus(String); + +impl AttendanceStatus { + pub fn try_new(value: &str) -> Result { + validate_status(value)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct Attendance { + id: AttendanceId, + event: EventId, + user: UserId, + status: AttendanceStatus, + marked_by: UserId, +} + +impl Attendance { + pub fn get_id(&self) -> &AttendanceId { + &self.id + } + + pub fn get_event(&self) -> &EventId { + &self.event + } + + pub fn get_user(&self) -> &UserId { + &self.user + } + + pub fn get_status(&self) -> &AttendanceStatus { + &self.status + } + + pub fn get_marked_by(&self) -> &UserId { + &self.marked_by + } + + /// Record (or overwrite) `user`'s status for `event`. One row per (event, + /// user), keyed by a deterministic composite id so this is a single atomic + /// UPSERT — concurrent marks for the same pair can no longer both insert and + /// collide on the unique index (a 500); they converge on the one row. + pub async fn mark( + event: &EventId, + user: &UserId, + status: AttendanceStatus, + marked_by: &UserId, + db: &Database, + ) -> Result { + let attendance = Attendance { + id: AttendanceId::composite(event, user), + event: event.clone(), + user: user.clone(), + status, + marked_by: marked_by.clone(), + }; + let saved: Option = db + .upsert(attendance.id.record()) + .content(attendance) + .await?; + saved.ok_or_else(|| AppError::Internal("failed to mark attendance".into())) + } + + pub async fn list_for_event( + event: &EventId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM attendance WHERE event = $ev ORDER BY id DESC") + .bind(("ev", event.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn remove( + event: &EventId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("DELETE attendance WHERE event = $ev AND user = $usr RETURN BEFORE") + .bind(("ev", event.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn status_must_be_known() { + for status in ["present", "absent", "late", "excused"] { + assert_eq!(AttendanceStatus::try_new(status).unwrap().as_str(), status); + } + assert!(AttendanceStatus::try_new("maybe").is_err()); + assert!(AttendanceStatus::try_new("").is_err()); + } +} diff --git a/src/domain/event.rs b/src/domain/event.rs new file mode 100644 index 0000000..affb0a6 --- /dev/null +++ b/src/domain/event.rs @@ -0,0 +1,176 @@ +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::constant::{MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; +use crate::database::{Database, EVENT_TABLE}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::{validate_optional, validate_required}; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct EventId(RecordId); + +impl EventId { + pub fn generate() -> Self { + Self(RecordId::new(EVENT_TABLE, Ulid::new().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(EVENT_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct EventTitle(String); + +impl EventTitle { + pub fn try_new(value: &str) -> Result { + validate_required("title", value, MAX_EVENT_TITLE_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct EventDescription(String); + +impl EventDescription { + pub fn try_new(value: &str) -> Result { + validate_optional("description", value, MAX_EVENT_DESCRIPTION_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct Event { + id: EventId, + creator: UserId, + title: EventTitle, + description: EventDescription, + starts_at: Option, + ends_at: Option, +} + +impl Event { + pub fn get_id(&self) -> &EventId { + &self.id + } + + pub fn get_creator(&self) -> &UserId { + &self.creator + } + + pub fn get_title(&self) -> &EventTitle { + &self.title + } + + pub fn get_description(&self) -> &EventDescription { + &self.description + } + + pub fn get_starts_at(&self) -> Option { + self.starts_at + } + + pub fn get_ends_at(&self) -> Option { + self.ends_at + } + + pub fn is_creator(&self, user: &UserId) -> bool { + &self.creator == user + } + + pub async fn create( + creator: &UserId, + title: EventTitle, + description: EventDescription, + starts_at: Option, + ends_at: Option, + db: &Database, + ) -> Result { + let event = Event { + id: EventId::generate(), + creator: creator.clone(), + title, + description, + starts_at, + ends_at, + }; + let created: Option = db.create(event.id.record()).content(event).await?; + created.ok_or_else(|| AppError::Internal("failed to create event".into())) + } + + pub async fn read(id: &EventId, db: &Database) -> Result, AppError> { + Ok(db.select(id.record()).await?) + } + + pub async fn list_all(db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM event ORDER BY id DESC") + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn update( + mut self, + title: EventTitle, + description: EventDescription, + starts_at: Option, + ends_at: Option, + db: &Database, + ) -> Result { + self.title = title; + self.description = description; + self.starts_at = starts_at; + self.ends_at = ends_at; + let updated: Option = db.update(self.id.record()).content(self).await?; + updated.ok_or(AppError::NotFound) + } + + /// Delete the event and cascade-remove its attendance rows. + pub async fn delete(self, db: &Database) -> Result { + db.query("DELETE attendance WHERE event = $ev") + .bind(("ev", self.id.record())) + .await? + .check()?; + let deleted: Option = db.delete(self.id.record()).await?; + deleted.ok_or(AppError::NotFound) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn title_is_required() { + assert!(EventTitle::try_new("standup").is_ok()); + assert!(EventTitle::try_new("").is_err()); + assert!(EventTitle::try_new(" ").is_err()); + } + + #[tokio::test] + async fn description_is_optional() { + assert!(EventDescription::try_new("").is_ok()); + } +} diff --git a/src/domain/exam.rs b/src/domain/exam.rs new file mode 100644 index 0000000..09e1710 --- /dev/null +++ b/src/domain/exam.rs @@ -0,0 +1,191 @@ +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN}; +use crate::database::{Database, EXAM_TABLE}; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::{validate_exam_kind, validate_optional, validate_required}; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct ExamId(RecordId); + +impl ExamId { + pub fn generate() -> Self { + Self(RecordId::new(EXAM_TABLE, Ulid::new().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(EXAM_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct ExamTitle(String); + +impl ExamTitle { + pub fn try_new(value: &str) -> Result { + validate_required("title", value, MAX_EXAM_TITLE_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct ExamDescription(String); + +impl ExamDescription { + pub fn try_new(value: &str) -> Result { + validate_optional("description", value, MAX_EXAM_DESCRIPTION_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// A validated exam kind: `homework` | `quiz`. An exam is never a graded course +/// mark — only one of these two assessment forms. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct ExamKind(String); + +impl ExamKind { + pub fn try_new(value: &str) -> Result { + validate_exam_kind(value)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct Exam { + id: ExamId, + creator: UserId, + title: ExamTitle, + description: ExamDescription, + kind: ExamKind, +} + +impl Exam { + pub fn get_id(&self) -> &ExamId { + &self.id + } + + pub fn get_creator(&self) -> &UserId { + &self.creator + } + + pub fn get_title(&self) -> &ExamTitle { + &self.title + } + + pub fn get_description(&self) -> &ExamDescription { + &self.description + } + + pub fn get_kind(&self) -> &ExamKind { + &self.kind + } + + pub fn is_creator(&self, user: &UserId) -> bool { + &self.creator == user + } + + pub async fn create( + creator: &UserId, + title: ExamTitle, + description: ExamDescription, + kind: ExamKind, + db: &Database, + ) -> Result { + let exam = Exam { + id: ExamId::generate(), + creator: creator.clone(), + title, + description, + kind, + }; + let created: Option = db.create(exam.id.record()).content(exam).await?; + created.ok_or_else(|| AppError::Internal("failed to create exam".into())) + } + + pub async fn read(id: &ExamId, db: &Database) -> Result, AppError> { + Ok(db.select(id.record()).await?) + } + + pub async fn list_all(db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM exam ORDER BY id DESC") + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn update( + mut self, + title: ExamTitle, + description: ExamDescription, + kind: ExamKind, + db: &Database, + ) -> Result { + self.title = title; + self.description = description; + self.kind = kind; + let updated: Option = db.update(self.id.record()).content(self).await?; + updated.ok_or(AppError::NotFound) + } + + /// Delete the exam and cascade-remove its result rows. + pub async fn delete(self, db: &Database) -> Result { + db.query("DELETE exam_result WHERE exam = $ex") + .bind(("ex", self.id.record())) + .await? + .check()?; + let deleted: Option = db.delete(self.id.record()).await?; + deleted.ok_or(AppError::NotFound) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn title_is_required() { + assert!(ExamTitle::try_new("midterm").is_ok()); + assert!(ExamTitle::try_new("").is_err()); + assert!(ExamTitle::try_new(" ").is_err()); + } + + #[tokio::test] + async fn description_is_optional() { + assert!(ExamDescription::try_new("").is_ok()); + } + + #[tokio::test] + async fn kind_must_be_known() { + for kind in ["homework", "quiz"] { + assert_eq!(ExamKind::try_new(kind).unwrap().as_str(), kind); + } + assert!(ExamKind::try_new("final").is_err()); + assert!(ExamKind::try_new("").is_err()); + } +} diff --git a/src/domain/exam_result.rs b/src/domain/exam_result.rs new file mode 100644 index 0000000..03d09fc --- /dev/null +++ b/src/domain/exam_result.rs @@ -0,0 +1,162 @@ +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; + +use crate::database::{Database, EXAM_RESULT_TABLE}; +use crate::domain::exam::ExamId; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::validate_mark; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct ExamResultId(RecordId); + +impl ExamResultId { + /// A deterministic id for the (exam, user) pair. The same pair always maps to + /// the same record id, so grading is a single atomic UPSERT with no + /// find-then-insert race and one-row-per-pair by construction. ULID keys are + /// alphanumeric, so `_` is an unambiguous joiner. + pub fn composite(exam: &ExamId, user: &UserId) -> Self { + Self(RecordId::new( + EXAM_RESULT_TABLE, + format!("{}_{}", exam.key(), user.key()), + )) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// A validated exam mark. Stored as an `int`, held to `[MIN_MARK, MAX_MARK]`. +/// Kept in its own row — an exam result is never a course note. +#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] +pub struct Mark(i64); + +impl Mark { + pub fn try_new(value: i64) -> Result { + validate_mark(value)?; + Ok(Self(value)) + } + + pub fn as_i64(&self) -> i64 { + self.0 + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct ExamResult { + id: ExamResultId, + exam: ExamId, + user: UserId, + mark: Mark, + graded_by: UserId, +} + +impl ExamResult { + pub fn get_id(&self) -> &ExamResultId { + &self.id + } + + pub fn get_exam(&self) -> &ExamId { + &self.exam + } + + pub fn get_user(&self) -> &UserId { + &self.user + } + + pub fn get_mark(&self) -> Mark { + self.mark + } + + pub fn get_graded_by(&self) -> &UserId { + &self.graded_by + } + + async fn find( + exam: &ExamId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM exam_result WHERE exam = $ex AND user = $usr LIMIT 1") + .bind(("ex", exam.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } + + /// A single user's result for an exam, if graded. + pub async fn read_for_user( + exam: &ExamId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + Self::find(exam, user, db).await + } + + /// Record (or overwrite) `user`'s mark for `exam`. One row per (exam, user), + /// keyed by a deterministic composite id so this is a single atomic UPSERT — + /// concurrent grades for the same pair converge on one row instead of racing + /// the unique index into a 500. + pub async fn grade( + exam: &ExamId, + user: &UserId, + mark: Mark, + graded_by: &UserId, + db: &Database, + ) -> Result { + let result = ExamResult { + id: ExamResultId::composite(exam, user), + exam: exam.clone(), + user: user.clone(), + mark, + graded_by: graded_by.clone(), + }; + let saved: Option = db.upsert(result.id.record()).content(result).await?; + saved.ok_or_else(|| AppError::Internal("failed to record exam result".into())) + } + + pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC") + .bind(("ex", exam.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn remove( + exam: &ExamId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("DELETE exam_result WHERE exam = $ex AND user = $usr RETURN BEFORE") + .bind(("ex", exam.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn mark_range_is_enforced() { + assert_eq!(Mark::try_new(0).unwrap().as_i64(), 0); + assert_eq!(Mark::try_new(100).unwrap().as_i64(), 100); + assert!(Mark::try_new(-1).is_err()); + assert!(Mark::try_new(101).is_err()); + } +} diff --git a/src/domain/mod.rs b/src/domain/mod.rs new file mode 100644 index 0000000..8a5235e --- /dev/null +++ b/src/domain/mod.rs @@ -0,0 +1,13 @@ +//! Domain layer: every value is a validated newtype, and each entity owns its +//! own persistence. Types derive `surrealdb::types::SurrealValue` so the exact +//! same typed value flows from HTTP input all the way into the database. + +pub mod attendance; +pub mod event; +pub mod exam; +pub mod exam_result; +pub mod note; +pub mod role; +pub mod session; +pub mod timestamp; +pub mod user; diff --git a/src/domain/note.rs b/src/domain/note.rs new file mode 100644 index 0000000..fe3777a --- /dev/null +++ b/src/domain/note.rs @@ -0,0 +1,151 @@ +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::constant::{MAX_NOTE_CONTENT_LEN, MAX_NOTE_TITLE_LEN}; +use crate::database::{Database, NOTE_TABLE}; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::{validate_optional, validate_required}; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct NoteId(RecordId); + +impl NoteId { + pub fn generate() -> Self { + Self(RecordId::new(NOTE_TABLE, Ulid::new().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(NOTE_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct NoteTitle(String); + +impl NoteTitle { + pub fn try_new(value: &str) -> Result { + validate_required("title", value, MAX_NOTE_TITLE_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct NoteContent(String); + +impl NoteContent { + pub fn try_new(value: &str) -> Result { + validate_optional("content", value, MAX_NOTE_CONTENT_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct Note { + id: NoteId, + user: UserId, + title: NoteTitle, + content: NoteContent, +} + +impl Note { + pub fn get_id(&self) -> &NoteId { + &self.id + } + + pub fn get_title(&self) -> &NoteTitle { + &self.title + } + + pub fn get_content(&self) -> &NoteContent { + &self.content + } + + pub async fn create( + owner: &UserId, + title: NoteTitle, + content: NoteContent, + db: &Database, + ) -> Result { + let note = Note { + id: NoteId::generate(), + user: owner.clone(), + title, + content, + }; + let created: Option = db.create(note.id.record()).content(note).await?; + created.ok_or_else(|| AppError::Internal("failed to create note".into())) + } + + /// Read a note only if it belongs to `owner`. + pub async fn read_owned( + id: &NoteId, + owner: &UserId, + db: &Database, + ) -> Result, AppError> { + let note: Option = db.select(id.record()).await?; + Ok(note.filter(|note| ¬e.user == owner)) + } + + pub async fn list_for(owner: &UserId, db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM note WHERE user = $usr ORDER BY id DESC") + .bind(("usr", owner.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn update( + mut self, + title: NoteTitle, + content: NoteContent, + db: &Database, + ) -> Result { + self.title = title; + self.content = content; + let updated: Option = db.update(self.id.record()).content(self).await?; + updated.ok_or(AppError::NotFound) + } + + pub async fn delete(self, db: &Database) -> Result { + let deleted: Option = db.delete(self.id.record()).await?; + deleted.ok_or(AppError::NotFound) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn title_is_required() { + assert_eq!(NoteTitle::try_new("hi").unwrap().as_str(), "hi"); + assert!(NoteTitle::try_new(" ").is_err()); + } + + #[tokio::test] + async fn content_is_optional() { + assert_eq!(NoteContent::try_new("").unwrap().as_str(), ""); + assert_eq!(NoteContent::try_new("body").unwrap().as_str(), "body"); + } +} diff --git a/src/domain/role.rs b/src/domain/role.rs new file mode 100644 index 0000000..b96c3c5 --- /dev/null +++ b/src/domain/role.rs @@ -0,0 +1,96 @@ +use surrealdb::types::SurrealValue; + +use crate::error::ValidationError; + +/// The four access levels, in ascending order of privilege. +/// +/// The variants are declared low-to-high, so the derived `Ord` matches the +/// hierarchy: `Role::Admin > Role::Teacher`. That ordering is exactly what +/// [`Role::at_least`] relies on — a higher role satisfies any lower requirement. +/// +/// `#[surreal(untagged, rename_all = "lowercase")]` makes each variant serialize +/// to a bare lowercase string (`"student"`, `"teacher"`, …) instead of the +/// default object-wrapped form, so it stores in the `role` column's `TYPE string` +/// and round-trips straight back into the enum. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, SurrealValue)] +#[surreal(untagged, rename_all = "lowercase")] +pub enum Role { + Student, + Teacher, + Manager, + Admin, +} + +impl Role { + /// Every role, lowest privilege first. + pub const ALL: [Role; 4] = [Role::Student, Role::Teacher, Role::Manager, Role::Admin]; + + /// The wire/storage form. Must stay in lockstep with `rename_all = "lowercase"`. + pub fn as_str(self) -> &'static str { + match self { + Role::Student => "student", + Role::Teacher => "teacher", + Role::Manager => "manager", + Role::Admin => "admin", + } + } + + /// Parse a wire string into a role — the inverse of [`Role::as_str`]. + pub fn try_from_str(value: &str) -> Result { + Self::ALL + .into_iter() + .find(|role| role.as_str() == value) + .ok_or(ValidationError::Invalid { + field: "role", + reason: "must be one of: student, teacher, manager, admin", + }) + } + + /// True when `self` is at least as privileged as `min` (the hierarchy check). + pub fn at_least(self, min: Role) -> bool { + self >= min + } +} + +#[cfg(test)] +mod tests { + use super::*; + use surrealdb::types::Value; + + #[tokio::test] + async fn hierarchy_orders_low_to_high() { + assert!(Role::Student < Role::Teacher); + assert!(Role::Teacher < Role::Manager); + assert!(Role::Manager < Role::Admin); + } + + #[tokio::test] + async fn at_least_is_inclusive_and_upward() { + // A teacher clears the teacher bar and everything below it. + assert!(Role::Teacher.at_least(Role::Teacher)); + assert!(Role::Teacher.at_least(Role::Student)); + assert!(!Role::Teacher.at_least(Role::Manager)); + // Admin clears every bar. + assert!(Role::ALL.iter().all(|&r| Role::Admin.at_least(r))); + } + + #[tokio::test] + async fn str_round_trips() { + for role in Role::ALL { + assert_eq!(Role::try_from_str(role.as_str()).unwrap(), role); + } + assert!(Role::try_from_str("wizard").is_err()); + assert!(Role::try_from_str("").is_err()); + } + + #[tokio::test] + async fn surreal_value_is_a_plain_string() { + // The whole point of `untagged`: the stored value is a bare string, so a + // `TYPE string` column accepts it. Guard that the encoding never regresses. + for role in Role::ALL { + let value = role.into_value(); + assert_eq!(value, Value::String(role.as_str().to_string())); + assert_eq!(Role::from_value(value).unwrap(), role); + } + } +} diff --git a/src/domain/session.rs b/src/domain/session.rs new file mode 100644 index 0000000..1e28683 --- /dev/null +++ b/src/domain/session.rs @@ -0,0 +1,143 @@ +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::constant::SESSION_DURATION_DAYS; +use crate::database::{Database, SESSION_TABLE}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct SessionId(RecordId); + +impl SessionId { + pub fn generate() -> Self { + Self(RecordId::new(SESSION_TABLE, Ulid::new().to_string())) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + #[allow(dead_code)] + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// A random, opaque session token (64 hex chars). +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct SessionToken(String); + +impl SessionToken { + pub fn generate() -> Result { + let mut bytes = [0u8; 32]; + getrandom::fill(&mut bytes).map_err(|e| AppError::Internal(format!("rng: {e}")))?; + Ok(Self(hex::encode(bytes))) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct Session { + id: SessionId, + user: UserId, + token: SessionToken, + expires_at: Timestamp, +} + +impl Session { + pub async fn create(user: &UserId, db: &Database) -> Result { + let session = Session { + id: SessionId::generate(), + user: user.clone(), + token: SessionToken::generate()?, + expires_at: Timestamp::in_days(SESSION_DURATION_DAYS), + }; + let created: Option = db.create(session.id.record()).content(session).await?; + created.ok_or_else(|| AppError::Internal("failed to create session".into())) + } + + pub fn token(&self) -> &SessionToken { + &self.token + } + + pub fn user(&self) -> &UserId { + &self.user + } + + pub fn is_expired(&self) -> bool { + self.expires_at.is_past() + } + + pub async fn find_by_token(token: &str, db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM session WHERE token = $tok LIMIT 1") + .bind(("tok", token.to_string())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } + + pub async fn delete_by_token(token: &str, db: &Database) -> Result<(), AppError> { + db.query("DELETE session WHERE token = $tok") + .bind(("tok", token.to_string())) + .await? + .check()?; + Ok(()) + } + + /// Delete every session whose expiry is in the past, returning how many were + /// removed. Expired sessions are already rejected at auth, but nothing else + /// deletes their rows — without this sweep the `session` table grows forever. + pub async fn purge_expired(db: &Database) -> Result { + let now = Timestamp::now().as_millis(); + let mut result = db + .query("DELETE session WHERE expires_at < $now RETURN BEFORE") + .bind(("now", now)) + .await? + .check()?; + Ok(result.take::>(0)?.len() as u64) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn token_is_64_hex_and_unique() { + let token = SessionToken::generate().unwrap(); + assert_eq!(token.as_str().len(), 64); + assert!(token.as_str().chars().all(|c| c.is_ascii_hexdigit())); + assert_ne!(SessionToken::generate().unwrap().as_str(), token.as_str()); + } + + #[tokio::test] + async fn purge_expired_removes_only_past_sessions() { + let db = crate::database::init_mem().await.unwrap(); + db.query( + "CREATE session SET user = type::record('user', 'u'), token = 'past', expires_at = 1; + CREATE session SET user = type::record('user', 'u'), token = 'future', expires_at = 99999999999999;", + ) + .await + .unwrap() + .check() + .unwrap(); + + assert_eq!(Session::purge_expired(&db).await.unwrap(), 1); + assert!(Session::find_by_token("past", &db).await.unwrap().is_none()); + assert!( + Session::find_by_token("future", &db) + .await + .unwrap() + .is_some() + ); + } +} diff --git a/src/domain/timestamp.rs b/src/domain/timestamp.rs new file mode 100644 index 0000000..fe14d1d --- /dev/null +++ b/src/domain/timestamp.rs @@ -0,0 +1,51 @@ +use surrealdb::types::SurrealValue; + +/// A unix-millisecond instant. Stored as an `int`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, SurrealValue)] +pub struct Timestamp(i64); + +impl Timestamp { + pub fn now() -> Self { + Self(chrono::Utc::now().timestamp_millis()) + } + + pub fn in_days(days: i64) -> Self { + Self((chrono::Utc::now() + chrono::Duration::days(days)).timestamp_millis()) + } + + pub fn from_millis(millis: i64) -> Self { + Self(millis) + } + + pub fn as_millis(&self) -> i64 { + self.0 + } + + pub fn is_past(&self) -> bool { + self.0 < Self::now().0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn millis_roundtrip() { + assert_eq!( + Timestamp::from_millis(1_700_000_000_000).as_millis(), + 1_700_000_000_000 + ); + } + + #[tokio::test] + async fn ordering() { + assert!(Timestamp::from_millis(1) < Timestamp::from_millis(2)); + } + + #[tokio::test] + async fn expiry_direction() { + assert!(!Timestamp::in_days(1).is_past()); + assert!(Timestamp::in_days(-1).is_past()); + } +} diff --git a/src/domain/user.rs b/src/domain/user.rs new file mode 100644 index 0000000..1073306 --- /dev/null +++ b/src/domain/user.rs @@ -0,0 +1,266 @@ +use std::sync::OnceLock; + +use argon2::password_hash::SaltString; +use argon2::{Argon2, PasswordHasher, PasswordVerifier}; +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::database::{Database, USER_TABLE}; +use crate::domain::role::Role; +use crate::error::{AppError, ValidationError}; +use crate::validate::{validate_password, validate_username}; + +/// Typed user record id (`user:`). +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct UserId(RecordId); + +impl UserId { + pub fn generate() -> Self { + Self(RecordId::new(USER_TABLE, Ulid::new().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(USER_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// A validated username. Construction guarantees the restrictions hold and +/// canonicalizes the value: the stored string is trimmed, since the unique +/// index and the login lookup key on it — `"ali "` must be `"ali"`, not a +/// second, visually identical account. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct Username(String); + +impl Username { + pub fn try_new(value: &str) -> Result { + validate_username(value)?; + Ok(Self(value.trim().to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// A validated plaintext password. Never stored — only hashed or verified. +pub struct Password(String); + +impl Password { + pub fn try_new(value: &str) -> Result { + validate_password(value)?; + Ok(Self(value.to_string())) + } + + pub fn hash(&self) -> Result { + let mut salt_bytes = [0u8; 16]; + getrandom::fill(&mut salt_bytes).map_err(|e| AppError::Internal(format!("rng: {e}")))?; + let salt = SaltString::encode_b64(&salt_bytes) + .map_err(|e| AppError::Internal(format!("salt: {e}")))?; + let hash = Argon2::default() + .hash_password(self.0.as_bytes(), &salt)? + .to_string(); + Ok(PasswordHash(hash)) + } +} + +/// An argon2 PHC hash, safe to persist. +#[derive(Debug, Clone, SurrealValue)] +pub struct PasswordHash(String); + +/// A fixed password whose hash is the login decoy (see [`PasswordHash::verify_decoy`]). +/// Not a secret — it never matches a real account. +const DECOY_PASSWORD: &str = "decoy-password-not-a-secret"; + +/// A process-wide decoy hash, computed once on first use. Verifying against it +/// performs the full argon2 work while matching no real account. +fn decoy_hash() -> &'static PasswordHash { + static DECOY: OnceLock = OnceLock::new(); + DECOY.get_or_init(|| { + Password::try_new(DECOY_PASSWORD) + .expect("decoy password satisfies the password rules") + .hash() + .expect("decoy password hashes") + }) +} + +impl PasswordHash { + pub fn as_str(&self) -> &str { + &self.0 + } + + pub fn verify(&self, password: &Password) -> bool { + match argon2::password_hash::PasswordHash::new(&self.0) { + Ok(parsed) => Argon2::default() + .verify_password(password.0.as_bytes(), &parsed) + .is_ok(), + Err(_) => false, + } + } + + /// Run a throwaway verification against the decoy hash. Login calls this when + /// the username is unknown, so a missing user costs the same argon2 time as a + /// real (wrong-password) check — otherwise the faster reply would let an + /// attacker enumerate valid usernames by timing. + pub fn verify_decoy(password: &Password) { + let _ = decoy_hash().verify(password); + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct User { + id: UserId, + username: Username, + password_hash: PasswordHash, + role: Role, +} + +impl User { + pub fn get_id(&self) -> &UserId { + &self.id + } + + pub fn get_username(&self) -> &Username { + &self.username + } + + pub fn get_password_hash(&self) -> &PasswordHash { + &self.password_hash + } + + pub fn get_role(&self) -> Role { + self.role + } + + /// Register a new account. New users always start as [`Role::Student`]; + /// elevation is a separate, admin-only action (see [`User::set_role`]). + pub async fn create( + username: Username, + password_hash: PasswordHash, + db: &Database, + ) -> Result { + if Self::find_by_username(username.as_str(), db) + .await? + .is_some() + { + return Err(AppError::Conflict("username already taken")); + } + let user = User { + id: UserId::generate(), + username, + password_hash, + role: Role::Student, + }; + let created: Result, surrealdb::Error> = + db.create(user.id.record()).content(user.clone()).await; + match created { + Ok(Some(created)) => Ok(created), + Ok(None) => Err(AppError::Internal("failed to create user".into())), + // The availability pre-check above is not atomic with the insert: + // two concurrent registrations can both pass it, and the loser then + // trips the unique username index. That loss is the same condition + // as the sequential duplicate, so report the same 409 — not a 500. + Err(err) => { + if Self::find_by_username(user.username.as_str(), db) + .await? + .is_some() + { + Err(AppError::Conflict("username already taken")) + } else { + Err(err.into()) + } + } + } + } + + pub async fn read(id: &UserId, db: &Database) -> Result, AppError> { + Ok(db.select(id.record()).await?) + } + + pub async fn list_all(db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM user ORDER BY id DESC") + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// Overwrite this user's role. The caller is responsible for authorizing it. + pub async fn set_role(mut self, role: Role, db: &Database) -> Result { + self.role = role; + let updated: Option = db.update(self.id.record()).content(self).await?; + updated.ok_or(AppError::NotFound) + } + + pub async fn find_by_username(username: &str, db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM user WHERE username = $username LIMIT 1") + .bind(("username", username.to_string())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn username_newtype_validates() { + assert_eq!(Username::try_new("ali").unwrap().as_str(), "ali"); + assert!(Username::try_new("").is_err()); + assert!(Username::try_new("ab").is_err()); + } + + #[tokio::test] + async fn username_is_stored_trimmed() { + // The unique index and the login lookup key on the *stored* string, so + // padding must not survive construction — otherwise "ali " and "ali" + // become two distinct, visually identical accounts. + assert_eq!(Username::try_new(" ali ").unwrap().as_str(), "ali"); + } + + #[tokio::test] + async fn short_password_rejected() { + assert!(Password::try_new("123").is_err()); + assert!(Password::try_new("secret1").is_ok()); + } + + #[tokio::test] + async fn password_hash_roundtrips() { + let hash = Password::try_new("secret1").unwrap().hash().unwrap(); + assert!(hash.verify(&Password::try_new("secret1").unwrap())); + assert!(!hash.verify(&Password::try_new("wrongpw").unwrap())); + } + + #[tokio::test] + async fn decoy_hash_is_valid_and_nonmatching() { + // The decoy must be a real, parseable argon2 hash. If it ever became + // malformed, verify() would early-return without doing the hashing work + // and the login timing-equalization would silently disappear. + assert!( + decoy_hash().verify(&Password::try_new(DECOY_PASSWORD).unwrap()), + "decoy hash must verify its own password" + ); + assert!(!decoy_hash().verify(&Password::try_new("some-other-pw").unwrap())); + } + + #[tokio::test] + async fn user_id_key_roundtrips() { + let id = UserId::generate(); + let key = id.key().to_string(); + assert!(!key.is_empty()); + assert_eq!(UserId::from_key(&key).key(), key); + } +}