Now creating password on 1 blocking task because the generation doesn't take that long, removed back slash from the password chars

This commit is contained in:
StNicolay 2023-05-12 20:29:44 +03:00
parent 522194c708
commit 0b92bcd9f3
Signed by: StNicolay
GPG Key ID: 9693D04DCD962B0D

View File

@ -1,11 +1,11 @@
use crate::handlers::markups::deletion_markup;
use arrayvec::{ArrayString, ArrayVec};
use rand::{rngs::OsRng, seq::SliceRandom};
use std::{iter, str::from_utf8_unchecked};
use std::str::from_utf8_unchecked;
use teloxide::{adaptors::Throttle, prelude::*, types::ParseMode};
use tokio::task::JoinSet;
use tokio::task::spawn_blocking;
const CHARS: &[u8] = br##"!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~"##;
const CHARS: &[u8] = br##"!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~"##;
/// Returns true if the generated master password is valid.
/// It checks that it has at least one lowercase, one lowercase and one punctuation char
@ -28,32 +28,30 @@ fn check_generated_password(password: &[u8]) -> bool {
}
/// Continuously generates the password until it passes the checks
fn generete_password() -> ArrayString<34> {
loop {
let password: ArrayVec<u8, 32> = iter::repeat_with(|| *CHARS.choose(&mut OsRng).unwrap())
.take(32)
fn generete_passwords() -> ArrayVec<ArrayString<34>, 10> {
let mut passwords = ArrayVec::new_const();
while !passwords.is_full() {
let password: ArrayVec<u8, 32> = (0..32)
.map(|_| *CHARS.choose(&mut OsRng).unwrap())
.collect();
if check_generated_password(&password) {
let mut string = ArrayString::<34>::new_const();
string.push('`');
unsafe { string.push_str(from_utf8_unchecked(&password)) };
string.push('`');
return string;
passwords.push(string)
}
}
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::<{ 11 + 35 * 10 }>::new();
message.push_str("Passwords:\n");
let mut join_set = JoinSet::new();
for _ in 0..10 {
join_set.spawn_blocking(generete_password);
}
while let Some(password) = join_set.join_next().await {
message.push_str(password?.as_str());
message.push('\n')
let mut message: ArrayString<{ 10 + 35 * 10 }> = "Passwords:".try_into().unwrap();
let passwords = spawn_blocking(|| generete_passwords()).await?;
for password in passwords {
message.push('\n');
message.push_str(&password)
}
bot.send_message(msg.chat.id, message.as_str())
.parse_mode(ParseMode::MarkdownV2)