use axum::{extract::FromRequestParts, response::IntoResponse}; mod bearer; mod header; mod principal; pub use bearer::*; pub use header::*; pub use principal::*; use super::ExtractorError; use crate::repository::RepositoryError; #[derive(Debug)] pub struct Auth(pub Principal); impl FromRequestParts for Auth where T: 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(T::SCHEME) { return Err(AuthError::UnsupportedScheme); } let credentials = T::credentials(header.token()).map_err(Into::::into)?; let authorization = T::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), #[error(transparent)] Repository(#[from] RepositoryError), } impl IntoResponse for AuthError { fn into_response(self) -> axum::response::Response { ExtractorError::from(self).into_response() } } trait AuthScheme { const SCHEME: &'static str; type Credentials: Send; type Error: Into; fn credentials(token: &str) -> Result; } trait Authorizer: AuthScheme + Sized { fn authorize( credentials: Self::Credentials, state: &S, ) -> impl Future, Self::Error>> + Send; }