From 51865c365c8509437c602df6cb034332ddb80844 Mon Sep 17 00:00:00 2001 From: DenebTM Date: Sat, 10 Feb 2024 13:39:10 +0100 Subject: [PATCH] distinguish invalid token from database error --- src/auth.rs | 8 ++++---- src/db.rs | 11 +++++------ 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/auth.rs b/src/auth.rs index 7e18575..318beff 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -63,10 +63,10 @@ impl UserAuthenticator { ) -> Result<(), AuthenticationError> { let mut db = self.db.lock().await; - // TODO: (in db) distinguish between invalid token and SQLX error - db.get_token(username).await?; - - Ok(()) + match db.get_token(username).await? { + Some(_) => Ok(()), + None => Err(AuthenticationError::InvalidToken), + } } } diff --git a/src/db.rs b/src/db.rs index f284d87..fbc222b 100644 --- a/src/db.rs +++ b/src/db.rs @@ -11,7 +11,7 @@ const DB_URI_DEFAULT: &str = "sqlite://sqlite.db"; const TABLE_USER_TOKENS: &str = "user_tokens"; pub trait Database { - async fn get_token(&mut self, username: &str) -> Result; + async fn get_token(&mut self, username: &str) -> Result, sqlx::Error>; async fn save_token(&mut self, username: &str, token: &UserToken) -> Result<(), sqlx::Error>; } @@ -56,9 +56,8 @@ impl SqliteDatabase { } impl Database for SqliteDatabase { - // TODO: distinguish between invalid token and SQLX error - async fn get_token(&mut self, username: &str) -> Result { - let row: (String,) = query_as( + async fn get_token(&mut self, username: &str) -> Result, sqlx::Error> { + let row: Option<(String,)> = query_as( "SELECT token FROM user_tokens WHERE @@ -68,10 +67,10 @@ impl Database for SqliteDatabase { created DESC", ) .bind(username) - .fetch_one(&mut self.conn) + .fetch_optional(&mut self.conn) .await?; - Ok(UserToken::from(row.0)) + Ok(row.map(|(token_str, ..)| UserToken::from(token_str))) } async fn save_token(&mut self, username: &str, token: &UserToken) -> Result<(), sqlx::Error> {