extern crate bcrypt; use bcrypt::{hash, DEFAULT_COST}; use diesel::Insertable; use uuid::Uuid; use crate::schema::users; pub const MIN_PASSWORD_LENGTH: usize = 6; /// Rejects empty/trivial passwords. Kept as a standalone function so callers /// (e.g. the user-creation handler) can return a `400` for this case /// specifically, rather than the `500` that `NewUser::new`'s `anyhow::Result` /// would otherwise map to. pub fn validate_password(password: &str) -> Result<(), &'static str> { if password.trim().len() < MIN_PASSWORD_LENGTH { return Err("password must be at least 6 characters long"); } Ok(()) } #[derive(Insertable, Clone)] #[diesel(table_name=users)] pub struct NewUser { pub username: String, pub email: String, pub password: String, pub unique_id: String, } impl NewUser { pub fn new(username: String, email: String, password: String) -> anyhow::Result { validate_password(&password).map_err(anyhow::Error::msg)?; let hashed_password: String = hash(password.as_str(), DEFAULT_COST)?; let uuid = Uuid::new_v4(); Ok(NewUser { username, email, password: hashed_password, unique_id: uuid.to_string(), }) } }