Simplify user token generation
This commit is contained in:
parent
8c478ace92
commit
ffd3a95076
1 changed files with 8 additions and 11 deletions
19
src/auth.rs
19
src/auth.rs
|
@ -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 {
|
||||||
|
|
Loading…
Reference in a new issue