Add sync constructors to CookieJar, SignedCookieJar, and PrivateCookieJar (#1264)

* Add sync constructors to `CookieJar`, `SignedCookieJar`, and `PrivateCookieJar`

* Move to constructor

* use `RequestParts::extract`
This commit is contained in:
David Pedersen
2022-08-16 15:42:01 +02:00
committed by GitHub
parent fb32fcc07c
commit 01630cfef6
4 changed files with 105 additions and 18 deletions
+37 -4
View File
@@ -6,6 +6,7 @@ use axum::{
Extension,
};
use cookie::PrivateJar;
use http::HeaderMap;
use std::{convert::Infallible, fmt, marker::PhantomData};
/// Extractor that grabs private cookies from the request and manages the jar.
@@ -82,21 +83,53 @@ where
type Rejection = <axum::Extension<K> as FromRequest<B>>::Rejection;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let key = Extension::<K>::from_request(req).await?.0.into();
let key = req.extract::<Extension<K>>().await?.0.into();
let PrivateCookieJar {
jar,
key,
_marker: _,
} = PrivateCookieJar::from_headers(req.headers(), key);
Ok(PrivateCookieJar {
jar,
key,
_marker: PhantomData,
})
}
}
impl PrivateCookieJar {
/// Create a new `PrivateCookieJar` from a map of request headers.
///
/// The valid cookies in `headers` will be added to the jar.
///
/// This is inteded to be used in middleware and other where places it might be difficult to
/// run extractors. Normally you should create `PrivateCookieJar`s through [`FromRequest`].
pub fn from_headers(headers: &HeaderMap, key: Key) -> Self {
let mut jar = cookie::CookieJar::new();
let mut private_jar = jar.private_mut(&key);
for cookie in cookies_from_request(req) {
for cookie in cookies_from_request(headers) {
if let Some(cookie) = private_jar.decrypt(cookie) {
private_jar.add_original(cookie);
}
}
Ok(Self {
Self {
jar,
key,
_marker: PhantomData,
})
}
}
/// Create a new empty `PrivateCookieJarIter`.
///
/// This is inteded to be used in middleware and other places where it might be difficult to
/// run extractors. Normally you should create `PrivateCookieJar`s through [`FromRequest`].
pub fn new(key: Key) -> Self {
Self {
jar: Default::default(),
key,
_marker: PhantomData,
}
}
}