openlegends_api/user/register/request/
data.rs

1pub mod error;
2pub use error::Error;
3
4pub const PASSWORD_PATTERN: &str = r"^[\w]{6,64}$"; // @TODO
5pub const USERNAME_PATTERN: &str = r"^[\w]{2,64}$";
6
7use regex::Regex;
8use serde::{Deserialize, Serialize};
9
10#[derive(Serialize, Deserialize, Debug)]
11pub struct Data {
12    password: String,
13    username: String,
14}
15
16impl Data {
17    pub fn build(username: String, password: String) -> Result<Self, Error> {
18        match Regex::new(USERNAME_PATTERN) {
19            Ok(regex) => {
20                if regex.is_match(&username) {
21                    match Regex::new(PASSWORD_PATTERN) {
22                        Ok(regex) => {
23                            if regex.is_match(&password) {
24                                Ok(Self { password, username })
25                            } else {
26                                Err(Error::Password(PASSWORD_PATTERN.to_string()))
27                            }
28                        }
29                        Err(e) => Err(Error::Regex(e)),
30                    }
31                } else {
32                    Err(Error::Username(USERNAME_PATTERN.to_string()))
33                }
34            }
35            Err(e) => Err(Error::Regex(e)),
36        }
37    }
38
39    pub fn to_json(&self) -> Result<String, Error> {
40        match serde_json::to_string(&self) {
41            Ok(json) => Ok(json),
42            Err(e) => Err(Error::Json(e)),
43        }
44    }
45
46    pub fn username(&self) -> &str {
47        &self.username
48    }
49}