hyper_cors/
allow_credentials.rs1use std::sync::Arc;
4
5use http::{
6 header::{self, HeaderName, HeaderValue},
7 request::Parts as RequestParts,
8};
9
10use crate::headers::ALLOW_CREDENTIALS_TRUE;
11
12#[derive(Clone, Default)]
14#[must_use]
15pub struct AllowCredentials(AllowCredentialsInner);
16
17impl AllowCredentials {
18 pub fn yes() -> Self {
20 Self(AllowCredentialsInner::Yes)
21 }
22
23 pub fn predicate<F>(f: F) -> Self
27 where
28 F: Fn(&HeaderValue, &RequestParts) -> bool + Send + Sync + 'static,
29 {
30 Self(AllowCredentialsInner::Predicate(Arc::new(f)))
31 }
32
33 pub(crate) fn is_true(&self) -> bool {
37 matches!(&self.0, AllowCredentialsInner::Yes)
38 }
39
40 pub(crate) fn to_header(
44 &self,
45 origin: Option<&HeaderValue>,
46 parts: &RequestParts,
47 ) -> Option<(HeaderName, HeaderValue)> {
48 let allow_creds = match &self.0 {
49 AllowCredentialsInner::Yes => true,
50 AllowCredentialsInner::No => false,
51 AllowCredentialsInner::Predicate(f) => origin.is_some() && f(origin?, parts),
52 };
53 allow_creds.then_some((
54 header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
55 ALLOW_CREDENTIALS_TRUE,
56 ))
57 }
58}
59
60impl std::fmt::Debug for AllowCredentials {
61 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62 match &self.0 {
63 AllowCredentialsInner::Yes => f.debug_tuple("Yes").finish(),
64 AllowCredentialsInner::No => f.debug_tuple("No").finish(),
65 AllowCredentialsInner::Predicate(_) => f.debug_tuple("Predicate").finish(),
66 }
67 }
68}
69
70impl From<bool> for AllowCredentials {
71 fn from(v: bool) -> Self {
72 if v {
73 Self::yes()
74 } else {
75 Self(AllowCredentialsInner::No)
76 }
77 }
78}
79
80#[derive(Clone, Default)]
81enum AllowCredentialsInner {
82 Yes,
83 #[default]
84 No,
85 #[allow(clippy::type_complexity)]
86 Predicate(Arc<dyn for<'a> Fn(&'a HeaderValue, &'a RequestParts) -> bool + Send + Sync>),
87}