| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | use std::sync::OnceLock; |
| 7 | |
| 8 | use argon2::password_hash::phc::PasswordHash as PhcHash; |
| 9 | use argon2::{Argon2, PasswordHasher, PasswordVerifier}; |
| 10 | use uuid::Uuid; |
| 11 | |
| 12 | use crate::constant::{AI_PRINCIPAL_KEY, DECOY_PASSWORD, MAX_STUDENT_NUMBER_LEN}; |
| 13 | use crate::domain::monotonic_id::next_uuid; |
| 14 | use crate::domain::note_file::FileContentType; |
| 15 | use crate::domain::person::PersonId; |
| 16 | use crate::domain::preferences::{Language, PaletteColor, Theme}; |
| 17 | use crate::domain::profile::{ |
| 18 | Address, Bio, BirthDate, DisplayName, Email, Gender, PersonName, Phone, |
| 19 | }; |
| 20 | use crate::domain::role::Role; |
| 21 | use crate::error::{AppError, ValidationError}; |
| 22 | use crate::validate::{validate_password, validate_required, validate_username}; |
| 23 | |
| 24 | |
| 25 | |
| 26 | #[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)] |
| 27 | #[sqlx(transparent)] |
| 28 | pub struct UserId(Uuid); |
| 29 | |
| 30 | impl UserId { |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | pub fn generate() -> Self { |
| 38 | Self(next_uuid()) |
| 39 | } |
| 40 | |
| 41 | |
| 42 | |
| 43 | pub fn uuid(&self) -> Uuid { |
| 44 | self.0 |
| 45 | } |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | pub fn from_key(key: &str) -> Self { |
| 52 | Self(Uuid::parse_str(key).unwrap_or(Uuid::nil())) |
| 53 | } |
| 54 | |
| 55 | |
| 56 | pub fn key(&self) -> String { |
| 57 | self.0.to_string() |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 66 | #[sqlx(transparent)] |
| 67 | pub struct Username(String); |
| 68 | |
| 69 | impl Username { |
| 70 | pub fn try_new(value: &str) -> Result<Self, ValidationError> { |
| 71 | validate_username(value)?; |
| 72 | Ok(Self(value.trim().to_string())) |
| 73 | } |
| 74 | |
| 75 | pub fn as_str(&self) -> &str { |
| 76 | &self.0 |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)] |
| 90 | #[sqlx(transparent)] |
| 91 | pub struct StudentNumber(String); |
| 92 | |
| 93 | impl StudentNumber { |
| 94 | pub fn try_new(value: &str) -> Result<Self, ValidationError> { |
| 95 | let trimmed = value.trim(); |
| 96 | validate_required("student_number", trimmed, MAX_STUDENT_NUMBER_LEN)?; |
| 97 | Ok(Self(trimmed.to_string())) |
| 98 | } |
| 99 | |
| 100 | pub fn as_str(&self) -> &str { |
| 101 | &self.0 |
| 102 | } |
| 103 | |
| 104 | |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | pub fn non_student_refusal() -> ValidationError { |
| 111 | ValidationError::Invalid { |
| 112 | field: "student_number", |
| 113 | reason: "only a student account may hold a student number", |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | |
| 125 | fn argon2_permits() -> &'static tokio::sync::Semaphore { |
| 126 | static PERMITS: OnceLock<tokio::sync::Semaphore> = OnceLock::new(); |
| 127 | PERMITS.get_or_init(|| { |
| 128 | let cores = std::thread::available_parallelism().map_or(2, |n| n.get()); |
| 129 | tokio::sync::Semaphore::new(cores * 2) |
| 130 | }) |
| 131 | } |
| 132 | |
| 133 | |
| 134 | pub struct Password(String); |
| 135 | |
| 136 | impl Password { |
| 137 | pub fn try_new(value: &str) -> Result<Self, ValidationError> { |
| 138 | validate_password(value)?; |
| 139 | Ok(Self(value.to_string())) |
| 140 | } |
| 141 | |
| 142 | |
| 143 | |
| 144 | fn hash(&self) -> Result<PasswordHash, AppError> { |
| 145 | |
| 146 | |
| 147 | let hash = Argon2::default() |
| 148 | .hash_password(self.0.as_bytes())? |
| 149 | .to_string(); |
| 150 | Ok(PasswordHash(hash)) |
| 151 | } |
| 152 | |
| 153 | |
| 154 | |
| 155 | |
| 156 | |
| 157 | pub async fn hash_async(&self) -> Result<PasswordHash, AppError> { |
| 158 | let plain = self.0.clone(); |
| 159 | let _permit = argon2_permits() |
| 160 | .acquire() |
| 161 | .await |
| 162 | .map_err(|e| AppError::Internal(format!("hash permit: {e}")))?; |
| 163 | tokio::task::spawn_blocking(move || Password(plain).hash()) |
| 164 | .await |
| 165 | .map_err(|e| AppError::Internal(format!("hash task: {e}")))? |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | |
| 170 | #[derive(Debug, Clone, sqlx::Type)] |
| 171 | #[sqlx(transparent)] |
| 172 | pub struct PasswordHash(String); |
| 173 | |
| 174 | |
| 175 | |
| 176 | fn decoy_hash() -> &'static PasswordHash { |
| 177 | static DECOY: OnceLock<PasswordHash> = OnceLock::new(); |
| 178 | DECOY.get_or_init(|| { |
| 179 | Password::try_new(DECOY_PASSWORD) |
| 180 | .expect("decoy password satisfies the password rules") |
| 181 | .hash() |
| 182 | .expect("decoy password hashes") |
| 183 | }) |
| 184 | } |
| 185 | |
| 186 | impl PasswordHash { |
| 187 | pub fn as_str(&self) -> &str { |
| 188 | &self.0 |
| 189 | } |
| 190 | |
| 191 | |
| 192 | fn verify(&self, password: &Password) -> bool { |
| 193 | match PhcHash::new(&self.0) { |
| 194 | Ok(parsed) => Argon2::default() |
| 195 | .verify_password(password.0.as_bytes(), &parsed) |
| 196 | .is_ok(), |
| 197 | Err(_) => false, |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | |
| 202 | pub async fn verify_async(&self, password: &Password) -> bool { |
| 203 | let hash = self.0.clone(); |
| 204 | let plain = password.0.clone(); |
| 205 | |
| 206 | |
| 207 | |
| 208 | let Ok(_permit) = argon2_permits().acquire().await else { |
| 209 | return false; |
| 210 | }; |
| 211 | tokio::task::spawn_blocking(move || PasswordHash(hash).verify(&Password(plain))) |
| 212 | .await |
| 213 | .unwrap_or(false) |
| 214 | } |
| 215 | |
| 216 | |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | pub async fn verify_decoy_async(password: &Password) { |
| 222 | let plain = password.0.clone(); |
| 223 | |
| 224 | let Ok(_permit) = argon2_permits().acquire().await else { |
| 225 | return; |
| 226 | }; |
| 227 | let _ = tokio::task::spawn_blocking(move || decoy_hash().verify(&Password(plain))).await; |
| 228 | } |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | |
| 235 | pub fn prewarm_decoy() { |
| 236 | |
| 237 | |
| 238 | tokio::task::spawn_blocking(|| { |
| 239 | decoy_hash(); |
| 240 | }); |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | #[derive(Debug, Clone, sqlx::FromRow)] |
| 245 | |
| 246 | |
| 247 | pub struct User { |
| 248 | pub(crate) id: UserId, |
| 249 | pub(crate) username: Username, |
| 250 | |
| 251 | |
| 252 | |
| 253 | pub(crate) person: Option<PersonId>, |
| 254 | pub(crate) role: Role, |
| 255 | |
| 256 | |
| 257 | |
| 258 | |
| 259 | |
| 260 | pub(crate) student_number: Option<StudentNumber>, |
| 261 | |
| 262 | |
| 263 | |
| 264 | pub(crate) name: Option<PersonName>, |
| 265 | pub(crate) surname: Option<PersonName>, |
| 266 | pub(crate) email: Option<Email>, |
| 267 | pub(crate) phone: Option<Phone>, |
| 268 | pub(crate) birth_date: Option<BirthDate>, |
| 269 | |
| 270 | |
| 271 | |
| 272 | pub(crate) gender: Option<Gender>, |
| 273 | pub(crate) address: Option<Address>, |
| 274 | pub(crate) emergency_contact_name: Option<PersonName>, |
| 275 | pub(crate) emergency_contact_phone: Option<Phone>, |
| 276 | |
| 277 | |
| 278 | pub(crate) theme: Option<Theme>, |
| 279 | pub(crate) language: Option<Language>, |
| 280 | pub(crate) palette_color: Option<PaletteColor>, |
| 281 | |
| 282 | |
| 283 | |
| 284 | |
| 285 | |
| 286 | |
| 287 | pub(crate) display_name: Option<DisplayName>, |
| 288 | pub(crate) bio: Option<Bio>, |
| 289 | |
| 290 | |
| 291 | |
| 292 | pub(crate) branch: Option<String>, |
| 293 | pub(crate) avatar_file: Option<String>, |
| 294 | pub(crate) avatar_content_type: Option<FileContentType>, |
| 295 | pub(crate) avatar_size: Option<i64>, |
| 296 | } |
| 297 | |
| 298 | impl User { |
| 299 | |
| 300 | |
| 301 | |
| 302 | |
| 303 | |
| 304 | |
| 305 | |
| 306 | pub(crate) fn ai_principal() -> User { |
| 307 | User { |
| 308 | id: UserId(Uuid::nil()), |
| 309 | username: Username(AI_PRINCIPAL_KEY.to_string()), |
| 310 | person: None, |
| 311 | role: Role::Ai, |
| 312 | student_number: None, |
| 313 | name: None, |
| 314 | surname: None, |
| 315 | email: None, |
| 316 | phone: None, |
| 317 | birth_date: None, |
| 318 | gender: None, |
| 319 | address: None, |
| 320 | emergency_contact_name: None, |
| 321 | emergency_contact_phone: None, |
| 322 | theme: None, |
| 323 | language: None, |
| 324 | palette_color: None, |
| 325 | display_name: None, |
| 326 | bio: None, |
| 327 | branch: None, |
| 328 | avatar_file: None, |
| 329 | avatar_content_type: None, |
| 330 | avatar_size: None, |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | pub fn get_id(&self) -> &UserId { |
| 335 | &self.id |
| 336 | } |
| 337 | |
| 338 | pub fn get_username(&self) -> &Username { |
| 339 | &self.username |
| 340 | } |
| 341 | pub fn get_person(&self) -> Option<&PersonId> { |
| 342 | self.person.as_ref() |
| 343 | } |
| 344 | |
| 345 | pub fn get_role(&self) -> Role { |
| 346 | self.role |
| 347 | } |
| 348 | |
| 349 | |
| 350 | |
| 351 | |
| 352 | |
| 353 | pub fn get_student_number(&self) -> Option<&StudentNumber> { |
| 354 | self.student_number.as_ref() |
| 355 | } |
| 356 | |
| 357 | pub fn get_name(&self) -> Option<&PersonName> { |
| 358 | self.name.as_ref() |
| 359 | } |
| 360 | |
| 361 | pub fn get_surname(&self) -> Option<&PersonName> { |
| 362 | self.surname.as_ref() |
| 363 | } |
| 364 | |
| 365 | pub fn get_email(&self) -> Option<&Email> { |
| 366 | self.email.as_ref() |
| 367 | } |
| 368 | |
| 369 | pub fn get_phone(&self) -> Option<&Phone> { |
| 370 | self.phone.as_ref() |
| 371 | } |
| 372 | |
| 373 | pub fn get_birth_date(&self) -> Option<&BirthDate> { |
| 374 | self.birth_date.as_ref() |
| 375 | } |
| 376 | |
| 377 | pub fn get_gender(&self) -> Option<Gender> { |
| 378 | self.gender |
| 379 | } |
| 380 | |
| 381 | pub fn get_address(&self) -> Option<&Address> { |
| 382 | self.address.as_ref() |
| 383 | } |
| 384 | |
| 385 | pub fn get_emergency_contact_name(&self) -> Option<&PersonName> { |
| 386 | self.emergency_contact_name.as_ref() |
| 387 | } |
| 388 | |
| 389 | pub fn get_emergency_contact_phone(&self) -> Option<&Phone> { |
| 390 | self.emergency_contact_phone.as_ref() |
| 391 | } |
| 392 | |
| 393 | pub fn get_theme(&self) -> Option<Theme> { |
| 394 | self.theme |
| 395 | } |
| 396 | |
| 397 | pub fn get_language(&self) -> Option<Language> { |
| 398 | self.language |
| 399 | } |
| 400 | |
| 401 | pub fn get_palette_color(&self) -> Option<&PaletteColor> { |
| 402 | self.palette_color.as_ref() |
| 403 | } |
| 404 | |
| 405 | pub fn get_display_name(&self) -> Option<&DisplayName> { |
| 406 | self.display_name.as_ref() |
| 407 | } |
| 408 | |
| 409 | pub fn get_bio(&self) -> Option<&Bio> { |
| 410 | self.bio.as_ref() |
| 411 | } |
| 412 | |
| 413 | |
| 414 | |
| 415 | pub fn get_branch(&self) -> Option<&str> { |
| 416 | self.branch.as_deref() |
| 417 | } |
| 418 | |
| 419 | pub fn get_avatar_file(&self) -> Option<&str> { |
| 420 | self.avatar_file.as_deref() |
| 421 | } |
| 422 | |
| 423 | pub fn get_avatar_content_type(&self) -> Option<&FileContentType> { |
| 424 | self.avatar_content_type.as_ref() |
| 425 | } |
| 426 | |
| 427 | pub fn get_avatar_size(&self) -> Option<i64> { |
| 428 | self.avatar_size |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | #[cfg(test)] |
| 433 | mod tests { |
| 434 | use super::*; |
| 435 | |
| 436 | #[tokio::test] |
| 437 | async fn username_newtype_validates() { |
| 438 | assert_eq!(Username::try_new("ali").unwrap().as_str(), "ali"); |
| 439 | assert!(Username::try_new("").is_err()); |
| 440 | assert!(Username::try_new("ab").is_err()); |
| 441 | assert!(Username::try_new("Ali").is_err()); |
| 442 | assert!(Username::try_new("-ali").is_err()); |
| 443 | assert!(Username::try_new("ali-").is_err()); |
| 444 | } |
| 445 | |
| 446 | #[tokio::test] |
| 447 | async fn username_is_stored_trimmed() { |
| 448 | |
| 449 | |
| 450 | |
| 451 | assert_eq!(Username::try_new(" ali ").unwrap().as_str(), "ali"); |
| 452 | } |
| 453 | |
| 454 | #[tokio::test] |
| 455 | async fn student_number_newtype_validates_and_trims() { |
| 456 | |
| 457 | |
| 458 | assert_eq!(StudentNumber::try_new(" 1234 ").unwrap().as_str(), "1234"); |
| 459 | assert!(StudentNumber::try_new("").is_err()); |
| 460 | assert!(StudentNumber::try_new(" ").is_err()); |
| 461 | assert!(StudentNumber::try_new(&"9".repeat(MAX_STUDENT_NUMBER_LEN)).is_ok()); |
| 462 | assert!(StudentNumber::try_new(&"9".repeat(MAX_STUDENT_NUMBER_LEN + 1)).is_err()); |
| 463 | } |
| 464 | |
| 465 | #[tokio::test] |
| 466 | async fn short_password_rejected() { |
| 467 | assert!(Password::try_new("123").is_err()); |
| 468 | assert!(Password::try_new("secret1").is_ok()); |
| 469 | } |
| 470 | |
| 471 | #[tokio::test] |
| 472 | async fn password_hash_roundtrips() { |
| 473 | let hash = Password::try_new("secret1").unwrap().hash().unwrap(); |
| 474 | assert!(hash.verify(&Password::try_new("secret1").unwrap())); |
| 475 | assert!(!hash.verify(&Password::try_new("wrongpw").unwrap())); |
| 476 | } |
| 477 | |
| 478 | #[tokio::test] |
| 479 | async fn decoy_hash_is_valid_and_nonmatching() { |
| 480 | |
| 481 | |
| 482 | |
| 483 | assert!( |
| 484 | decoy_hash().verify(&Password::try_new(DECOY_PASSWORD).unwrap()), |
| 485 | "decoy hash must verify its own password" |
| 486 | ); |
| 487 | assert!(!decoy_hash().verify(&Password::try_new("some-other-pw").unwrap())); |
| 488 | } |
| 489 | |
| 490 | #[tokio::test] |
| 491 | async fn user_id_key_roundtrips() { |
| 492 | let id = UserId::generate(); |
| 493 | let key = id.key(); |
| 494 | assert!(!key.is_empty()); |
| 495 | assert_eq!(UserId::from_key(&key).key(), key); |
| 496 | } |
| 497 | } |