Optional personal info on user accounts
Browse files at this commitbaceaf5caad056e25727285708ac9714aa3979d7Parent: 3397086- feat
- optional personal info on user accounts
9 changed files +462 -7
- src/constant.rs +9 -0
- src/database.rs +5 -0
- src/domain/mod.rs +1 -0
- src/domain/profile.rs +134 -0
- src/domain/user.rs +55 -0
- src/lib.rs +1 -1
- src/validate.rs +96 -2
- src/web/dto.rs +18 -2
- src/web/users.rs +143 -2
src/constant.rsmodified+9 -0
| @@ -6,6 +6,15 @@ pub const MAX_USERNAME_LEN: usize = 32; | ||
| 6 | 6 | pub const MIN_PASSWORD_LEN: usize = 6; |
| 7 | 7 | pub const MAX_PASSWORD_LEN: usize = 128; |
| 8 | 8 | |
| 9 | +pub const MAX_NAME_LEN: usize = 100; | |
| 10 | + | |
| 11 | +/// RFC 5321's practical upper bound for a full address. | |
| 12 | +pub const MAX_EMAIL_LEN: usize = 254; | |
| 13 | + | |
| 14 | +/// Digit-count bounds for a phone number (E.164 allows at most 15). | |
| 15 | +pub const MIN_PHONE_DIGITS: usize = 7; | |
| 16 | +pub const MAX_PHONE_DIGITS: usize = 15; | |
| 17 | + | |
| 9 | 18 | pub const MAX_NOTE_TITLE_LEN: usize = 200; |
| 10 | 19 | pub const MAX_NOTE_CONTENT_LEN: usize = 10_000; |
| 11 | 20 |
src/database.rsmodified+5 -0
| @@ -23,6 +23,11 @@ const MIGRATION: &str = " | ||
| 23 | 23 | DEFINE FIELD IF NOT EXISTS username ON user TYPE string; |
| 24 | 24 | DEFINE FIELD IF NOT EXISTS password_hash ON user TYPE string; |
| 25 | 25 | DEFINE FIELD IF NOT EXISTS role ON user TYPE string DEFAULT 'student'; |
| 26 | + DEFINE FIELD IF NOT EXISTS name ON user TYPE option<string>; | |
| 27 | + DEFINE FIELD IF NOT EXISTS surname ON user TYPE option<string>; | |
| 28 | + DEFINE FIELD IF NOT EXISTS email ON user TYPE option<string>; | |
| 29 | + DEFINE FIELD IF NOT EXISTS phone ON user TYPE option<string>; | |
| 30 | + DEFINE FIELD IF NOT EXISTS birth_date ON user TYPE option<string>; | |
| 26 | 31 | DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; |
| 27 | 32 | UPDATE user SET role = 'student' WHERE role = NONE; |
| 28 | 33 |
src/domain/mod.rsmodified+1 -0
| @@ -7,6 +7,7 @@ pub mod event; | ||
| 7 | 7 | pub mod exam; |
| 8 | 8 | pub mod exam_result; |
| 9 | 9 | pub mod note; |
| 10 | +pub mod profile; | |
| 10 | 11 | pub mod role; |
| 11 | 12 | pub mod session; |
| 12 | 13 | pub mod timestamp; |
src/domain/profile.rsadded+134 -0
| @@ -0,0 +1,134 @@ | ||
| 1 | +//! Personal-info newtypes shared by every account role — student, teacher, | |
| 2 | +//! manager, and admin records all carry the same optional contact fields. | |
| 3 | + | |
| 4 | +use surrealdb::types::SurrealValue; | |
| 5 | + | |
| 6 | +use crate::constant::MAX_NAME_LEN; | |
| 7 | +use crate::error::ValidationError; | |
| 8 | +use crate::validate::{validate_email, validate_phone, validate_required}; | |
| 9 | + | |
| 10 | +/// A person's given or family name. One type serves both fields — the `field` | |
| 11 | +/// tag only steers the error message ("name …" vs "surname …"). Stored trimmed; | |
| 12 | +/// unicode is welcome (names are not ASCII). | |
| 13 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | |
| 14 | +pub struct PersonName(String); | |
| 15 | + | |
| 16 | +impl PersonName { | |
| 17 | + pub fn try_new(field: &'static str, value: &str) -> Result<Self, ValidationError> { | |
| 18 | + validate_required(field, value, MAX_NAME_LEN)?; | |
| 19 | + Ok(Self(value.trim().to_string())) | |
| 20 | + } | |
| 21 | + | |
| 22 | + pub fn as_str(&self) -> &str { | |
| 23 | + &self.0 | |
| 24 | + } | |
| 25 | +} | |
| 26 | + | |
| 27 | +/// A plausibly-shaped email address (see [`validate_email`]). Stored trimmed. | |
| 28 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | |
| 29 | +pub struct Email(String); | |
| 30 | + | |
| 31 | +impl Email { | |
| 32 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | |
| 33 | + validate_email(value)?; | |
| 34 | + Ok(Self(value.trim().to_string())) | |
| 35 | + } | |
| 36 | + | |
| 37 | + pub fn as_str(&self) -> &str { | |
| 38 | + &self.0 | |
| 39 | + } | |
| 40 | +} | |
| 41 | + | |
| 42 | +/// A phone number: optional leading `+`, 7–15 digits, cosmetic separators | |
| 43 | +/// allowed (see [`validate_phone`]). Stored trimmed, separators kept as given. | |
| 44 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | |
| 45 | +pub struct Phone(String); | |
| 46 | + | |
| 47 | +impl Phone { | |
| 48 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | |
| 49 | + validate_phone(value)?; | |
| 50 | + Ok(Self(value.trim().to_string())) | |
| 51 | + } | |
| 52 | + | |
| 53 | + pub fn as_str(&self) -> &str { | |
| 54 | + &self.0 | |
| 55 | + } | |
| 56 | +} | |
| 57 | + | |
| 58 | +/// A birth date, canonicalized to `YYYY-MM-DD`. Construction parses the input | |
| 59 | +/// as a real calendar date (no 2026-02-30) and refuses future dates. | |
| 60 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | |
| 61 | +pub struct BirthDate(String); | |
| 62 | + | |
| 63 | +impl BirthDate { | |
| 64 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | |
| 65 | + let date = chrono::NaiveDate::parse_from_str(value.trim(), "%Y-%m-%d").map_err(|_| { | |
| 66 | + ValidationError::Invalid { | |
| 67 | + field: "birth_date", | |
| 68 | + reason: "must be a calendar date in YYYY-MM-DD form", | |
| 69 | + } | |
| 70 | + })?; | |
| 71 | + if date > chrono::Utc::now().date_naive() { | |
| 72 | + return Err(ValidationError::Invalid { | |
| 73 | + field: "birth_date", | |
| 74 | + reason: "must not be in the future", | |
| 75 | + }); | |
| 76 | + } | |
| 77 | + Ok(Self(date.format("%Y-%m-%d").to_string())) | |
| 78 | + } | |
| 79 | + | |
| 80 | + pub fn as_str(&self) -> &str { | |
| 81 | + &self.0 | |
| 82 | + } | |
| 83 | +} | |
| 84 | + | |
| 85 | +#[cfg(test)] | |
| 86 | +mod tests { | |
| 87 | + use super::*; | |
| 88 | + | |
| 89 | + #[tokio::test] | |
| 90 | + async fn person_name_trims_and_validates() { | |
| 91 | + assert_eq!( | |
| 92 | + PersonName::try_new("name", " Ada ").unwrap().as_str(), | |
| 93 | + "Ada" | |
| 94 | + ); | |
| 95 | + // Unicode names must pass — this is not the ASCII-only username rule. | |
| 96 | + assert_eq!( | |
| 97 | + PersonName::try_new("surname", "Gümüş").unwrap().as_str(), | |
| 98 | + "Gümüş" | |
| 99 | + ); | |
| 100 | + assert!(PersonName::try_new("name", " ").is_err()); | |
| 101 | + assert!(PersonName::try_new("name", &"x".repeat(101)).is_err()); | |
| 102 | + } | |
| 103 | + | |
| 104 | + #[tokio::test] | |
| 105 | + async fn name_errors_carry_the_field_tag() { | |
| 106 | + // One newtype serves two fields; the message must still say which one. | |
| 107 | + let err = PersonName::try_new("surname", "").unwrap_err(); | |
| 108 | + assert!(err.to_string().contains("surname")); | |
| 109 | + } | |
| 110 | + | |
| 111 | + #[tokio::test] | |
| 112 | + async fn email_and_phone_store_trimmed() { | |
| 113 | + assert_eq!( | |
| 114 | + Email::try_new(" ada@example.com ").unwrap().as_str(), | |
| 115 | + "ada@example.com" | |
| 116 | + ); | |
| 117 | + assert_eq!( | |
| 118 | + Phone::try_new(" +90 555 123 45 67 ").unwrap().as_str(), | |
| 119 | + "+90 555 123 45 67" | |
| 120 | + ); | |
| 121 | + } | |
| 122 | + | |
| 123 | + #[tokio::test] | |
| 124 | + async fn birth_date_canonicalizes() { | |
| 125 | + assert_eq!( | |
| 126 | + BirthDate::try_new("1990-1-2").unwrap().as_str(), | |
| 127 | + "1990-01-02" | |
| 128 | + ); | |
| 129 | + assert!(BirthDate::try_new("1990-02-30").is_err()); // not a real date | |
| 130 | + assert!(BirthDate::try_new("02/01/1990").is_err()); // wrong format | |
| 131 | + assert!(BirthDate::try_new("9999-01-01").is_err()); // future | |
| 132 | + assert!(BirthDate::try_new("").is_err()); | |
| 133 | + } | |
| 134 | +} |
src/domain/user.rsmodified+55 -0
| @@ -6,6 +6,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 6 | 6 | use ulid::Ulid; |
| 7 | 7 | |
| 8 | 8 | use crate::database::{Database, USER_TABLE}; |
| 9 | +use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; | |
| 9 | 10 | use crate::domain::role::Role; |
| 10 | 11 | use crate::error::{AppError, ValidationError}; |
| 11 | 12 | use crate::validate::{validate_password, validate_username}; |
| @@ -123,6 +124,14 @@ pub struct User { | ||
| 123 | 124 | username: Username, |
| 124 | 125 | password_hash: PasswordHash, |
| 125 | 126 | role: Role, |
| 127 | + // Personal info, identical for every role. All optional: accounts are | |
| 128 | + // created from bare credentials and filled in later, and rows from before | |
| 129 | + // these fields existed simply read back as `None`. | |
| 130 | + name: Option<PersonName>, | |
| 131 | + surname: Option<PersonName>, | |
| 132 | + email: Option<Email>, | |
| 133 | + phone: Option<Phone>, | |
| 134 | + birth_date: Option<BirthDate>, | |
| 126 | 135 | } |
| 127 | 136 | |
| 128 | 137 | impl User { |
| @@ -142,6 +151,26 @@ impl User { | ||
| 142 | 151 | self.role |
| 143 | 152 | } |
| 144 | 153 | |
| 154 | + pub fn get_name(&self) -> Option<&PersonName> { | |
| 155 | + self.name.as_ref() | |
| 156 | + } | |
| 157 | + | |
| 158 | + pub fn get_surname(&self) -> Option<&PersonName> { | |
| 159 | + self.surname.as_ref() | |
| 160 | + } | |
| 161 | + | |
| 162 | + pub fn get_email(&self) -> Option<&Email> { | |
| 163 | + self.email.as_ref() | |
| 164 | + } | |
| 165 | + | |
| 166 | + pub fn get_phone(&self) -> Option<&Phone> { | |
| 167 | + self.phone.as_ref() | |
| 168 | + } | |
| 169 | + | |
| 170 | + pub fn get_birth_date(&self) -> Option<&BirthDate> { | |
| 171 | + self.birth_date.as_ref() | |
| 172 | + } | |
| 173 | + | |
| 145 | 174 | /// Register a new account. New users always start as [`Role::Student`]; |
| 146 | 175 | /// elevation is a separate, admin-only action (see [`User::set_role`]). |
| 147 | 176 | pub async fn create( |
| @@ -160,6 +189,11 @@ impl User { | ||
| 160 | 189 | username, |
| 161 | 190 | password_hash, |
| 162 | 191 | role: Role::Student, |
| 192 | + name: None, | |
| 193 | + surname: None, | |
| 194 | + email: None, | |
| 195 | + phone: None, | |
| 196 | + birth_date: None, | |
| 163 | 197 | }; |
| 164 | 198 | let created: Result<Option<User>, surrealdb::Error> = |
| 165 | 199 | db.create(user.id.record()).content(user.clone()).await; |
| @@ -202,6 +236,27 @@ impl User { | ||
| 202 | 236 | updated.ok_or(AppError::NotFound) |
| 203 | 237 | } |
| 204 | 238 | |
| 239 | + /// Overwrite the personal-info fields wholesale. Each argument is the final | |
| 240 | + /// value (`None` clears); merging "keep what wasn't sent" against the | |
| 241 | + /// current row is the HTTP layer's job. The caller authorizes. | |
| 242 | + pub async fn set_profile( | |
| 243 | + mut self, | |
| 244 | + name: Option<PersonName>, | |
| 245 | + surname: Option<PersonName>, | |
| 246 | + email: Option<Email>, | |
| 247 | + phone: Option<Phone>, | |
| 248 | + birth_date: Option<BirthDate>, | |
| 249 | + db: &Database, | |
| 250 | + ) -> Result<User, AppError> { | |
| 251 | + self.name = name; | |
| 252 | + self.surname = surname; | |
| 253 | + self.email = email; | |
| 254 | + self.phone = phone; | |
| 255 | + self.birth_date = birth_date; | |
| 256 | + let updated: Option<User> = db.update(self.id.record()).content(self).await?; | |
| 257 | + updated.ok_or(AppError::NotFound) | |
| 258 | + } | |
| 259 | + | |
| 205 | 260 | pub async fn find_by_username(username: &str, db: &Database) -> Result<Option<User>, AppError> { |
| 206 | 261 | let mut result = db |
| 207 | 262 | .query("SELECT * FROM user WHERE username = $username LIMIT 1") |
src/lib.rsmodified+1 -1
| @@ -38,7 +38,7 @@ use crate::state::AppState; | ||
| 38 | 38 | tags( |
| 39 | 39 | (name = "meta", description = "Liveness and service metadata"), |
| 40 | 40 | (name = "auth", description = "Registration, login, session lifecycle"), |
| 41 | - (name = "users", description = "User listing and role administration (admin only)"), | |
| 41 | + (name = "users", description = "User info: self-service profile, plus listing, lookup, and role/profile administration (admin only)"), | |
| 42 | 42 | (name = "notes", description = "Per-user notes CRUD"), |
| 43 | 43 | (name = "events", description = "Events and attendance"), |
| 44 | 44 | (name = "exams", description = "Exams (homework/quiz) and student results"), |
src/validate.rsmodified+96 -2
| @@ -2,8 +2,8 @@ | ||
| 2 | 2 | //! the value, so an existing newtype is always valid (parse, don't validate). |
| 3 | 3 | |
| 4 | 4 | use crate::constant::{ |
| 5 | - ATTENDANCE_STATUSES, EXAM_KINDS, MAX_MARK, MAX_PASSWORD_LEN, MAX_USERNAME_LEN, MIN_MARK, | |
| 6 | - MIN_PASSWORD_LEN, MIN_USERNAME_LEN, | |
| 5 | + ATTENDANCE_STATUSES, EXAM_KINDS, MAX_EMAIL_LEN, MAX_MARK, MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, | |
| 6 | + MAX_USERNAME_LEN, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_USERNAME_LEN, | |
| 7 | 7 | }; |
| 8 | 8 | use crate::error::ValidationError; |
| 9 | 9 | |
| @@ -91,6 +91,71 @@ pub fn validate_optional( | ||
| 91 | 91 | Ok(()) |
| 92 | 92 | } |
| 93 | 93 | |
| 94 | +/// Pragmatic email shape check: one `@` with non-empty sides, a dot inside the | |
| 95 | +/// domain, ASCII, no whitespace. Deliverability is not provable here — this only | |
| 96 | +/// rejects values that cannot be an address. | |
| 97 | +pub fn validate_email(value: &str) -> Result<(), ValidationError> { | |
| 98 | + let value = value.trim(); | |
| 99 | + if value.is_empty() { | |
| 100 | + return Err(ValidationError::Empty("email")); | |
| 101 | + } | |
| 102 | + if !value.is_ascii() { | |
| 103 | + return Err(ValidationError::NotAscii("email")); | |
| 104 | + } | |
| 105 | + if value.chars().count() > MAX_EMAIL_LEN { | |
| 106 | + return Err(ValidationError::TooLong { | |
| 107 | + field: "email", | |
| 108 | + max: MAX_EMAIL_LEN, | |
| 109 | + got: value.chars().count(), | |
| 110 | + }); | |
| 111 | + } | |
| 112 | + let invalid = ValidationError::Invalid { | |
| 113 | + field: "email", | |
| 114 | + reason: "must look like name@example.com", | |
| 115 | + }; | |
| 116 | + if value.contains(char::is_whitespace) || value.matches('@').count() != 1 { | |
| 117 | + return Err(invalid); | |
| 118 | + } | |
| 119 | + match value.split_once('@') { | |
| 120 | + Some((local, domain)) | |
| 121 | + if !local.is_empty() | |
| 122 | + && domain.contains('.') | |
| 123 | + && !domain.starts_with('.') | |
| 124 | + && !domain.ends_with('.') => | |
| 125 | + { | |
| 126 | + Ok(()) | |
| 127 | + } | |
| 128 | + _ => Err(invalid), | |
| 129 | + } | |
| 130 | +} | |
| 131 | + | |
| 132 | +/// Phone numbers: an optional leading `+`, then digits with cosmetic spaces, | |
| 133 | +/// dashes, or parentheses; 7–15 digits total (E.164's ceiling). | |
| 134 | +pub fn validate_phone(value: &str) -> Result<(), ValidationError> { | |
| 135 | + let value = value.trim(); | |
| 136 | + if value.is_empty() { | |
| 137 | + return Err(ValidationError::Empty("phone")); | |
| 138 | + } | |
| 139 | + let rest = value.strip_prefix('+').unwrap_or(value); | |
| 140 | + if rest | |
| 141 | + .chars() | |
| 142 | + .any(|c| !c.is_ascii_digit() && !matches!(c, ' ' | '-' | '(' | ')')) | |
| 143 | + { | |
| 144 | + return Err(ValidationError::Invalid { | |
| 145 | + field: "phone", | |
| 146 | + reason: "may contain digits, spaces, dashes, parentheses, and a leading +", | |
| 147 | + }); | |
| 148 | + } | |
| 149 | + let digits = rest.chars().filter(char::is_ascii_digit).count(); | |
| 150 | + if !(MIN_PHONE_DIGITS..=MAX_PHONE_DIGITS).contains(&digits) { | |
| 151 | + return Err(ValidationError::Invalid { | |
| 152 | + field: "phone", | |
| 153 | + reason: "must contain 7 to 15 digits", | |
| 154 | + }); | |
| 155 | + } | |
| 156 | + Ok(()) | |
| 157 | +} | |
| 158 | + | |
| 94 | 159 | pub fn validate_status(value: &str) -> Result<(), ValidationError> { |
| 95 | 160 | if ATTENDANCE_STATUSES.contains(&value) { |
| 96 | 161 | Ok(()) |
| @@ -170,6 +235,35 @@ mod tests { | ||
| 170 | 235 | assert!(validate_optional("content", "toolong", 3).is_err()); |
| 171 | 236 | } |
| 172 | 237 | |
| 238 | + #[tokio::test] | |
| 239 | + async fn email_rules() { | |
| 240 | + assert!(validate_email("ada@example.com").is_ok()); | |
| 241 | + assert!(validate_email(" ada@example.com ").is_ok()); // trimmed before checking | |
| 242 | + assert!(validate_email("").is_err()); | |
| 243 | + assert!(validate_email("ada").is_err()); // no @ | |
| 244 | + assert!(validate_email("@example.com").is_err()); // empty local part | |
| 245 | + assert!(validate_email("ada@").is_err()); // empty domain | |
| 246 | + assert!(validate_email("ada@example").is_err()); // no dot in domain | |
| 247 | + assert!(validate_email("ada@.com").is_err()); // dot at domain edge | |
| 248 | + assert!(validate_email("ada@example.com.").is_err()); | |
| 249 | + assert!(validate_email("a da@example.com").is_err()); // whitespace inside | |
| 250 | + assert!(validate_email("ada@ex@ample.com").is_err()); // two @ | |
| 251 | + assert!(validate_email("adä@example.com").is_err()); // non-ascii | |
| 252 | + assert!(validate_email(&format!("{}@example.com", "x".repeat(250))).is_err()); | |
| 253 | + } | |
| 254 | + | |
| 255 | + #[tokio::test] | |
| 256 | + async fn phone_rules() { | |
| 257 | + assert!(validate_phone("+90 555 123 45 67").is_ok()); | |
| 258 | + assert!(validate_phone("05551234567").is_ok()); | |
| 259 | + assert!(validate_phone("(555) 123-4567").is_ok()); | |
| 260 | + assert!(validate_phone("").is_err()); | |
| 261 | + assert!(validate_phone("123456").is_err()); // 6 digits, too few | |
| 262 | + assert!(validate_phone("1234567890123456").is_err()); // 16 digits, too many | |
| 263 | + assert!(validate_phone("call-me-maybe").is_err()); // letters | |
| 264 | + assert!(validate_phone("55+5123456").is_err()); // + only allowed in front | |
| 265 | + } | |
| 266 | + | |
| 173 | 267 | #[tokio::test] |
| 174 | 268 | async fn status_rules() { |
| 175 | 269 | for status in ["present", "absent", "late", "excused"] { |
src/web/dto.rsmodified+18 -2
| @@ -30,8 +30,9 @@ impl From<DomainRole> for Role { | ||
| 30 | 30 | } |
| 31 | 31 | } |
| 32 | 32 | |
| 33 | -/// Public shape of a user: id, username, role. Never carries the password hash. | |
| 34 | -/// Shared by `auth` (register/login/me) and `users` (admin listing/role changes). | |
| 33 | +/// Public shape of a user: id, username, role, and the optional personal info | |
| 34 | +/// (`null` until filled in). Never carries the password hash. Shared by `auth` | |
| 35 | +/// (register/login/me) and `users` (listing, role and profile changes). | |
| 35 | 36 | #[derive(Serialize, ToSchema)] |
| 36 | 37 | pub struct UserResponse { |
| 37 | 38 | #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] |
| @@ -39,6 +40,16 @@ pub struct UserResponse { | ||
| 39 | 40 | #[schema(example = "ada")] |
| 40 | 41 | pub username: String, |
| 41 | 42 | pub role: Role, |
| 43 | + #[schema(example = "Ada")] | |
| 44 | + pub name: Option<String>, | |
| 45 | + #[schema(example = "Lovelace")] | |
| 46 | + pub surname: Option<String>, | |
| 47 | + #[schema(example = "ada@example.com")] | |
| 48 | + pub email: Option<String>, | |
| 49 | + #[schema(example = "+90 555 123 45 67")] | |
| 50 | + pub phone: Option<String>, | |
| 51 | + #[schema(example = "1990-01-02")] | |
| 52 | + pub birth_date: Option<String>, | |
| 42 | 53 | } |
| 43 | 54 | |
| 44 | 55 | impl UserResponse { |
| @@ -47,6 +58,11 @@ impl UserResponse { | ||
| 47 | 58 | id: user.get_id().key().to_string(), |
| 48 | 59 | username: user.get_username().as_str().to_string(), |
| 49 | 60 | role: user.get_role().into(), |
| 61 | + name: user.get_name().map(|v| v.as_str().to_string()), | |
| 62 | + surname: user.get_surname().map(|v| v.as_str().to_string()), | |
| 63 | + email: user.get_email().map(|v| v.as_str().to_string()), | |
| 64 | + phone: user.get_phone().map(|v| v.as_str().to_string()), | |
| 65 | + birth_date: user.get_birth_date().map(|v| v.as_str().to_string()), | |
| 50 | 66 | } |
| 51 | 67 | } |
| 52 | 68 | } |
src/web/users.rsmodified+143 -2
| @@ -5,18 +5,23 @@ use utoipa::ToSchema; | ||
| 5 | 5 | use utoipa_axum::router::OpenApiRouter; |
| 6 | 6 | use utoipa_axum::routes; |
| 7 | 7 | |
| 8 | +use crate::database::Database; | |
| 9 | +use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; | |
| 8 | 10 | use crate::domain::role::Role; |
| 9 | 11 | use crate::domain::user::{User, UserId}; |
| 10 | -use crate::error::{AppError, ErrorResponse}; | |
| 12 | +use crate::error::{AppError, ErrorResponse, ValidationError}; | |
| 11 | 13 | use crate::state::AppState; |
| 12 | 14 | |
| 13 | 15 | use super::dto::Role as RoleSchema; |
| 14 | -use super::{RequireAdmin, UserResponse}; | |
| 16 | +use super::{CurrentUser, RequireAdmin, UserResponse}; | |
| 15 | 17 | |
| 16 | 18 | pub fn routes() -> OpenApiRouter<AppState> { |
| 17 | 19 | OpenApiRouter::new() |
| 18 | 20 | .routes(routes!(list_users)) |
| 21 | + .routes(routes!(update_my_profile)) | |
| 22 | + .routes(routes!(get_user)) | |
| 19 | 23 | .routes(routes!(set_role)) |
| 24 | + .routes(routes!(update_user_profile)) | |
| 20 | 25 | } |
| 21 | 26 | |
| 22 | 27 | #[derive(Deserialize, ToSchema)] |
| @@ -27,6 +32,64 @@ struct SetRole { | ||
| 27 | 32 | role: String, |
| 28 | 33 | } |
| 29 | 34 | |
| 35 | +/// Partial personal-info update. Per field: omitted (or `null`) keeps the | |
| 36 | +/// current value, an empty string clears it, anything else is validated and set. | |
| 37 | +#[derive(Deserialize, ToSchema)] | |
| 38 | +struct UpdateProfile { | |
| 39 | + #[schema(example = "Ada")] | |
| 40 | + name: Option<String>, | |
| 41 | + #[schema(example = "Lovelace")] | |
| 42 | + surname: Option<String>, | |
| 43 | + #[schema(example = "ada@example.com")] | |
| 44 | + email: Option<String>, | |
| 45 | + #[schema(example = "+90 555 123 45 67")] | |
| 46 | + phone: Option<String>, | |
| 47 | + /// Birth date in `YYYY-MM-DD` form. | |
| 48 | + #[schema(example = "1990-01-02")] | |
| 49 | + birth_date: Option<String>, | |
| 50 | +} | |
| 51 | + | |
| 52 | +/// Resolve one patched field: absent keeps the current value, `""` clears it, | |
| 53 | +/// anything else must parse into the domain newtype. | |
| 54 | +fn merge_field<T: Clone>( | |
| 55 | + current: Option<&T>, | |
| 56 | + patch: Option<&str>, | |
| 57 | + parse: impl Fn(&str) -> Result<T, ValidationError>, | |
| 58 | +) -> Result<Option<T>, ValidationError> { | |
| 59 | + match patch { | |
| 60 | + None => Ok(current.cloned()), | |
| 61 | + Some("") => Ok(None), | |
| 62 | + Some(value) => Ok(Some(parse(value)?)), | |
| 63 | + } | |
| 64 | +} | |
| 65 | + | |
| 66 | +/// Merge `req` over `user`'s current info and persist. Shared by the | |
| 67 | +/// self-service and admin profile endpoints — they differ only in whose row | |
| 68 | +/// they load and who may call them. | |
| 69 | +async fn apply_profile( | |
| 70 | + user: User, | |
| 71 | + req: &UpdateProfile, | |
| 72 | + db: &Database, | |
| 73 | +) -> Result<UserResponse, AppError> { | |
| 74 | + let name = merge_field(user.get_name(), req.name.as_deref(), |v| { | |
| 75 | + PersonName::try_new("name", v) | |
| 76 | + })?; | |
| 77 | + let surname = merge_field(user.get_surname(), req.surname.as_deref(), |v| { | |
| 78 | + PersonName::try_new("surname", v) | |
| 79 | + })?; | |
| 80 | + let email = merge_field(user.get_email(), req.email.as_deref(), Email::try_new)?; | |
| 81 | + let phone = merge_field(user.get_phone(), req.phone.as_deref(), Phone::try_new)?; | |
| 82 | + let birth_date = merge_field( | |
| 83 | + user.get_birth_date(), | |
| 84 | + req.birth_date.as_deref(), | |
| 85 | + BirthDate::try_new, | |
| 86 | + )?; | |
| 87 | + let updated = user | |
| 88 | + .set_profile(name, surname, email, phone, birth_date, db) | |
| 89 | + .await?; | |
| 90 | + Ok(UserResponse::new(&updated)) | |
| 91 | +} | |
| 92 | + | |
| 30 | 93 | /// List every user with their role. Admin only. |
| 31 | 94 | #[utoipa::path( |
| 32 | 95 | get, |
| @@ -47,6 +110,84 @@ async fn list_users( | ||
| 47 | 110 | Ok(Json(users.iter().map(UserResponse::new).collect())) |
| 48 | 111 | } |
| 49 | 112 | |
| 113 | +/// Update the caller's own personal info: name, surname, email, phone, birth | |
| 114 | +/// date. Any authenticated role. Omitted fields stay as they are; an empty | |
| 115 | +/// string clears a field. | |
| 116 | +#[utoipa::path( | |
| 117 | + patch, | |
| 118 | + path = "/me", | |
| 119 | + tag = "users", | |
| 120 | + security(("session_cookie" = [])), | |
| 121 | + request_body = UpdateProfile, | |
| 122 | + responses( | |
| 123 | + (status = 200, description = "Updated user", body = UserResponse), | |
| 124 | + (status = 400, description = "Invalid field", body = ErrorResponse), | |
| 125 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 126 | + ), | |
| 127 | +)] | |
| 128 | +async fn update_my_profile( | |
| 129 | + State(st): State<AppState>, | |
| 130 | + CurrentUser(user): CurrentUser, | |
| 131 | + Json(req): Json<UpdateProfile>, | |
| 132 | +) -> Result<Json<UserResponse>, AppError> { | |
| 133 | + Ok(Json(apply_profile(user, &req, &st.db).await?)) | |
| 134 | +} | |
| 135 | + | |
| 136 | +/// Fetch one user with their role and personal info. Admin only. | |
| 137 | +#[utoipa::path( | |
| 138 | + get, | |
| 139 | + path = "/{id}", | |
| 140 | + tag = "users", | |
| 141 | + security(("session_cookie" = [])), | |
| 142 | + params(("id" = String, Path, description = "User id")), | |
| 143 | + responses( | |
| 144 | + (status = 200, description = "The user", body = UserResponse), | |
| 145 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 146 | + (status = 403, description = "Requires admin role", body = ErrorResponse), | |
| 147 | + (status = 404, description = "User not found", body = ErrorResponse), | |
| 148 | + ), | |
| 149 | +)] | |
| 150 | +async fn get_user( | |
| 151 | + State(st): State<AppState>, | |
| 152 | + _admin: RequireAdmin, | |
| 153 | + Path(id): Path<String>, | |
| 154 | +) -> Result<Json<UserResponse>, AppError> { | |
| 155 | + let user = User::read(&UserId::from_key(&id), &st.db) | |
| 156 | + .await? | |
| 157 | + .ok_or(AppError::NotFound)?; | |
| 158 | + Ok(Json(UserResponse::new(&user))) | |
| 159 | +} | |
| 160 | + | |
| 161 | +/// Update any user's personal info. Admin only — the school-office path for | |
| 162 | +/// maintaining records on behalf of students and staff. Same field semantics | |
| 163 | +/// as `PATCH /users/me`. | |
| 164 | +#[utoipa::path( | |
| 165 | + patch, | |
| 166 | + path = "/{id}/profile", | |
| 167 | + tag = "users", | |
| 168 | + security(("session_cookie" = [])), | |
| 169 | + params(("id" = String, Path, description = "User id")), | |
| 170 | + request_body = UpdateProfile, | |
| 171 | + responses( | |
| 172 | + (status = 200, description = "Updated user", body = UserResponse), | |
| 173 | + (status = 400, description = "Invalid field", body = ErrorResponse), | |
| 174 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 175 | + (status = 403, description = "Requires admin role", body = ErrorResponse), | |
| 176 | + (status = 404, description = "User not found", body = ErrorResponse), | |
| 177 | + ), | |
| 178 | +)] | |
| 179 | +async fn update_user_profile( | |
| 180 | + State(st): State<AppState>, | |
| 181 | + _admin: RequireAdmin, | |
| 182 | + Path(id): Path<String>, | |
| 183 | + Json(req): Json<UpdateProfile>, | |
| 184 | +) -> Result<Json<UserResponse>, AppError> { | |
| 185 | + let user = User::read(&UserId::from_key(&id), &st.db) | |
| 186 | + .await? | |
| 187 | + .ok_or(AppError::NotFound)?; | |
| 188 | + Ok(Json(apply_profile(user, &req, &st.db).await?)) | |
| 189 | +} | |
| 190 | + | |
| 50 | 191 | /// Set a user's role. Admin only. An admin cannot change their own role — that |
| 51 | 192 | /// guard keeps a sole admin from accidentally locking everyone out of role |
| 52 | 193 | /// management (recover such a lockout with the SurrealQL in the README). |