1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
//! Cookies Extractor

use std::sync::{Arc, Mutex};

use crate::{
    async_trait, Error, FromRequest, IntoResponse, Request, RequestExt, Response, StatusCode,
    ThisError,
};

pub use libcookie::{Cookie, CookieJar, SameSite};

#[cfg(any(feature = "cookie-signed", feature = "cookie-private"))]
pub type CookieKey = libcookie::Key;

pub struct Cookies {
    inner: Arc<Mutex<CookieJar>>,
    #[cfg(any(feature = "cookie-signed", feature = "cookie-private"))]
    key: Option<Arc<CookieKey>>,
}

impl Clone for Cookies {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            #[cfg(any(feature = "cookie-signed", feature = "cookie-private"))]
            key: self.key.clone(),
        }
    }
}

impl Cookies {
    pub(crate) const SPLITER: char = ';';

    pub fn new(cookie_jar: CookieJar) -> Self {
        Self {
            inner: Arc::new(Mutex::new(cookie_jar)),
            #[cfg(any(feature = "cookie-signed", feature = "cookie-private"))]
            key: None,
        }
    }

    pub fn jar(&self) -> &Mutex<CookieJar> {
        &self.inner
    }

    pub fn remove(&self, name: impl AsRef<str>) {
        if let Ok(mut c) = self.jar().lock() {
            c.remove(Cookie::named(name.as_ref().to_string()))
        }
    }

    pub fn get(&self, name: impl AsRef<str>) -> Option<Cookie<'_>> {
        self.jar()
            .lock()
            .ok()
            .and_then(|c| c.get(name.as_ref()).cloned())
    }

    pub fn add(&self, cookie: Cookie<'_>) {
        if let Ok(mut c) = self.jar().lock() {
            c.add(cookie.into_owned())
        }
    }

    pub fn add_original(&self, cookie: Cookie<'_>) {
        if let Ok(mut c) = self.jar().lock() {
            c.add_original(cookie.into_owned())
        }
    }

    pub fn reset_delta(&self) {
        if let Ok(mut c) = self.jar().lock() {
            c.reset_delta()
        }
    }
}

#[cfg(any(feature = "cookie-signed", feature = "cookie-private"))]
impl Cookies {
    pub fn with_key(mut self, key: Arc<CookieKey>) -> Self {
        self.key.replace(key);
        self
    }

    pub fn key(&self) -> &CookieKey {
        self.key.as_ref().expect("the `CookieKey` is required")
    }
}

#[cfg(feature = "cookie-private")]
impl Cookies {
    pub fn private_get(&self, name: impl AsRef<str>) -> Option<Cookie<'_>> {
        self.jar()
            .lock()
            .ok()
            .and_then(|c| c.private(self.key()).get(name.as_ref()))
    }

    pub fn private_add(&self, cookie: Cookie<'_>) {
        if let Ok(mut c) = self.jar().lock() {
            c.private_mut(self.key()).add(cookie.into_owned())
        }
    }

    pub fn private_remove(&self, name: impl AsRef<str>) {
        if let Ok(mut c) = self.jar().lock() {
            c.private_mut(self.key())
                .remove(Cookie::named(name.as_ref().to_string()))
        }
    }

    pub fn private_add_original(&self, cookie: Cookie<'_>) {
        if let Ok(mut c) = self.jar().lock() {
            c.private_mut(self.key()).add_original(cookie.into_owned())
        }
    }

    pub fn private_decrypt(&self, cookie: Cookie<'_>) -> Option<Cookie<'_>> {
        self.jar()
            .lock()
            .ok()?
            .private(self.key())
            .decrypt(cookie.into_owned())
    }
}

#[cfg(feature = "cookie-signed")]
impl Cookies {
    pub fn signed_get(&self, name: impl AsRef<str>) -> Option<Cookie<'_>> {
        self.jar()
            .lock()
            .ok()
            .and_then(|c| c.signed(self.key()).get(name.as_ref()))
    }

    pub fn signed_add(&self, cookie: Cookie<'_>) {
        if let Ok(mut c) = self.jar().lock() {
            c.signed_mut(self.key()).add(cookie.into_owned())
        }
    }

    pub fn signed_remove(&self, name: impl AsRef<str>) {
        if let Ok(mut c) = self.jar().lock() {
            c.signed_mut(self.key())
                .remove(Cookie::named(name.as_ref().to_string()))
        }
    }

    pub fn signed_add_original(&self, cookie: Cookie<'_>) {
        if let Ok(mut c) = self.jar().lock() {
            c.signed_mut(self.key()).add_original(cookie.into_owned())
        }
    }

    pub fn signed_verify(&self, cookie: Cookie<'_>) -> Option<Cookie<'_>> {
        self.jar()
            .lock()
            .ok()?
            .signed(self.key())
            .verify(cookie.into_owned())
    }
}

#[derive(ThisError, Debug)]
pub enum CookiesError {
    /// Failed to read cookies
    #[error("failed to read cookies")]
    Read,
    /// Failed to parse cookies
    #[error("failed to parse cookies")]
    Parse,
}

impl From<CookiesError> for Error {
    fn from(e: CookiesError) -> Self {
        Error::Responder(e.into_response())
    }
}

impl IntoResponse for CookiesError {
    fn into_response(self) -> Response {
        (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()).into_response()
    }
}

#[async_trait]
impl FromRequest for Cookies {
    type Error = CookiesError;

    async fn extract(req: &mut Request) -> Result<Self, Self::Error> {
        req.cookies()
    }
}