From cce6662d635bb2115f9f2a7bab92cc105166e761 Mon Sep 17 00:00:00 2001 From: Owen Jacobson Date: Wed, 18 Sep 2024 01:27:47 -0400 Subject: App methods now return errors that allow not-found cases to be distinguished. --- src/repo/error.rs | 23 +++++++++++++++++++++++ src/repo/login/extract.rs | 15 +++++++++++---- src/repo/mod.rs | 1 + src/repo/token.rs | 4 ++-- 4 files changed, 37 insertions(+), 6 deletions(-) create mode 100644 src/repo/error.rs (limited to 'src/repo') diff --git a/src/repo/error.rs b/src/repo/error.rs new file mode 100644 index 0000000..a5961e2 --- /dev/null +++ b/src/repo/error.rs @@ -0,0 +1,23 @@ +pub trait NotFound { + type Ok; + fn not_found(self, map: F) -> Result + where + E: From, + F: FnOnce() -> E; +} + +impl NotFound for Result { + type Ok = T; + + fn not_found(self, map: F) -> Result + where + E: From, + F: FnOnce() -> E, + { + match self { + Err(sqlx::Error::RowNotFound) => Err(map()), + Err(other) => Err(other.into()), + Ok(value) => Ok(value), + } + } +} diff --git a/src/repo/login/extract.rs b/src/repo/login/extract.rs index a068bc0..a45a1cd 100644 --- a/src/repo/login/extract.rs +++ b/src/repo/login/extract.rs @@ -5,7 +5,12 @@ use axum::{ }; use super::Login; -use crate::{app::App, clock::RequestedAt, error::InternalError, login::extract::IdentityToken}; +use crate::{ + app::App, + clock::RequestedAt, + error::InternalError, + login::{app::ValidateError, extract::IdentityToken}, +}; #[async_trait::async_trait] impl FromRequestParts for Login { @@ -22,9 +27,11 @@ impl FromRequestParts for Login { let secret = identity_token.secret().ok_or(LoginError::Unauthorized)?; let app = State::::from_request_parts(parts, state).await?; - let login = app.logins().validate(secret, used_at).await?; - - login.ok_or(LoginError::Unauthorized) + match app.logins().validate(secret, used_at).await { + Ok(login) => Ok(login), + Err(ValidateError::InvalidToken) => Err(LoginError::Unauthorized), + Err(other) => Err(other.into()), + } } } diff --git a/src/repo/mod.rs b/src/repo/mod.rs index d8995a3..f36f0da 100644 --- a/src/repo/mod.rs +++ b/src/repo/mod.rs @@ -1,4 +1,5 @@ pub mod channel; +pub mod error; pub mod login; pub mod message; pub mod token; diff --git a/src/repo/token.rs b/src/repo/token.rs index 01a982e..5674c92 100644 --- a/src/repo/token.rs +++ b/src/repo/token.rs @@ -88,7 +88,7 @@ impl<'c> Tokens<'c> { &mut self, secret: &str, used_at: DateTime, - ) -> Result, sqlx::Error> { + ) -> Result { // I would use `update … returning` to do this in one query, but // sqlite3, as of this writing, does not allow an update's `returning` // clause to reference columns from tables joined into the update. Two @@ -117,7 +117,7 @@ impl<'c> Tokens<'c> { "#, secret, ) - .fetch_optional(&mut *self.0) + .fetch_one(&mut *self.0) .await?; Ok(login) -- cgit v1.2.3