fedimovies/src/models/users/types.rs

87 lines
2.2 KiB
Rust
Raw Normal View History

2021-04-09 00:22:17 +00:00
use chrono::{DateTime, Utc};
use postgres_types::FromSql;
use regex::Regex;
use serde::Deserialize;
use uuid::Uuid;
use crate::errors::ValidationError;
use crate::models::profiles::types::DbActorProfile;
use crate::models::profiles::validators::validate_username;
2021-04-09 00:22:17 +00:00
#[derive(FromSql)]
#[postgres(name = "user_account")]
pub struct DbUser {
pub id: Uuid,
pub wallet_address: Option<String>,
2021-04-09 00:22:17 +00:00
pub password_hash: String,
pub private_key: String,
pub invite_code: Option<String>,
pub created_at: DateTime<Utc>,
}
// Represents local user
#[derive(Clone)]
#[cfg_attr(test, derive(Default))]
2021-04-09 00:22:17 +00:00
pub struct User {
pub id: Uuid,
pub wallet_address: Option<String>,
2021-04-09 00:22:17 +00:00
pub password_hash: String,
pub private_key: String,
pub profile: DbActorProfile,
}
2021-11-12 22:05:31 +00:00
impl User {
pub fn new(
db_user: DbUser,
db_profile: DbActorProfile,
) -> Self {
assert_eq!(db_user.id, db_profile.id);
Self {
id: db_user.id,
wallet_address: db_user.wallet_address,
password_hash: db_user.password_hash,
private_key: db_user.private_key,
profile: db_profile,
}
}
}
2021-04-09 00:22:17 +00:00
#[derive(Deserialize)]
2021-10-05 20:57:24 +00:00
pub struct UserCreateData {
2021-04-09 00:22:17 +00:00
pub username: String,
2021-10-05 20:57:24 +00:00
pub password: String,
pub wallet_address: Option<String>,
2021-04-09 00:22:17 +00:00
pub invite_code: Option<String>,
}
fn validate_local_username(username: &str) -> Result<(), ValidationError> {
// The username regexp should not allow domain names and IP addresses
2021-04-09 00:22:17 +00:00
let username_regexp = Regex::new(r"^[a-z0-9_]+$").unwrap();
if !username_regexp.is_match(username) {
return Err(ValidationError("invalid username"));
}
Ok(())
}
2021-10-05 20:57:24 +00:00
impl UserCreateData {
2021-04-09 00:22:17 +00:00
/// Validate and clean.
pub fn clean(&self) -> Result<(), ValidationError> {
validate_username(&self.username)?;
validate_local_username(&self.username)?;
2021-04-09 00:22:17 +00:00
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_validate_local_username() {
let result_1 = validate_local_username("name_1");
2021-04-09 00:22:17 +00:00
assert_eq!(result_1.is_ok(), true);
let result_2 = validate_local_username("name&");
2021-04-09 00:22:17 +00:00
assert_eq!(result_2.is_ok(), false);
}
}