Added an authorization header bearer token extraction demo.
This commit is contained in:
@@ -5,7 +5,7 @@ use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
dtos::account::{AccountRequest, AccountResponse},
|
||||
extractors::{json::Json, path::Path, query::Query},
|
||||
extractors::{auth::Auth, json::Json, path::Path, query::Query},
|
||||
};
|
||||
use crate::{
|
||||
error::AppError,
|
||||
@@ -33,6 +33,7 @@ pub struct QueryParams {
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn list_accounts(
|
||||
Auth(auth): Auth,
|
||||
State(pool): State<PgPool>,
|
||||
Query(query): Query<QueryParams>,
|
||||
) -> Result<Json<Vec<AccountResponse>>, AppError> {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod auth;
|
||||
pub mod form;
|
||||
pub mod json;
|
||||
pub mod path;
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user