Over engineered bearer token extraction (although it's not perfect yet).

This commit is contained in:
2026-10-10 12:15:00 +02:00
parent 1655becf39
commit 30efddbc20
6 changed files with 320 additions and 130 deletions
@@ -0,0 +1,52 @@
use axum::extract::FromRef;
use sqlx::PgPool;
use super::{AuthScheme, Authorizer};
use crate::{
crypto::hash_secret,
repository::{self, RepositoryError},
};
#[derive(Debug)]
pub struct Bearer;
impl AuthScheme for Bearer {
const SCHEME: &'static str = "Bearer";
type Credentials = String;
type Error = BearerError;
fn credentials(token: &str) -> Result<Self::Credentials, Self::Error> {
Ok(token.to_string())
}
}
impl<S> Authorizer<S> for Bearer
where
PgPool: FromRef<S>,
S: Send + Sync,
{
async fn authorize(
credentials: Self::Credentials,
state: &S,
) -> Result<crate::domain::Authorization, Self::Error> {
let pool = PgPool::from_ref(state);
let token_hash = hash_secret(&credentials);
let token = repository::tokens::get_by_access_token_hash(&pool, &token_hash)
.await
.map_err(|error| BearerError::Repository(error))?
.ok_or(BearerError::InvalidCredentials)?;
Ok(crate::domain::Authorization::new(token.user_id))
}
}
#[derive(Debug, thiserror::Error)]
pub enum BearerError {
#[error("invalid credentials")]
InvalidCredentials,
#[error(transparent)]
Repository(#[from] RepositoryError),
}