From 0d07af7d79efb38bb68a7a62371269b9378d9e32 Mon Sep 17 00:00:00 2001 From: Radical Date: Fri, 2 May 2025 19:26:37 +0200 Subject: [PATCH] feat: style: return unauthorized when token isnt found and flatten function structure --- src/api/v1/auth/mod.rs | 44 ++++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/src/api/v1/auth/mod.rs b/src/api/v1/auth/mod.rs index 469ccc2..ff74c6b 100644 --- a/src/api/v1/auth/mod.rs +++ b/src/api/v1/auth/mod.rs @@ -37,32 +37,34 @@ pub async fn check_access_token( access_token: String, pool: &sqlx::Pool, ) -> Result { - match sqlx::query_as( + let row = sqlx::query_as( "SELECT CAST(uuid as VARCHAR), created FROM access_tokens WHERE token = $1", ) .bind(&access_token) .fetch_one(pool) - .await - { - Ok(row) => { - let (uuid, created): (String, i64) = row; + .await; - let current_time = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_secs() as i64; - - let lifetime = current_time - created; - - if lifetime > 3600 { - return Err(HttpResponse::Unauthorized().finish()); - } - - Ok(Uuid::from_str(&uuid).unwrap()) - } - Err(error) => { - error!("{}", error); - Err(HttpResponse::InternalServerError().finish()) + if let Err(error) = row { + if error.to_string() == "no rows returned by a query that expected to return at least one row" { + return Err(HttpResponse::Unauthorized().finish()) } + + error!("{}", error); + return Err(HttpResponse::InternalServerError().json(r#"{ "error": "Unhandled exception occured, contact the server administrator" }"#)) } + + let (uuid, created): (String, i64) = row.unwrap(); + + let current_time = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs() as i64; + + let lifetime = current_time - created; + + if lifetime > 3600 { + return Err(HttpResponse::Unauthorized().finish()); + } + + Ok(Uuid::from_str(&uuid).unwrap()) }