Struggling to clean up error handling.

This commit is contained in:
2026-10-10 17:18:36 +02:00
parent 5f85713892
commit 94b2f23a59
4 changed files with 64 additions and 48 deletions
+17 -6
View File
@@ -13,15 +13,15 @@ pub struct Bearer;
impl AuthScheme for Bearer {
const SCHEME: &'static str = "Bearer";
type Credentials = String;
type Credentials = BearerToken;
type Error = BearerError;
fn credentials(token: &str) -> Result<Self::Credentials, Self::Error> {
Ok(token.to_string())
Ok(BearerToken(token.to_string()))
}
}
impl<S, T> Authorizer<S, T> for Bearer
impl<S> Authorizer<S> for Bearer
where
PgPool: FromRef<S>,
S: Send + Sync,
@@ -29,19 +29,21 @@ where
async fn authorize(
credentials: Self::Credentials,
state: &S,
) -> Result<Principal<T>, Self::Error> {
) -> Result<Principal<Self>, Self::Error> {
let pool = PgPool::from_ref(state);
let token_hash = hash_secret(&credentials);
let token_hash = hash_secret(&credentials.0);
let token = repository::tokens::get_by_access_token_hash(&pool, &token_hash)
.await
.map_err(BearerError::Repository)?
.ok_or(BearerError::InvalidCredentials)?;
Ok(Principal::<T>::new(token.user_id))
Ok(Principal::new(token.user_id))
}
}
pub struct BearerToken(String);
#[derive(Debug, thiserror::Error)]
pub enum BearerError {
#[error("invalid credentials")]
@@ -50,3 +52,12 @@ pub enum BearerError {
#[error(transparent)]
Repository(#[from] RepositoryError),
}
impl crate::error::ClientError for BearerError {
fn client_error_message(&self) -> &'static str {
match self {
BearerError::InvalidCredentials => "Invalid credentials",
BearerError::Repository(_) => "Repository error",
}
}
}