Removed magic values from gen_password. Made generate_password accept constants for the amount the length of the password

This commit is contained in:
StNicolay 2023-06-07 21:35:22 +03:00
parent 5087f8e2c6
commit b0f4d1927a
Signed by: StNicolay
GPG Key ID: 9693D04DCD962B0D
2 changed files with 15 additions and 6 deletions

View File

@ -16,7 +16,7 @@ bitflags::bitflags! {
/// Returns true if the generated master password is valid.
/// It checks that it has at least one lowercase, one uppercase, one number and one punctuation char
#[inline]
fn check_generated_password(password: &[u8; 32]) -> bool {
fn check_generated_password<const LENGTH: usize>(password: &[u8; LENGTH]) -> bool {
let mut flags = PasswordFlags::empty();
for &byte in password {
match byte {
@ -36,12 +36,12 @@ fn check_generated_password(password: &[u8; 32]) -> bool {
}
#[inline]
fn generate_password<R>(rng: &mut R) -> ArrayString<32>
fn generate_password<R, const LENGTH: usize>(rng: &mut R) -> ArrayString<LENGTH>
where
R: Rng + CryptoRng,
{
loop {
let password: [u8; 32] = array::from_fn(|_| *CHARS.choose(rng).unwrap());
let password = array::from_fn(|_| *CHARS.choose(rng).unwrap());
if check_generated_password(&password) {
return ArrayString::from_byte_string(&password).unwrap();
}
@ -50,7 +50,8 @@ where
/// Continuously generates the password until it passes the checks
#[inline]
pub fn generate_passwords() -> [ArrayString<32>; 10] {
pub fn generate_passwords<const AMOUNT: usize, const LENGTH: usize>(
) -> [ArrayString<LENGTH>; AMOUNT] {
let mut rng = thread_rng();
array::from_fn(|_| generate_password(&mut rng))
}

View File

@ -5,10 +5,18 @@ use std::fmt::Write;
use teloxide::{adaptors::Throttle, prelude::*, types::ParseMode};
use tokio::task::spawn_blocking;
const MESSAGE_HEADER: &str = "Passwords:";
const PASSWORD_LENGTH: usize = 32;
const PASSWORD_PADDING_LENGTH: usize = 3;
const AMOUNT_OF_PASSWORDS: usize = 10;
type PasswordArray = [ArrayString<PASSWORD_LENGTH>; AMOUNT_OF_PASSWORDS];
const BUFFER_LENGTH: usize =
MESSAGE_HEADER.len() + (PASSWORD_LENGTH + PASSWORD_PADDING_LENGTH) * AMOUNT_OF_PASSWORDS;
/// Handles /gen_password command by generating 10 copyable passwords and sending them to the user
pub async fn gen_password(bot: Throttle<Bot>, msg: Message) -> crate::Result<()> {
let mut message: ArrayString<{ 10 + 35 * 10 }> = "Passwords:".try_into().unwrap();
let passwords = spawn_blocking(generate_passwords).await?;
let mut message: ArrayString<BUFFER_LENGTH> = MESSAGE_HEADER.try_into().unwrap();
let passwords: PasswordArray = spawn_blocking(generate_passwords).await?;
for password in passwords {
write!(message, "\n`{password}`").unwrap();
}