use std::sync::Arc;
use http::{
header::{self, HeaderName, HeaderValue},
request::Parts as RequestParts,
};
use crate::headers::ALLOW_CREDENTIALS_TRUE;
#[derive(Clone, Default)]
#[must_use]
pub struct AllowCredentials(AllowCredentialsInner);
impl AllowCredentials {
pub fn yes() -> Self {
Self(AllowCredentialsInner::Yes)
}
pub fn predicate<F>(f: F) -> Self
where
F: Fn(&HeaderValue, &RequestParts) -> bool + Send + Sync + 'static,
{
Self(AllowCredentialsInner::Predicate(Arc::new(f)))
}
pub(crate) fn is_true(&self) -> bool {
matches!(&self.0, AllowCredentialsInner::Yes)
}
pub(crate) fn to_header(
&self,
origin: Option<&HeaderValue>,
parts: &RequestParts,
) -> Option<(HeaderName, HeaderValue)> {
let allow_creds = match &self.0 {
AllowCredentialsInner::Yes => true,
AllowCredentialsInner::No => false,
AllowCredentialsInner::Predicate(f) => origin.is_some() && f(origin?, parts),
};
allow_creds.then_some((
header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
ALLOW_CREDENTIALS_TRUE,
))
}
}
impl std::fmt::Debug for AllowCredentials {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.0 {
AllowCredentialsInner::Yes => f.debug_tuple("Yes").finish(),
AllowCredentialsInner::No => f.debug_tuple("No").finish(),
AllowCredentialsInner::Predicate(_) => f.debug_tuple("Predicate").finish(),
}
}
}
impl From<bool> for AllowCredentials {
fn from(v: bool) -> Self {
if v {
Self::yes()
} else {
Self(AllowCredentialsInner::No)
}
}
}
#[derive(Clone, Default)]
enum AllowCredentialsInner {
Yes,
#[default]
No,
#[allow(clippy::type_complexity)]
Predicate(Arc<dyn for<'a> Fn(&'a HeaderValue, &'a RequestParts) -> bool + Send + Sync>),
}