mirror of
https://github.com/tokio-rs/axum.git
synced 2026-08-27 00:00:24 +02:00
Add a separate trait for optional extractors (#2475)
This commit is contained in:
@@ -11,7 +11,7 @@
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use async_session::{MemoryStore, Session, SessionStore};
|
||||
use axum::{
|
||||
extract::{FromRef, FromRequestParts, Query, State},
|
||||
extract::{FromRef, FromRequestParts, OptionalFromRequestParts, Query, State},
|
||||
http::{header::SET_COOKIE, HeaderMap},
|
||||
response::{IntoResponse, Redirect, Response},
|
||||
routing::get,
|
||||
@@ -24,7 +24,7 @@ use oauth2::{
|
||||
ClientSecret, CsrfToken, RedirectUrl, Scope, TokenResponse, TokenUrl,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::env;
|
||||
use std::{convert::Infallible, env};
|
||||
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
||||
|
||||
static COOKIE_NAME: &str = "SESSION";
|
||||
@@ -351,6 +351,24 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> OptionalFromRequestParts<S> for User
|
||||
where
|
||||
MemoryStore: FromRef<S>,
|
||||
S: Send + Sync,
|
||||
{
|
||||
type Rejection = Infallible;
|
||||
|
||||
async fn from_request_parts(
|
||||
parts: &mut Parts,
|
||||
state: &S,
|
||||
) -> Result<Option<Self>, Self::Rejection> {
|
||||
match <User as FromRequestParts<S>>::from_request_parts(parts, state).await {
|
||||
Ok(res) => Ok(Some(res)),
|
||||
Err(AuthRedirect) => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Use anyhow, define error and enable '?'
|
||||
// For a simplified example of using anyhow in axum check /examples/anyhow-error-response
|
||||
#[derive(Debug)]
|
||||
|
||||
Reference in New Issue
Block a user