use crate::{AuthService, UserResponse};
use axum::{extract::FromRequestParts, http::request::Parts};
use capy_core::AppError;
#[derive(Clone, Debug)]
pub struct AuthUser(pub UserResponse);
#[derive(Clone, Debug)]
pub struct OptionalAuth(pub Option<UserResponse>);
impl<S: Send + Sync> FromRequestParts<S> for OptionalAuth {
type Rejection = AppError;
async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, AppError> {
let service = parts.extensions.get::<AuthService>().ok_or_else(|| {
AppError::Configuration("Install App::auth before using auth extractors.".into())
})?;
Ok(Self(service.identity(&parts.headers).await?))
}
}
impl<S: Send + Sync> FromRequestParts<S> for AuthUser {
type Rejection = AppError;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, AppError> {
let OptionalAuth(user) = OptionalAuth::from_request_parts(parts, state).await?;
user.map(Self).ok_or(AppError::Unauthorized)
}
}