Skip to main content

axum_oidc_client/extractors/
auth_session_extractor.rs

1use axum::{
2    extract::FromRequestParts,
3    http::request::Parts,
4    response::{IntoResponse, Response},
5};
6use futures_util::future::BoxFuture;
7use std::ops::Deref;
8
9use super::shared::extract_auth_session;
10use crate::auth_session::AuthSession;
11
12impl<S> FromRequestParts<S> for AuthSession
13where
14    S: Send + Sync,
15{
16    type Rejection = Response;
17
18    #[allow(refining_impl_trait)]
19    fn from_request_parts<'a>(
20        parts: &'a mut Parts,
21        _state: &S,
22    ) -> BoxFuture<'a, Result<Self, Self::Rejection>> {
23        Box::pin(async move {
24            extract_auth_session(parts)
25                .await
26                .map_err(IntoResponse::into_response)
27        })
28    }
29}
30
31/// Optional extractor for AuthSession that can be used in route handlers
32/// This extracts the authenticated user's session if present,
33/// returning None if the user is not authenticated
34pub struct OptionalAuthSession(pub Option<AuthSession>);
35
36impl Deref for OptionalAuthSession {
37    type Target = Option<AuthSession>;
38
39    fn deref(&self) -> &Self::Target {
40        &self.0
41    }
42}
43
44impl<S> FromRequestParts<S> for OptionalAuthSession
45where
46    S: Send + Sync,
47{
48    type Rejection = std::convert::Infallible;
49
50    #[allow(refining_impl_trait)]
51    fn from_request_parts<'a>(
52        parts: &'a mut Parts,
53        _state: &S,
54    ) -> BoxFuture<'a, Result<Self, Self::Rejection>> {
55        Box::pin(async move {
56            let session = extract_auth_session(parts).await.ok();
57            Ok(OptionalAuthSession(session))
58        })
59    }
60}