1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use crate::prelude::*;
pub use crate::{Login, Signup};
use lazy_static::lazy_static;
use regex::Regex;
const EMAIL_REGEX: &str = r"^[\w\-\.]+@([\w-]+\.)+[\w\-]{2,4}$";
impl Signup {
pub fn is_valid(&self) -> Result<()> {
self.password.is_secure()?;
self.email.is_valid()?;
Ok(())
}
}
impl From<Signup> for Login {
fn from(form: Signup) -> Login {
Login {
email: form.email,
password: form.password,
}
}
}
pub trait ValidEmail {
fn is_valid(&self) -> Result<()>;
}
pub trait SafePassword {
fn is_secure(&self) -> Result<()>;
}
impl ValidEmail for str {
fn is_valid(&self) -> Result<()> {
lazy_static! {
static ref RE: Regex = Regex::new(EMAIL_REGEX).unwrap();
}
if RE.is_match(&self) {
Ok(())
} else {
Err(Error {
message: format!("'{}' is not a valid email address.", self),
kind: ErrorKind::FormValidationError,
})
}
}
}
impl SafePassword for str {
fn is_secure(&self) -> Result<()> {
if self.len() > 8 {
Ok(())
} else {
raise(
ErrorKind::UnsafePasswordError,
"Unsafe password. It must be at least 8 characters long.",
)
}
}
}