bugfix: return existing token instead of creating a new one every time
This commit is contained in:
parent
5c747f2b41
commit
731f6f2f6c
2 changed files with 17 additions and 7 deletions
|
@ -84,7 +84,7 @@ impl UserAuthenticator {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[instrument]
|
#[instrument]
|
||||||
pub async fn create_user_token(
|
pub async fn get_user_token(
|
||||||
&self,
|
&self,
|
||||||
username: &str,
|
username: &str,
|
||||||
password: &Password,
|
password: &Password,
|
||||||
|
@ -108,13 +108,23 @@ impl UserAuthenticator {
|
||||||
return Err(AuthenticationError::InvalidUserOrPassword);
|
return Err(AuthenticationError::InvalidUserOrPassword);
|
||||||
};
|
};
|
||||||
|
|
||||||
let new_token =
|
// if a valid token exists, return it; if not, create a new one
|
||||||
UserToken::from(Alphanumeric.sample_string(&mut thread_rng(), Self::TOKEN_LEN));
|
|
||||||
|
|
||||||
let mut db = self.db.lock().await;
|
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]
|
#[instrument]
|
||||||
|
|
|
@ -114,7 +114,7 @@ async fn api_login(
|
||||||
event!(Level::INFO, "Generating user key");
|
event!(Level::INFO, "Generating user key");
|
||||||
|
|
||||||
let (username, user_token) = user_authenticator
|
let (username, user_token) = user_authenticator
|
||||||
.create_user_token(&username, &password)
|
.get_user_token(&username, &password)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(Json(LoginResponse {
|
Ok(Json(LoginResponse {
|
||||||
|
|
Loading…
Reference in a new issue