Added an authorization header bearer token extraction demo.

This commit is contained in:
2026-10-09 16:46:28 +02:00
parent 18e142ec91
commit 7fb3abc93d
6 changed files with 236 additions and 1 deletions
+68
View File
@@ -0,0 +1,68 @@
use axum::{
RequestPartsExt,
extract::{FromRef, FromRequestParts},
http::HeaderMap,
};
use sqlx::PgPool;
use uuid::Uuid;
use crate::{crypto::hash_secret, error::AppError, repository};
#[derive(Debug)]
pub struct Auth(pub Authorization);
impl<S> FromRequestParts<S> for Auth
where
PgPool: FromRef<S>,
S: Send + Sync,
{
type Rejection = AppError;
async fn from_request_parts(
parts: &mut axum::http::request::Parts,
state: &S,
) -> Result<Self, Self::Rejection> {
let pool = PgPool::from_ref(state);
let headers = parts.extract::<HeaderMap>().await.map_err(|e| {
tracing::error!("Failed to extract headers: {:?}", e);
AppError::Internal
})?;
let token_hash = headers
.get(axum::http::header::AUTHORIZATION)
.and_then(|h| h.to_str().ok())
.and_then(|h| h.split_once(' '))
.filter(|(scheme, _)| scheme.eq_ignore_ascii_case("Bearer"))
.map(|(_, token)| token.trim())
.filter(|token| !token.is_empty())
.map(hash_secret)
.ok_or(AppError::Unauthorized)?;
let token = repository::tokens::get_by_access_token_hash(&pool, &token_hash)
.await
.map_err(|_| AppError::Internal)?
.ok_or(AppError::Unauthorized)?;
Ok(Auth(Authorization {
user_id: token.id,
app_id: None,
}))
}
}
#[derive(Debug)]
pub struct Authorization {
user_id: Uuid,
app_id: Option<Uuid>,
}
impl Authorization {
pub fn user_id(&self) -> Uuid {
self.user_id
}
pub fn app_id(&self) -> Option<Uuid> {
self.app_id
}
}