sunday_slate/auth/
password.rs1use crate::validation::no_whitespace;
2use garde::Validate;
3use serde::Deserialize;
4
5#[derive(Debug, Clone, PartialEq, Deserialize, Validate)]
8#[garde(transparent)]
9pub struct Password(#[garde(ascii, length(min = 8), custom(no_whitespace))] pub String);
10pub fn hash(plain: &str) -> String {
11 password_auth::generate_hash(plain)
12}
13
14pub fn verify(plain: &str, stored_hash: &str) -> bool {
15 password_auth::verify_password(plain, stored_hash).is_ok()
16}
17
18pub fn is_obsolete(stored_hash: &str) -> bool {
19 password_auth::is_hash_obsolete(stored_hash).unwrap_or(false)
20}
21
22#[cfg(test)]
23mod tests {
24 use super::*;
25
26 #[test]
27 fn hash_verify_roundtrip() {
28 let hash = hash("correct horse battery staple");
29 assert!(verify("correct horse battery staple", &hash));
30 }
31
32 #[test]
33 fn verify_wrong_password_fails() {
34 let hash = hash("hunter2");
35 assert!(!verify("wrong", &hash));
36 }
37
38 #[test]
39 fn verify_invalid_hash_fails() {
40 assert!(!verify("anything", "not-a-valid-hash"));
41 }
42
43 #[test]
44 fn fresh_hash_is_not_obsolete() {
45 let hash = hash("password");
46 assert!(!is_obsolete(&hash));
47 }
48
49 use garde::Validate;
50
51 #[test]
52 fn password_accepts_valid() {
53 let p = Password("hunter22".to_string());
54 assert!(p.validate().is_ok());
55 }
56
57 #[test]
58 fn password_rejects_short() {
59 let p = Password("short".to_string());
60 let Err(report) = p.validate() else {
61 panic!("expected error");
62 };
63 for (_path, err) in report.iter() {
64 assert!(err.message().contains("length"));
65 assert!(!err.message().contains("ascii"));
66 assert!(!err.message().contains("whitespace"));
67 assert!(!err.message().contains("spaces"));
68 }
69 }
70
71 #[test]
72 fn password_rejects_non_ascii() {
73 let p = Password("hunter😀22".to_string());
74 let Err(report) = p.validate() else {
75 panic!("expected error");
76 };
77 for (_, err) in report.iter() {
78 assert_eq!(err.message(), "not ascii");
79 }
80 }
81
82 #[test]
83 fn password_rejects_whitespace() {
84 let p = Password("hunter 22".to_string());
85 let Err(report) = p.validate() else {
86 panic!("expected error");
87 };
88 for (_, err) in report.iter() {
89 assert_eq!(err.message(), "must not contain spaces");
90 }
91 }
92
93 #[test]
94 fn password_accumulates_multiple_errors() {
95 let p = Password("sh ort".to_string()); let Err(report) = p.validate() else {
97 panic!("expected error");
98 };
99 let mut messages: Vec<&str> = report.iter().map(|(_, e)| e.message()).collect();
100 messages.sort();
101 assert_eq!(messages.len(), 2);
102 assert!(messages.contains(&"length is lower than 8"));
103 assert!(messages.contains(&"must not contain spaces"));
104 }
105}