capy-auth 0.10.0

Optional database-backed browser sessions and explicit authorization for Capy.
Documentation
use crate::{AuthService, UserResponse};
use axum::{extract::FromRequestParts, http::request::Parts};
use capy_core::AppError;

/// Required authenticated identity. Invalid, expired, deleted, or absent identities return 401.
#[derive(Clone, Debug)]
pub struct AuthUser(pub UserResponse);
/// Optional identity. Only an absent cookie or valid anonymous CSRF session yields None.
/// Malformed, unknown, expired, or deleted-user sessions still return 401.
#[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)
    }
}