use axum::{extract::FromRequestParts, response::IntoResponse}; mod bearer; mod header; pub use bearer::*; pub use header::*; use crate::{domain::Authorization, error::AppError}; #[derive(Debug)] pub struct Auth(pub Authorization); impl FromRequestParts for Auth where Bearer: AuthScheme + Authorizer, S: Send + Sync, { type Rejection = AuthError; async fn from_request_parts( parts: &mut axum::http::request::Parts, state: &S, ) -> Result { let header = AuthHeader::from_request_parts(parts, state).await?; if !header.scheme().eq_ignore_ascii_case(Bearer::SCHEME) { return Err(AuthError::UnsupportedScheme); } let credentials = Bearer::credentials(header.token()).map_err(Into::::into)?; let authorization = Bearer::authorize(credentials, state) .await .map_err(Into::::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), } impl From for AppError { fn from(err: AuthError) -> Self { match err { AuthError::UnsupportedScheme => { AppError::Unauthorized("Unsupported authorization scheme".into()) } AuthError::Header(AuthHeaderError::Missing) => { AppError::Unauthorized("Missing authorization header".into()) } AuthError::Header(AuthHeaderError::NotAscii(_)) => { AppError::Unauthorized("Invalid authorization header encoding".into()) } AuthError::Header(AuthHeaderError::MalformedValue) => { AppError::Unauthorized("Malformed authorization header".into()) } AuthError::Header(AuthHeaderError::EmptyScheme) => { AppError::Unauthorized("Empty authorization scheme".into()) } AuthError::Header(AuthHeaderError::EmptyToken) => { AppError::Unauthorized("Empty token value".into()) } AuthError::Bearer(BearerError::InvalidCredentials) => { AppError::Unauthorized("Unauthorized".into()) } AuthError::Bearer(BearerError::Repository(error)) => error.into(), } } } 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; fn credentials(token: &str) -> Result; } trait Authorizer: AuthScheme { fn authorize( credentials: Self::Credentials, state: &S, ) -> impl Future> + Send; }