Skip to main content

capy_auth/
extract.rs

1use crate::{AuthService, UserResponse};
2use axum::{extract::FromRequestParts, http::request::Parts};
3use capy_core::AppError;
4
5/// Required authenticated identity. Invalid, expired, deleted, or absent identities return 401.
6#[derive(Clone, Debug)]
7pub struct AuthUser(pub UserResponse);
8/// Optional identity. Only an absent cookie or valid anonymous CSRF session yields None.
9/// Malformed, unknown, expired, or deleted-user sessions still return 401.
10#[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}