diff --git a/src/mastodon_api/oauth/utils.rs b/src/mastodon_api/oauth/utils.rs index affad95..dba07cb 100644 --- a/src/mastodon_api/oauth/utils.rs +++ b/src/mastodon_api/oauth/utils.rs @@ -1,6 +1,6 @@ use base64; -use rand; -use rand::prelude::*; + +use crate::utils::random::generate_random_sequence; pub fn render_authorization_page() -> String { let page = r#" @@ -41,8 +41,7 @@ pub fn render_authorization_page() -> String { const ACCESS_TOKEN_SIZE: usize = 20; pub fn generate_access_token() -> String { - let mut rng = rand::thread_rng(); - let value: [u8; ACCESS_TOKEN_SIZE] = rng.gen(); + let value: [u8; ACCESS_TOKEN_SIZE] = generate_random_sequence(); base64::encode_config(value, base64::URL_SAFE_NO_PAD) } diff --git a/src/models/users/utils.rs b/src/models/users/utils.rs index 9d88209..a2485da 100644 --- a/src/models/users/utils.rs +++ b/src/models/users/utils.rs @@ -1,12 +1,11 @@ use hex; -use rand; -use rand::prelude::*; + +use crate::utils::random::generate_random_sequence; 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(); + let value: [u8; INVITE_CODE_LENGTH / 2] = generate_random_sequence(); hex::encode(value) } diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 0cfd55f..999af7f 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -9,4 +9,5 @@ pub mod id; pub mod markdown; pub mod multibase; pub mod passwords; +pub mod random; pub mod urls; diff --git a/src/utils/passwords.rs b/src/utils/passwords.rs index 081862e..80c31e7 100644 --- a/src/utils/passwords.rs +++ b/src/utils/passwords.rs @@ -1,8 +1,7 @@ -use rand::Rng; +use super::random::generate_random_sequence; pub fn hash_password(password: &str) -> Result { - let mut rng = rand::thread_rng(); - let salt: [u8; 32] = rng.gen(); + let salt: [u8; 32] = generate_random_sequence(); let config = argon2::Config::default(); argon2::hash_encoded(password.as_bytes(), &salt, &config) @@ -14,3 +13,16 @@ pub fn verify_password( ) -> Result { argon2::verify_encoded(password_hash, password.as_bytes()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_verify_password() { + let password = "$test123"; + let password_hash = hash_password(password).unwrap(); + let result = verify_password(&password_hash, password); + assert_eq!(result.is_ok(), true); + } +} diff --git a/src/utils/random.rs b/src/utils/random.rs new file mode 100644 index 0000000..d4ffa25 --- /dev/null +++ b/src/utils/random.rs @@ -0,0 +1,8 @@ +use rand::Rng; + +pub fn generate_random_sequence() -> [u8; LEN] { + let mut rng = rand::thread_rng(); + let mut value = [0u8; LEN]; + rng.fill(&mut value[..]); + value +}