Added an authorization header bearer token extraction demo.
This commit is contained in:
@@ -2,6 +2,31 @@ use chrono::{DateTime, Utc};
|
||||
|
||||
use super::{DatabaseError, dtos::TokenRow};
|
||||
|
||||
pub async fn get_by_access_token_hash<'e, E>(
|
||||
executor: E,
|
||||
access_token_hash: &[u8],
|
||||
) -> Result<Option<TokenRow>, DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let row = sqlx::query_as!(
|
||||
TokenRow,
|
||||
r#"
|
||||
SELECT *
|
||||
FROM tokens
|
||||
WHERE access_token_hash = $1
|
||||
AND access_expires_at > now()
|
||||
AND revoked_at IS NULL
|
||||
"#,
|
||||
access_token_hash,
|
||||
)
|
||||
.fetch_optional(executor)
|
||||
.await
|
||||
.map_err(DatabaseError::from)?;
|
||||
|
||||
Ok(row)
|
||||
}
|
||||
|
||||
pub async fn issue<'e, E>(executor: E, token: TokenRow) -> Result<(), DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
|
||||
@@ -6,6 +6,21 @@ use crate::{
|
||||
domain::Token,
|
||||
};
|
||||
|
||||
pub async fn get_by_access_token_hash<'e, E>(
|
||||
executor: E,
|
||||
access_token_hash: &[u8],
|
||||
) -> Result<Option<Token>, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let token = db::get_by_access_token_hash(executor, access_token_hash)
|
||||
.await?
|
||||
.map(decode)
|
||||
.transpose()?;
|
||||
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
pub async fn issue<'e, E>(executor: E, token: Token) -> Result<(), RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
@@ -42,6 +57,19 @@ where
|
||||
Ok(db::revoke(executor, token_hash).await?)
|
||||
}
|
||||
|
||||
fn decode(token: TokenRow) -> Result<Token, RepositoryError> {
|
||||
Ok(Token {
|
||||
id: token.id,
|
||||
access_token_hash: token.access_token_hash,
|
||||
refresh_token_hash: token.refresh_token_hash,
|
||||
access_expires_at: token.access_expires_at,
|
||||
refresh_expires_at: token.refresh_expires_at,
|
||||
refreshed_at: token.refreshed_at,
|
||||
revoked_at: token.revoked_at,
|
||||
created_at: token.created_at,
|
||||
})
|
||||
}
|
||||
|
||||
fn encode(token: Token) -> TokenRow {
|
||||
TokenRow {
|
||||
id: token.id,
|
||||
|
||||
@@ -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