axum_cookie/
lib.rs

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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#![doc = include_str!("../README.md")]
use axum_core::extract::{FromRequestParts, Request};
use axum_core::response::Response;
use cookie_rs::{Cookie, CookieJar};
use http::header::{COOKIE, SET_COOKIE};
use http::request::Parts;
use http::{HeaderValue, StatusCode};
use std::collections::BTreeSet;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use tower_layer::Layer;
use tower_service::Service;

pub mod cookie {
    pub use cookie_rs::*;
}

pub mod prelude {
    pub use crate::CookieLayer;
    pub use crate::CookieManager;
    pub use cookie_rs::prelude::*;
}

/// Manages cookies using a thread-safe `CookieJar`.
/// This struct provides methods to add, remove, and retrieve cookies,
/// as well as generate `Set-Cookie` headers for HTTP responses.
#[derive(Clone)]
pub struct CookieManager {
    jar: Arc<Mutex<CookieJar<'static>>>,
}

impl CookieManager {
    /// Creates a new instance of `CookieManager` with the specified cookie jar.
    ///
    /// # Arguments
    /// * `jar` - The initial cookie jar to manage cookies.
    pub fn new(jar: CookieJar<'static>) -> Self {
        Self {
            jar: Arc::new(Mutex::new(jar)),
        }
    }

    /// Adds a cookie to the jar.
    ///
    /// # Arguments
    /// * `cookie` - The cookie to add to the jar.
    pub fn add<C: Into<Cookie<'static>>>(&self, cookie: C) {
        let mut jar = self.jar.lock().unwrap();

        jar.add(cookie);
    }

    /// Adds a cookie to the jar.
    ///
    /// # Arguments
    /// * `cookie` - The cookie to add to the jar.
    ///
    /// > alias for `CookieManager::add`
    pub fn set<C: Into<Cookie<'static>>>(&self, cookie: C) {
        self.add(cookie);
    }

    /// Removes a cookie from the jar by its name.
    ///
    /// # Arguments
    /// * `name` - The name of the cookie to remove.
    pub fn remove(&self, name: &str) {
        let mut jar = self.jar.lock().unwrap();

        jar.remove(name.to_owned());
    }

    /// Retrieves a cookie from the jar by its name.
    ///
    /// # Arguments
    /// * `name` - The name of the cookie to retrieve.
    ///
    /// # Returns
    /// * `Option<Cookie<'static>>` - The cookie if found, otherwise `None`.
    pub fn get(&self, name: &str) -> Option<Cookie<'static>> {
        let jar = self.jar.lock().unwrap();

        jar.get(name).cloned()
    }

    /// Returns all cookies in the jar as a set.
    ///
    /// # Returns
    /// * `BTreeSet<Cookie<'static>>` - A set of all cookies currently in the jar.
    pub fn cookie(&self) -> BTreeSet<Cookie<'static>> {
        let jar = self.jar.lock().unwrap();

        jar.cookie().into_iter().cloned().collect()
    }

    /// Generates `Set-Cookie` header value for all cookies in the jar.
    ///
    /// # Returns
    /// * `Vec<String>` - A vector of `Set-Cookie` header string value.
    pub fn as_header_value(&self) -> Vec<String> {
        let jar = self.jar.lock().unwrap();

        jar.as_header_values()
    }
}

impl<S> FromRequestParts<S> for CookieManager {
    type Rejection = (StatusCode, String);

    fn from_request_parts(
        parts: &mut Parts,
        _: &S,
    ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send {
        Box::pin(async move {
            parts
                .extensions
                .get::<Result<Self, Self::Rejection>>()
                .cloned()
                .ok_or((
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "CookieLayer is not initialized".to_string(),
                ))?
        })
    }
}

/// A middleware layer for processing cookies.
/// This layer integrates cookie management into the middleware stack.
#[derive(Clone, Default)]
pub struct CookieLayer {
    strict: bool,
}

impl CookieLayer {
    /// Creates a layer with strict cookie parsing enabled.
    pub fn strict() -> Self {
        Self { strict: true }
    }
}

impl<S> Layer<S> for CookieLayer {
    type Service = CookieMiddleware<S>;

    fn layer(&self, inner: S) -> Self::Service {
        CookieMiddleware {
            strict: self.strict,
            inner,
        }
    }
}

/// Middleware for handling HTTP requests and responses with cookies.
/// This middleware parses cookies from requests and adds `Set-Cookie` headers to responses.
#[derive(Clone)]
pub struct CookieMiddleware<S> {
    strict: bool,
    inner: S,
}

impl<S, ReqBody> Service<Request<ReqBody>> for CookieMiddleware<S>
where
    S: Service<Request<ReqBody>, Response = Response<ReqBody>> + Send + 'static,
    S::Future: Send + 'static,
    ReqBody: Send + 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, mut req: Request<ReqBody>) -> Self::Future {
        let cookie = req
            .headers()
            .get(COOKIE)
            .map(|h| h.to_str())
            .unwrap_or(Ok(""))
            .map(|c| c.to_owned());

        let manager = cookie
            .map(|cookie| {
                match self.strict {
                    false => CookieJar::parse(cookie),
                    true => CookieJar::parse_strict(cookie),
                }
                .map(CookieManager::new)
                .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))
            })
            .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))
            .and_then(|inner| inner);

        req.extensions_mut().insert(manager.clone());

        let fut = self.inner.call(req);

        Box::pin(async move {
            let mut response = fut.await?;

            if let Ok(manager) = manager {
                for cookie in manager.as_header_value() {
                    response
                        .headers_mut()
                        .append(SET_COOKIE, HeaderValue::from_str(&cookie).unwrap());
                }
            }

            Ok(response)
        })
    }
}