use thiserror::Error;
#[derive(Error, Debug, Clone)]
pub enum CCashUsernameError {
#[error("CCashUserError: Name too short (needs to be atleast 3 characters)")]
NameTooShort,
#[error("CCashUserError: Name too long (needs to be at most 16 characters)")]
NameTooLong,
#[error("CCashUserError: Name contains invalid characters: {0}")]
NameContainsInvalidCharacters(String),
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct CCashUser {
#[serde(rename(serialize = "name"))]
pub(crate) username: String,
#[serde(rename(serialize = "pass"))]
pub(crate) password: String,
}
impl CCashUser {
pub fn new(username: &str, password: &str) -> Result<Self, CCashUsernameError> {
let username = username.to_lowercase();
if username.len() < 3 {
return Err(CCashUsernameError::NameTooShort);
} else if username.len() > 16 {
return Err(CCashUsernameError::NameTooLong);
} else if username.contains(' ') {
return Err(CCashUsernameError::NameContainsInvalidCharacters(
"Name cannot contain spaces".into(),
));
} else if !username.is_ascii() {
return Err(CCashUsernameError::NameContainsInvalidCharacters(
"Name cannot contain non-alphanumeric characters".into(),
));
}
Ok(Self {
username,
password: password.into(),
})
}
pub fn new_unchecked(username: &str, password: &str) -> Self {
Self {
username: username.into(),
password: password.into(),
}
}
pub fn get_username(&self) -> &str { &self.username }
pub fn get_password(&self) -> &str { &self.password }
pub(crate) fn update_password(&mut self, new_password: &str) {
self.password = new_password.into();
}
}