use std::sync::{Arc, Mutex, MutexGuard};
use cookie::CookieJar;
use http::HeaderMap;
use http::header::{COOKIE, SET_COOKIE};
pub use cookie::{Cookie, Key, SameSite};
#[derive(Clone)]
pub struct Cookies {
jar: Arc<Mutex<CookieJar>>,
key: Arc<Key>,
}
impl Cookies {
pub(crate) fn from_headers(headers: &HeaderMap, key: Arc<Key>) -> Self {
let mut jar = CookieJar::new();
for value in headers.get_all(COOKIE) {
let Ok(value) = value.to_str() else { continue };
for cookie in Cookie::split_parse_encoded(value.to_owned()).flatten() {
jar.add_original(cookie.into_owned());
}
}
Self {
jar: Arc::new(Mutex::new(jar)),
key,
}
}
fn jar(&self) -> MutexGuard<'_, CookieJar> {
self.jar.lock().unwrap_or_else(|e| e.into_inner())
}
pub fn get(&self, name: &str) -> Option<String> {
self.jar().get(name).map(|c| c.value().to_owned())
}
pub fn add(&self, cookie: impl Into<Cookie<'static>>) {
self.jar().add(with_defaults(cookie.into()));
}
pub fn remove(&self, name: &str) {
self.jar().remove(removal(name));
}
pub fn get_signed(&self, name: &str) -> Option<String> {
self.jar()
.signed(&self.key)
.get(name)
.map(|c| c.value().to_owned())
}
pub fn add_signed(&self, cookie: impl Into<Cookie<'static>>) {
self.jar()
.signed_mut(&self.key)
.add(with_defaults(cookie.into()));
}
pub fn get_private(&self, name: &str) -> Option<String> {
self.jar()
.private(&self.key)
.get(name)
.map(|c| c.value().to_owned())
}
pub fn add_private(&self, cookie: impl Into<Cookie<'static>>) {
self.jar()
.private_mut(&self.key)
.add(with_defaults(cookie.into()));
}
pub(crate) fn write_to(&self, headers: &mut HeaderMap) {
for cookie in self.jar().delta() {
match cookie.encoded().to_string().try_into() {
Ok(value) => {
headers.append(SET_COOKIE, value);
}
Err(_) => tracing::warn!("dropping cookie `{}` with invalid value", cookie.name()),
}
}
}
}
fn with_defaults(mut cookie: Cookie<'static>) -> Cookie<'static> {
if cookie.path().is_none() {
cookie.set_path("/");
}
if cookie.http_only().is_none() {
cookie.set_http_only(true);
}
cookie
}
fn removal(name: &str) -> Cookie<'static> {
Cookie::build(name.to_owned()).path("/").build()
}