Files
expenses/server/src/routes/extractors/auth.rs
T

77 lines
1.8 KiB
Rust

use axum::{extract::FromRequestParts, response::IntoResponse};
mod bearer;
mod header;
mod principal;
pub use bearer::*;
pub use header::*;
pub use principal::*;
use crate::{error::AppError, repository::RepositoryError};
#[derive(Debug)]
pub struct Auth<T = Bearer>(pub Principal<T>);
impl<T, S> FromRequestParts<S> for Auth<T>
where
T: AuthScheme + Authorizer<S>,
S: Send + Sync,
{
type Rejection = AuthError;
async fn from_request_parts(
parts: &mut axum::http::request::Parts,
state: &S,
) -> Result<Self, Self::Rejection> {
let header = AuthHeader::from_request_parts(parts, state).await?;
if !header.scheme().eq_ignore_ascii_case(T::SCHEME) {
return Err(AuthError::UnsupportedScheme);
}
let credentials = T::credentials(header.token()).map_err(Into::<AuthError>::into)?;
let authorization = T::authorize(credentials, state)
.await
.map_err(Into::<AuthError>::into)?;
Ok(Self(authorization))
}
}
#[derive(Debug, thiserror::Error)]
pub enum AuthError {
#[error("unsupported scheme")]
UnsupportedScheme,
#[error(transparent)]
Header(#[from] AuthHeaderError),
#[error(transparent)]
Bearer(#[from] BearerError),
#[error(transparent)]
Repository(#[from] RepositoryError),
}
impl IntoResponse for AuthError {
fn into_response(self) -> axum::response::Response {
AppError::from(self).into_response()
}
}
trait AuthScheme {
const SCHEME: &'static str;
type Credentials: Send;
type Error: Into<AuthError>;
fn credentials(token: &str) -> Result<Self::Credentials, Self::Error>;
}
trait Authorizer<S>: AuthScheme + Sized {
fn authorize(
credentials: Self::Credentials,
state: &S,
) -> impl Future<Output = Result<Principal<Self>, Self::Error>> + Send;
}