From baceaf5caad056e25727285708ac9714aa3979d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 12 Jul 2026 02:19:51 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(profile):=20optional=20persona?= =?UTF-8?q?l=20info=20on=20user=20accounts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every account (any role) gains name, surname, email, phone, and birth date as optional fields backed by validated newtypes: PersonName keeps unicode and trims, Email and Phone get pragmatic shape validators, and BirthDate parses real calendar dates in YYYY-MM-DD form and refuses the future. Existing rows read back as None via option columns. Endpoints: PATCH /users/me lets any authenticated user edit their own info; GET /users/{id} and PATCH /users/{id}/profile give admins the school-office path for maintaining records. Patch semantics per field: omitted keeps the current value, an empty string clears it, anything else is validated and set. UserResponse now carries the new fields. --- src/constant.rs | 9 +++ src/database.rs | 5 ++ src/domain/mod.rs | 1 + src/domain/profile.rs | 134 ++++++++++++++++++++++++++++++++++++++ src/domain/user.rs | 55 ++++++++++++++++ src/lib.rs | 2 +- src/validate.rs | 98 +++++++++++++++++++++++++++- src/web/dto.rs | 20 +++++- src/web/users.rs | 145 +++++++++++++++++++++++++++++++++++++++++- 9 files changed, 462 insertions(+), 7 deletions(-) create mode 100644 src/domain/profile.rs diff --git a/src/constant.rs b/src/constant.rs index 1f6a3e6..df8010b 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -6,6 +6,15 @@ pub const MAX_USERNAME_LEN: usize = 32; pub const MIN_PASSWORD_LEN: usize = 6; pub const MAX_PASSWORD_LEN: usize = 128; +pub const MAX_NAME_LEN: usize = 100; + +/// RFC 5321's practical upper bound for a full address. +pub const MAX_EMAIL_LEN: usize = 254; + +/// Digit-count bounds for a phone number (E.164 allows at most 15). +pub const MIN_PHONE_DIGITS: usize = 7; +pub const MAX_PHONE_DIGITS: usize = 15; + pub const MAX_NOTE_TITLE_LEN: usize = 200; pub const MAX_NOTE_CONTENT_LEN: usize = 10_000; diff --git a/src/database.rs b/src/database.rs index fe15716..ace23f6 100644 --- a/src/database.rs +++ b/src/database.rs @@ -23,6 +23,11 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS username ON user TYPE string; DEFINE FIELD IF NOT EXISTS password_hash ON user TYPE string; DEFINE FIELD IF NOT EXISTS role ON user TYPE string DEFAULT 'student'; + DEFINE FIELD IF NOT EXISTS name ON user TYPE option; + DEFINE FIELD IF NOT EXISTS surname ON user TYPE option; + DEFINE FIELD IF NOT EXISTS email ON user TYPE option; + DEFINE FIELD IF NOT EXISTS phone ON user TYPE option; + DEFINE FIELD IF NOT EXISTS birth_date ON user TYPE option; DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; UPDATE user SET role = 'student' WHERE role = NONE; diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 8a5235e..23e00ca 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -7,6 +7,7 @@ pub mod event; pub mod exam; pub mod exam_result; pub mod note; +pub mod profile; pub mod role; pub mod session; pub mod timestamp; diff --git a/src/domain/profile.rs b/src/domain/profile.rs new file mode 100644 index 0000000..08950dd --- /dev/null +++ b/src/domain/profile.rs @@ -0,0 +1,134 @@ +//! Personal-info newtypes shared by every account role — student, teacher, +//! manager, and admin records all carry the same optional contact fields. + +use surrealdb::types::SurrealValue; + +use crate::constant::MAX_NAME_LEN; +use crate::error::ValidationError; +use crate::validate::{validate_email, validate_phone, validate_required}; + +/// A person's given or family name. One type serves both fields — the `field` +/// tag only steers the error message ("name …" vs "surname …"). Stored trimmed; +/// unicode is welcome (names are not ASCII). +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct PersonName(String); + +impl PersonName { + pub fn try_new(field: &'static str, value: &str) -> Result { + validate_required(field, value, MAX_NAME_LEN)?; + Ok(Self(value.trim().to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// A plausibly-shaped email address (see [`validate_email`]). Stored trimmed. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct Email(String); + +impl Email { + pub fn try_new(value: &str) -> Result { + validate_email(value)?; + Ok(Self(value.trim().to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// A phone number: optional leading `+`, 7–15 digits, cosmetic separators +/// allowed (see [`validate_phone`]). Stored trimmed, separators kept as given. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct Phone(String); + +impl Phone { + pub fn try_new(value: &str) -> Result { + validate_phone(value)?; + Ok(Self(value.trim().to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// A birth date, canonicalized to `YYYY-MM-DD`. Construction parses the input +/// as a real calendar date (no 2026-02-30) and refuses future dates. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct BirthDate(String); + +impl BirthDate { + pub fn try_new(value: &str) -> Result { + let date = chrono::NaiveDate::parse_from_str(value.trim(), "%Y-%m-%d").map_err(|_| { + ValidationError::Invalid { + field: "birth_date", + reason: "must be a calendar date in YYYY-MM-DD form", + } + })?; + if date > chrono::Utc::now().date_naive() { + return Err(ValidationError::Invalid { + field: "birth_date", + reason: "must not be in the future", + }); + } + Ok(Self(date.format("%Y-%m-%d").to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn person_name_trims_and_validates() { + assert_eq!( + PersonName::try_new("name", " Ada ").unwrap().as_str(), + "Ada" + ); + // Unicode names must pass — this is not the ASCII-only username rule. + assert_eq!( + PersonName::try_new("surname", "Gümüş").unwrap().as_str(), + "Gümüş" + ); + assert!(PersonName::try_new("name", " ").is_err()); + assert!(PersonName::try_new("name", &"x".repeat(101)).is_err()); + } + + #[tokio::test] + async fn name_errors_carry_the_field_tag() { + // One newtype serves two fields; the message must still say which one. + let err = PersonName::try_new("surname", "").unwrap_err(); + assert!(err.to_string().contains("surname")); + } + + #[tokio::test] + async fn email_and_phone_store_trimmed() { + assert_eq!( + Email::try_new(" ada@example.com ").unwrap().as_str(), + "ada@example.com" + ); + assert_eq!( + Phone::try_new(" +90 555 123 45 67 ").unwrap().as_str(), + "+90 555 123 45 67" + ); + } + + #[tokio::test] + async fn birth_date_canonicalizes() { + assert_eq!( + BirthDate::try_new("1990-1-2").unwrap().as_str(), + "1990-01-02" + ); + assert!(BirthDate::try_new("1990-02-30").is_err()); // not a real date + assert!(BirthDate::try_new("02/01/1990").is_err()); // wrong format + assert!(BirthDate::try_new("9999-01-01").is_err()); // future + assert!(BirthDate::try_new("").is_err()); + } +} diff --git a/src/domain/user.rs b/src/domain/user.rs index 1073306..055e90c 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -6,6 +6,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; use crate::database::{Database, USER_TABLE}; +use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; use crate::domain::role::Role; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_password, validate_username}; @@ -123,6 +124,14 @@ pub struct User { username: Username, password_hash: PasswordHash, role: Role, + // Personal info, identical for every role. All optional: accounts are + // created from bare credentials and filled in later, and rows from before + // these fields existed simply read back as `None`. + name: Option, + surname: Option, + email: Option, + phone: Option, + birth_date: Option, } impl User { @@ -142,6 +151,26 @@ impl User { self.role } + pub fn get_name(&self) -> Option<&PersonName> { + self.name.as_ref() + } + + pub fn get_surname(&self) -> Option<&PersonName> { + self.surname.as_ref() + } + + pub fn get_email(&self) -> Option<&Email> { + self.email.as_ref() + } + + pub fn get_phone(&self) -> Option<&Phone> { + self.phone.as_ref() + } + + pub fn get_birth_date(&self) -> Option<&BirthDate> { + self.birth_date.as_ref() + } + /// 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( @@ -160,6 +189,11 @@ impl User { username, password_hash, role: Role::Student, + name: None, + surname: None, + email: None, + phone: None, + birth_date: None, }; let created: Result, surrealdb::Error> = db.create(user.id.record()).content(user.clone()).await; @@ -202,6 +236,27 @@ impl User { updated.ok_or(AppError::NotFound) } + /// Overwrite the personal-info fields wholesale. Each argument is the final + /// value (`None` clears); merging "keep what wasn't sent" against the + /// current row is the HTTP layer's job. The caller authorizes. + pub async fn set_profile( + mut self, + name: Option, + surname: Option, + email: Option, + phone: Option, + birth_date: Option, + db: &Database, + ) -> Result { + self.name = name; + self.surname = surname; + self.email = email; + self.phone = phone; + self.birth_date = birth_date; + 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") diff --git a/src/lib.rs b/src/lib.rs index 685e510..e38d5eb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -38,7 +38,7 @@ use crate::state::AppState; tags( (name = "meta", description = "Liveness and service metadata"), (name = "auth", description = "Registration, login, session lifecycle"), - (name = "users", description = "User listing and role administration (admin only)"), + (name = "users", description = "User info: self-service profile, plus listing, lookup, and role/profile administration (admin only)"), (name = "notes", description = "Per-user notes CRUD"), (name = "events", description = "Events and attendance"), (name = "exams", description = "Exams (homework/quiz) and student results"), diff --git a/src/validate.rs b/src/validate.rs index fb82985..f88022e 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -2,8 +2,8 @@ //! the value, so an existing newtype is always valid (parse, don't validate). use crate::constant::{ - ATTENDANCE_STATUSES, EXAM_KINDS, MAX_MARK, MAX_PASSWORD_LEN, MAX_USERNAME_LEN, MIN_MARK, - MIN_PASSWORD_LEN, MIN_USERNAME_LEN, + ATTENDANCE_STATUSES, EXAM_KINDS, MAX_EMAIL_LEN, MAX_MARK, MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, + MAX_USERNAME_LEN, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_USERNAME_LEN, }; use crate::error::ValidationError; @@ -91,6 +91,71 @@ pub fn validate_optional( Ok(()) } +/// Pragmatic email shape check: one `@` with non-empty sides, a dot inside the +/// domain, ASCII, no whitespace. Deliverability is not provable here — this only +/// rejects values that cannot be an address. +pub fn validate_email(value: &str) -> Result<(), ValidationError> { + let value = value.trim(); + if value.is_empty() { + return Err(ValidationError::Empty("email")); + } + if !value.is_ascii() { + return Err(ValidationError::NotAscii("email")); + } + if value.chars().count() > MAX_EMAIL_LEN { + return Err(ValidationError::TooLong { + field: "email", + max: MAX_EMAIL_LEN, + got: value.chars().count(), + }); + } + let invalid = ValidationError::Invalid { + field: "email", + reason: "must look like name@example.com", + }; + if value.contains(char::is_whitespace) || value.matches('@').count() != 1 { + return Err(invalid); + } + match value.split_once('@') { + Some((local, domain)) + if !local.is_empty() + && domain.contains('.') + && !domain.starts_with('.') + && !domain.ends_with('.') => + { + Ok(()) + } + _ => Err(invalid), + } +} + +/// Phone numbers: an optional leading `+`, then digits with cosmetic spaces, +/// dashes, or parentheses; 7–15 digits total (E.164's ceiling). +pub fn validate_phone(value: &str) -> Result<(), ValidationError> { + let value = value.trim(); + if value.is_empty() { + return Err(ValidationError::Empty("phone")); + } + let rest = value.strip_prefix('+').unwrap_or(value); + if rest + .chars() + .any(|c| !c.is_ascii_digit() && !matches!(c, ' ' | '-' | '(' | ')')) + { + return Err(ValidationError::Invalid { + field: "phone", + reason: "may contain digits, spaces, dashes, parentheses, and a leading +", + }); + } + let digits = rest.chars().filter(char::is_ascii_digit).count(); + if !(MIN_PHONE_DIGITS..=MAX_PHONE_DIGITS).contains(&digits) { + return Err(ValidationError::Invalid { + field: "phone", + reason: "must contain 7 to 15 digits", + }); + } + Ok(()) +} + pub fn validate_status(value: &str) -> Result<(), ValidationError> { if ATTENDANCE_STATUSES.contains(&value) { Ok(()) @@ -170,6 +235,35 @@ mod tests { assert!(validate_optional("content", "toolong", 3).is_err()); } + #[tokio::test] + async fn email_rules() { + assert!(validate_email("ada@example.com").is_ok()); + assert!(validate_email(" ada@example.com ").is_ok()); // trimmed before checking + assert!(validate_email("").is_err()); + assert!(validate_email("ada").is_err()); // no @ + assert!(validate_email("@example.com").is_err()); // empty local part + assert!(validate_email("ada@").is_err()); // empty domain + assert!(validate_email("ada@example").is_err()); // no dot in domain + assert!(validate_email("ada@.com").is_err()); // dot at domain edge + assert!(validate_email("ada@example.com.").is_err()); + assert!(validate_email("a da@example.com").is_err()); // whitespace inside + assert!(validate_email("ada@ex@ample.com").is_err()); // two @ + assert!(validate_email("adä@example.com").is_err()); // non-ascii + assert!(validate_email(&format!("{}@example.com", "x".repeat(250))).is_err()); + } + + #[tokio::test] + async fn phone_rules() { + assert!(validate_phone("+90 555 123 45 67").is_ok()); + assert!(validate_phone("05551234567").is_ok()); + assert!(validate_phone("(555) 123-4567").is_ok()); + assert!(validate_phone("").is_err()); + assert!(validate_phone("123456").is_err()); // 6 digits, too few + assert!(validate_phone("1234567890123456").is_err()); // 16 digits, too many + assert!(validate_phone("call-me-maybe").is_err()); // letters + assert!(validate_phone("55+5123456").is_err()); // + only allowed in front + } + #[tokio::test] async fn status_rules() { for status in ["present", "absent", "late", "excused"] { diff --git a/src/web/dto.rs b/src/web/dto.rs index f8e9d77..70181ea 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -30,8 +30,9 @@ impl From for Role { } } -/// Public shape of a user: id, username, role. Never carries the password hash. -/// Shared by `auth` (register/login/me) and `users` (admin listing/role changes). +/// Public shape of a user: id, username, role, and the optional personal info +/// (`null` until filled in). Never carries the password hash. Shared by `auth` +/// (register/login/me) and `users` (listing, role and profile changes). #[derive(Serialize, ToSchema)] pub struct UserResponse { #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] @@ -39,6 +40,16 @@ pub struct UserResponse { #[schema(example = "ada")] pub username: String, pub role: Role, + #[schema(example = "Ada")] + pub name: Option, + #[schema(example = "Lovelace")] + pub surname: Option, + #[schema(example = "ada@example.com")] + pub email: Option, + #[schema(example = "+90 555 123 45 67")] + pub phone: Option, + #[schema(example = "1990-01-02")] + pub birth_date: Option, } impl UserResponse { @@ -47,6 +58,11 @@ impl UserResponse { id: user.get_id().key().to_string(), username: user.get_username().as_str().to_string(), role: user.get_role().into(), + name: user.get_name().map(|v| v.as_str().to_string()), + surname: user.get_surname().map(|v| v.as_str().to_string()), + email: user.get_email().map(|v| v.as_str().to_string()), + phone: user.get_phone().map(|v| v.as_str().to_string()), + birth_date: user.get_birth_date().map(|v| v.as_str().to_string()), } } } diff --git a/src/web/users.rs b/src/web/users.rs index 7f532d5..1538ad4 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -5,18 +5,23 @@ use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; +use crate::database::Database; +use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; -use crate::error::{AppError, ErrorResponse}; +use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; use super::dto::Role as RoleSchema; -use super::{RequireAdmin, UserResponse}; +use super::{CurrentUser, RequireAdmin, UserResponse}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() .routes(routes!(list_users)) + .routes(routes!(update_my_profile)) + .routes(routes!(get_user)) .routes(routes!(set_role)) + .routes(routes!(update_user_profile)) } #[derive(Deserialize, ToSchema)] @@ -27,6 +32,64 @@ struct SetRole { role: String, } +/// Partial personal-info update. Per field: omitted (or `null`) keeps the +/// current value, an empty string clears it, anything else is validated and set. +#[derive(Deserialize, ToSchema)] +struct UpdateProfile { + #[schema(example = "Ada")] + name: Option, + #[schema(example = "Lovelace")] + surname: Option, + #[schema(example = "ada@example.com")] + email: Option, + #[schema(example = "+90 555 123 45 67")] + phone: Option, + /// Birth date in `YYYY-MM-DD` form. + #[schema(example = "1990-01-02")] + birth_date: Option, +} + +/// Resolve one patched field: absent keeps the current value, `""` clears it, +/// anything else must parse into the domain newtype. +fn merge_field( + current: Option<&T>, + patch: Option<&str>, + parse: impl Fn(&str) -> Result, +) -> Result, ValidationError> { + match patch { + None => Ok(current.cloned()), + Some("") => Ok(None), + Some(value) => Ok(Some(parse(value)?)), + } +} + +/// Merge `req` over `user`'s current info and persist. Shared by the +/// self-service and admin profile endpoints — they differ only in whose row +/// they load and who may call them. +async fn apply_profile( + user: User, + req: &UpdateProfile, + db: &Database, +) -> Result { + let name = merge_field(user.get_name(), req.name.as_deref(), |v| { + PersonName::try_new("name", v) + })?; + let surname = merge_field(user.get_surname(), req.surname.as_deref(), |v| { + PersonName::try_new("surname", v) + })?; + let email = merge_field(user.get_email(), req.email.as_deref(), Email::try_new)?; + let phone = merge_field(user.get_phone(), req.phone.as_deref(), Phone::try_new)?; + let birth_date = merge_field( + user.get_birth_date(), + req.birth_date.as_deref(), + BirthDate::try_new, + )?; + let updated = user + .set_profile(name, surname, email, phone, birth_date, db) + .await?; + Ok(UserResponse::new(&updated)) +} + /// List every user with their role. Admin only. #[utoipa::path( get, @@ -47,6 +110,84 @@ async fn list_users( Ok(Json(users.iter().map(UserResponse::new).collect())) } +/// Update the caller's own personal info: name, surname, email, phone, birth +/// date. Any authenticated role. Omitted fields stay as they are; an empty +/// string clears a field. +#[utoipa::path( + patch, + path = "/me", + tag = "users", + security(("session_cookie" = [])), + request_body = UpdateProfile, + responses( + (status = 200, description = "Updated user", body = UserResponse), + (status = 400, description = "Invalid field", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn update_my_profile( + State(st): State, + CurrentUser(user): CurrentUser, + Json(req): Json, +) -> Result, AppError> { + Ok(Json(apply_profile(user, &req, &st.db).await?)) +} + +/// Fetch one user with their role and personal info. Admin only. +#[utoipa::path( + get, + path = "/{id}", + tag = "users", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "User id")), + responses( + (status = 200, description = "The user", body = UserResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires admin role", body = ErrorResponse), + (status = 404, description = "User not found", body = ErrorResponse), + ), +)] +async fn get_user( + State(st): State, + _admin: RequireAdmin, + Path(id): Path, +) -> Result, AppError> { + let user = User::read(&UserId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + Ok(Json(UserResponse::new(&user))) +} + +/// Update any user's personal info. Admin only — the school-office path for +/// maintaining records on behalf of students and staff. Same field semantics +/// as `PATCH /users/me`. +#[utoipa::path( + patch, + path = "/{id}/profile", + tag = "users", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "User id")), + request_body = UpdateProfile, + responses( + (status = 200, description = "Updated user", body = UserResponse), + (status = 400, description = "Invalid field", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires admin role", body = ErrorResponse), + (status = 404, description = "User not found", body = ErrorResponse), + ), +)] +async fn update_user_profile( + State(st): State, + _admin: RequireAdmin, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let user = User::read(&UserId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + Ok(Json(apply_profile(user, &req, &st.db).await?)) +} + /// Set a user's role. Admin only. An admin cannot change their own role — that /// guard keeps a sole admin from accidentally locking everyone out of role /// management (recover such a lockout with the SurrealQL in the README).