Simplify user token generation

This commit is contained in:
Xiretza 2024-02-10 12:32:49 +00:00
parent 8c478ace92
commit ffd3a95076

View file

@ -3,7 +3,10 @@ use std::sync::Arc;
use base64::{prelude::BASE64_STANDARD, Engine}; use base64::{prelude::BASE64_STANDARD, Engine};
use hmac::{Hmac, Mac}; use hmac::{Hmac, Mac};
use md5::Md5; use md5::Md5;
use rand::{seq::IteratorRandom, thread_rng}; use rand::{
distributions::{Alphanumeric, DistString},
thread_rng,
};
use secrecy::{ExposeSecret, SecretVec}; use secrecy::{ExposeSecret, SecretVec};
use thiserror::Error; use thiserror::Error;
use time::{macros::format_description, OffsetDateTime}; use time::{macros::format_description, OffsetDateTime};
@ -33,22 +36,16 @@ pub struct Authenticator {
} }
impl Authenticator { impl Authenticator {
const USER_TOKEN_LEN: usize = 30;
pub fn new(db: Arc<Mutex<SqliteDatabase>>) -> Self { pub fn new(db: Arc<Mutex<SqliteDatabase>>) -> Self {
Self { db } Self { db }
} }
#[instrument] #[instrument]
pub async fn create_user_token(&mut self, username: &str, password: &Password) -> UserToken { pub async fn create_user_token(&mut self, username: &str, password: &Password) -> UserToken {
let mut token_str = "".to_owned(); let new_token =
UserToken::from(Alphanumeric.sample_string(&mut thread_rng(), Self::USER_TOKEN_LEN));
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 mut db = self.db.lock().await; let mut db = self.db.lock().await;
if let Err(err) = db.save_token(username, &new_token).await { if let Err(err) = db.save_token(username, &new_token).await {