From 731f6f2f6ca60c276b61178fdd7fa452c0ed05c4 Mon Sep 17 00:00:00 2001 From: DenebTM Date: Sun, 11 Feb 2024 19:12:51 +0100 Subject: [PATCH] bugfix: return existing token instead of creating a new one every time --- src/auth/mod.rs | 22 ++++++++++++++++------ src/server.rs | 2 +- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/auth/mod.rs b/src/auth/mod.rs index befbbb1..8683ec1 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -84,7 +84,7 @@ impl UserAuthenticator { } #[instrument] - pub async fn create_user_token( + pub async fn get_user_token( &self, username: &str, password: &Password, @@ -108,13 +108,23 @@ impl UserAuthenticator { return Err(AuthenticationError::InvalidUserOrPassword); }; - let new_token = - UserToken::from(Alphanumeric.sample_string(&mut thread_rng(), Self::TOKEN_LEN)); - + // if a valid token exists, return it; if not, create a new one let mut db = self.db.lock().await; - db.save_token(&username, &new_token).await?; + let token = + if let Some(UserTokenEntry::Valid(old_token, _, _)) = db.get_token(&username).await? { + // TODO: update old_token's last_used value - Ok((username, new_token)) + old_token + } else { + let new_token = + UserToken::from(Alphanumeric.sample_string(&mut thread_rng(), Self::TOKEN_LEN)); + + db.save_token(&username, &new_token).await?; + + new_token + }; + + Ok((username, token)) } #[instrument] diff --git a/src/server.rs b/src/server.rs index 18ed908..960aa3c 100644 --- a/src/server.rs +++ b/src/server.rs @@ -114,7 +114,7 @@ async fn api_login( event!(Level::INFO, "Generating user key"); let (username, user_token) = user_authenticator - .create_user_token(&username, &password) + .get_user_token(&username, &password) .await?; Ok(Json(LoginResponse {