diff --git a/src/bin/mitractl.rs b/src/bin/mitractl.rs index e39267b..76485bf 100644 --- a/src/bin/mitractl.rs +++ b/src/bin/mitractl.rs @@ -10,7 +10,7 @@ use mitra::logger::configure_logger; use mitra::models::posts::queries::delete_post; use mitra::models::profiles::queries::delete_profile; use mitra::models::users::queries::{ - generate_invite_code, + create_invite_code, get_invite_codes, }; @@ -77,7 +77,7 @@ async fn main() { println!("post deleted"); }, SubCommand::GenerateInviteCode(_) => { - let invite_code = generate_invite_code(db_client).await.unwrap(); + let invite_code = create_invite_code(db_client).await.unwrap(); println!("generated invite code: {}", invite_code); }, SubCommand::ListInviteCodes(_) => { diff --git a/src/models/users/mod.rs b/src/models/users/mod.rs index 0333ab5..4c01618 100644 --- a/src/models/users/mod.rs +++ b/src/models/users/mod.rs @@ -1,2 +1,3 @@ pub mod queries; pub mod types; +mod utils; diff --git a/src/models/users/queries.rs b/src/models/users/queries.rs index 305f874..b6ca770 100644 --- a/src/models/users/queries.rs +++ b/src/models/users/queries.rs @@ -4,13 +4,13 @@ use uuid::Uuid; use crate::errors::DatabaseError; use crate::models::profiles::queries::create_profile; use crate::models::profiles::types::{DbActorProfile, ProfileCreateData}; -use crate::utils::crypto::generate_random_string; use super::types::{DbUser, User, UserRegistrationData}; +use super::utils::generate_invite_code; -pub async fn generate_invite_code( +pub async fn create_invite_code( db_client: &impl GenericClient, ) -> Result { - let invite_code = generate_random_string(); + let invite_code = generate_invite_code(); db_client.execute( " INSERT INTO user_invite_code (code) diff --git a/src/models/users/utils.rs b/src/models/users/utils.rs new file mode 100644 index 0000000..9d88209 --- /dev/null +++ b/src/models/users/utils.rs @@ -0,0 +1,22 @@ +use hex; +use rand; +use rand::prelude::*; + +const INVITE_CODE_LENGTH: usize = 32; + +pub fn generate_invite_code() -> String { + let mut rng = rand::thread_rng(); + let value: [u8; INVITE_CODE_LENGTH / 2] = rng.gen(); + hex::encode(value) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_generate_invite_code() { + let invite_code = generate_invite_code(); + assert_eq!(invite_code.len(), INVITE_CODE_LENGTH); + } +} diff --git a/src/utils/crypto.rs b/src/utils/crypto.rs index 1c9c7ba..9bf7d9e 100644 --- a/src/utils/crypto.rs +++ b/src/utils/crypto.rs @@ -4,12 +4,6 @@ use rsa::{Hash, PaddingScheme, PublicKey, RsaPrivateKey, RsaPublicKey}; use rsa::pkcs8::{FromPrivateKey, FromPublicKey, ToPrivateKey, ToPublicKey}; use sha2::{Digest, Sha256}; -pub fn generate_random_string() -> String { - let mut rng = rand::thread_rng(); - let value: [u8; 16] = rng.gen(); - hex::encode(value) -} - pub fn hash_password(password: &str) -> Result { let mut rng = rand::thread_rng(); let salt: [u8; 32] = rng.gen();