From ffd3a95076684f9358d9ad58407df9a654781380 Mon Sep 17 00:00:00 2001 From: Xiretza Date: Sat, 10 Feb 2024 12:32:49 +0000 Subject: [PATCH] Simplify user token generation --- src/auth.rs | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/auth.rs b/src/auth.rs index 9982ef4..25f06b2 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -3,7 +3,10 @@ use std::sync::Arc; use base64::{prelude::BASE64_STANDARD, Engine}; use hmac::{Hmac, Mac}; use md5::Md5; -use rand::{seq::IteratorRandom, thread_rng}; +use rand::{ + distributions::{Alphanumeric, DistString}, + thread_rng, +}; use secrecy::{ExposeSecret, SecretVec}; use thiserror::Error; use time::{macros::format_description, OffsetDateTime}; @@ -33,22 +36,16 @@ pub struct Authenticator { } impl Authenticator { + const USER_TOKEN_LEN: usize = 30; + pub fn new(db: Arc>) -> Self { Self { db } } #[instrument] pub async fn create_user_token(&mut self, username: &str, password: &Password) -> UserToken { - let mut token_str = "".to_owned(); - - let mut rng = thread_rng(); - for _ in 0..30 { - let digit = (0..=15).choose(&mut rng).unwrap(); - let char = (('a' as u8) + digit) as char; - token_str.push(char) - } - - let new_token = UserToken::from(token_str); + let new_token = + UserToken::from(Alphanumeric.sample_string(&mut thread_rng(), Self::USER_TOKEN_LEN)); let mut db = self.db.lock().await; if let Err(err) = db.save_token(username, &new_token).await {