101 lines
2.9 KiB
Rust
101 lines
2.9 KiB
Rust
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<S> FromRequestParts<S> for Auth
|
|
where
|
|
Bearer: 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(Bearer::SCHEME) {
|
|
return Err(AuthError::UnsupportedScheme);
|
|
}
|
|
|
|
let credentials = Bearer::credentials(header.token()).map_err(Into::<AuthError>::into)?;
|
|
let authorization = Bearer::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),
|
|
}
|
|
|
|
impl From<AuthError> 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<AuthError>;
|
|
|
|
fn credentials(token: &str) -> Result<Self::Credentials, Self::Error>;
|
|
}
|
|
|
|
trait Authorizer<S>: AuthScheme {
|
|
fn authorize(
|
|
credentials: Self::Credentials,
|
|
state: &S,
|
|
) -> impl Future<Output = Result<Authorization, Self::Error>> + Send;
|
|
}
|