1use crate::{AuthService, UserResponse};
2use axum::{extract::FromRequestParts, http::request::Parts};
3use capy_core::AppError;
4
5#[derive(Clone, Debug)]
7pub struct AuthUser(pub UserResponse);
8#[derive(Clone, Debug)]
11pub struct OptionalAuth(pub Option<UserResponse>);
12impl<S: Send + Sync> FromRequestParts<S> for OptionalAuth {
13 type Rejection = AppError;
14 async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, AppError> {
15 let service = parts.extensions.get::<AuthService>().ok_or_else(|| {
16 AppError::Configuration("Install App::auth before using auth extractors.".into())
17 })?;
18 Ok(Self(service.identity(&parts.headers).await?))
19 }
20}
21impl<S: Send + Sync> FromRequestParts<S> for AuthUser {
22 type Rejection = AppError;
23 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, AppError> {
24 let OptionalAuth(user) = OptionalAuth::from_request_parts(parts, state).await?;
25 user.map(Self).ok_or(AppError::Unauthorized)
26 }
27}