Skip to main content

ntex_session/
lib.rs

1//! User sessions for the ntex web framework.
2//!
3//! The crate provides a backend-independent [`Session`] API. A session
4//! middleware loads the session state for each request and writes changes
5//! back to the response; handlers access the state through the [`Session`]
6//! extractor or the [`UserSession`] trait.
7//!
8//! Session values are stored as JSON strings and are (de)serialized with
9//! `serde_json`.
10//!
11//! Only a cookie based backend, [`CookieSession`], is provided (enabled by the
12//! default `cookie-session` feature). Other backends can be built on top of
13//! [`Session::set_session`] and [`Session::get_changes`].
14//!
15//! # Example
16//!
17//! ```rust
18//! use ntex::web::{self, App};
19//! use ntex_session::{CookieSession, Session};
20//!
21//! async fn index(session: Session) -> Result<&'static str, serde_json::Error> {
22//!     let count = session.get::<u32>("counter")?.unwrap_or(0);
23//!     session.set("counter", count + 1)?;
24//!     Ok("Welcome!")
25//! }
26//!
27//! let app = App::default()
28//!     .middleware(
29//!         // Use a secret, stable key in production; disable Secure only for local HTTP.
30//!         CookieSession::signed(&[0; 32]).secure(false),
31//!     )
32//!     .service(web::resource("/").to(index));
33//! ```
34use std::{cell::RefCell, convert::Infallible, rc::Rc};
35
36use ntex::http::{Payload, RequestHead};
37use ntex::util::{Extensions, HashMap};
38use ntex::web::{FromRequest, HttpRequest, WebRequest, WebResponse};
39use serde::Serialize;
40use serde::de::DeserializeOwned;
41use serde_json::error::Error as JsonError;
42
43#[cfg(feature = "cookie-session")]
44mod cookie;
45#[cfg(feature = "cookie-session")]
46pub use crate::cookie::{CookieSession, CookieSessionError, CookieSessionMiddleware};
47
48/// The high-level interface you use to read and modify session data.
49///
50/// `Session` is an extractor, it can also be obtained with
51/// [`UserSession::get_session`] from an [`HttpRequest`], [`WebRequest`] or
52/// [`RequestHead`]. All handles for the same request share the same state.
53/// Without session middleware, the state is not persisted between requests.
54///
55/// Once the session is [purged](Session::purge), further handler mutations
56/// through [`set`](Self::set), [`remove`](Self::remove), [`clear`](Self::clear),
57/// or [`renew`](Self::renew) are ignored.
58///
59/// ```rust
60/// use ntex_session::Session;
61/// use ntex::web::*;
62/// use serde_json::error::Error as JsonError;
63///
64/// fn index(session: Session) -> Result<&'static str, JsonError> {
65///     // access session data
66///     if let Some(count) = session.get::<i32>("counter")? {
67///         session.set("counter", count + 1)?;
68///     } else {
69///         session.set("counter", 1)?;
70///     }
71///
72///     Ok("Welcome!")
73/// }
74/// # fn main() {}
75/// ```
76pub struct Session(Rc<RefCell<SessionInner>>);
77
78/// Helper trait that allows to get the session of a request.
79pub trait UserSession {
80    /// Get the session of the request, creating an empty one if needed.
81    fn get_session(&self) -> Session;
82}
83
84impl UserSession for HttpRequest {
85    fn get_session(&self) -> Session {
86        Session::get_session(&mut self.extensions_mut())
87    }
88}
89
90impl<St> UserSession for WebRequest<St> {
91    fn get_session(&self) -> Session {
92        Session::get_session(&mut self.extensions_mut())
93    }
94}
95
96impl UserSession for RequestHead {
97    fn get_session(&self) -> Session {
98        Session::get_session(&mut self.extensions_mut())
99    }
100}
101
102/// Status of the session after the request is handled.
103///
104/// Returned by [`Session::get_changes`], backends use it to decide how to
105/// update the client.
106#[derive(PartialEq, Clone, Debug, Default)]
107pub enum SessionStatus {
108    /// A call to [`Session::set`], [`Session::remove`], or [`Session::clear`]
109    /// marked the state changed, even if it did not alter any stored value.
110    Changed,
111    /// Session was purged, the backend should remove it.
112    Purged,
113    /// Session was renewed, the backend should re-issue it with the
114    /// existing state.
115    Renewed,
116    /// Session was not modified.
117    #[default]
118    Unchanged,
119}
120
121#[derive(Default)]
122struct SessionInner {
123    state: HashMap<String, String>,
124    pub status: SessionStatus,
125}
126
127impl Session {
128    /// Get a value from the session.
129    ///
130    /// Returns `Ok(None)` if the key is not set.
131    ///
132    /// # Errors
133    ///
134    /// Returns an error if the stored JSON cannot be deserialized into `T`.
135    pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>, JsonError> {
136        if let Some(s) = self.0.borrow().state.get(key) {
137            Ok(Some(serde_json::from_str(s)?))
138        } else {
139            Ok(None)
140        }
141    }
142
143    /// Set a value in the session.
144    ///
145    /// Marks the session changed before serializing. Ignored if the session
146    /// is purged, in which case the value is not serialized.
147    ///
148    /// # Errors
149    ///
150    /// Returns an error if the value cannot be serialized. The existing value
151    /// is preserved, but the session remains marked changed.
152    pub fn set<T: Serialize>(&self, key: &str, value: T) -> Result<(), JsonError> {
153        let mut inner = self.0.borrow_mut();
154        if inner.status != SessionStatus::Purged {
155            inner.status = SessionStatus::Changed;
156            inner
157                .state
158                .insert(key.to_owned(), serde_json::to_string(&value)?);
159        }
160        Ok(())
161    }
162
163    /// Remove a value from the session.
164    ///
165    /// Ignored if the session is purged.
166    pub fn remove(&self, key: &str) {
167        let mut inner = self.0.borrow_mut();
168        if inner.status != SessionStatus::Purged {
169            inner.status = SessionStatus::Changed;
170            inner.state.remove(key);
171        }
172    }
173
174    /// Remove all values from the session.
175    ///
176    /// Ignored if the session is purged.
177    pub fn clear(&self) {
178        let mut inner = self.0.borrow_mut();
179        if inner.status != SessionStatus::Purged {
180            inner.status = SessionStatus::Changed;
181            inner.state.clear()
182        }
183    }
184
185    /// Remove the session, both client and server side.
186    ///
187    /// All values are dropped, and later calls to [`set`](Self::set),
188    /// [`remove`](Self::remove), [`clear`](Self::clear), and [`renew`](Self::renew)
189    /// in the same request are ignored. The backend performs the removal.
190    pub fn purge(&self) {
191        let mut inner = self.0.borrow_mut();
192        inner.status = SessionStatus::Purged;
193        inner.state.clear();
194    }
195
196    /// Marks the session for reissue while preserving its existing state.
197    ///
198    /// The backend chooses the renewal mechanism; [`CookieSession`] rewrites
199    /// the cookie without rotating its signing or encryption key. Ignored if
200    /// the session is purged.
201    pub fn renew(&self) {
202        let mut inner = self.0.borrow_mut();
203        if inner.status != SessionStatus::Purged {
204            inner.status = SessionStatus::Renewed;
205        }
206    }
207
208    /// Load session state into the request.
209    ///
210    /// Used by session backends before calling the inner service. Extends the
211    /// current state, overwriting matching keys without changing the status.
212    /// Values must be JSON encoded, as returned by [`Session::get_changes`];
213    /// this method does not validate them.
214    pub fn set_session<St>(data: impl Iterator<Item = (String, String)>, req: &WebRequest<St>) {
215        let session = Session::get_session(&mut req.extensions_mut());
216        let mut inner = session.0.borrow_mut();
217        inner.state.extend(data);
218    }
219
220    /// Drains the state from the response's request and returns its current status.
221    ///
222    /// Used by session backends after the inner service returns. The state is
223    /// moved out of all shared handles, but the status is not reset. Returns
224    /// `None` for the state only if no session was created; otherwise returns
225    /// `Some`, even for empty or unchanged state.
226    pub fn get_changes(
227        res: &mut WebResponse,
228    ) -> (
229        SessionStatus,
230        Option<impl Iterator<Item = (String, String)> + use<>>,
231    ) {
232        if let Some(s_impl) = res
233            .request()
234            .extensions()
235            .get::<Rc<RefCell<SessionInner>>>()
236        {
237            let state = std::mem::take(&mut s_impl.borrow_mut().state);
238            (s_impl.borrow().status.clone(), Some(state.into_iter()))
239        } else {
240            (SessionStatus::Unchanged, None)
241        }
242    }
243
244    fn get_session(extensions: &mut Extensions) -> Session {
245        if let Some(s_impl) = extensions.get::<Rc<RefCell<SessionInner>>>() {
246            return Session(Rc::clone(s_impl));
247        }
248        let inner = Rc::new(RefCell::new(SessionInner::default()));
249        extensions.insert(inner.clone());
250        Session(inner)
251    }
252}
253
254/// Extractor implementation for Session type.
255///
256/// ```rust
257/// use ntex_session::Session;
258/// use serde_json::error::Error as JsonError;
259///
260/// fn index(session: Session) -> Result<&'static str, JsonError> {
261///     // access session data
262///     if let Some(count) = session.get::<i32>("counter")? {
263///         session.set("counter", count + 1)?;
264///     } else {
265///         session.set("counter", 1)?;
266///     }
267///
268///     Ok("Welcome!")
269/// }
270/// # fn main() {}
271/// ```
272impl<St> FromRequest<St> for Session {
273    type Error = Infallible;
274
275    #[inline]
276    async fn from_request(
277        _: &St,
278        req: &HttpRequest,
279        _: &mut Payload,
280    ) -> Result<Session, Infallible> {
281        Ok(Session::get_session(&mut req.extensions_mut()))
282    }
283}
284
285#[cfg(test)]
286mod tests {
287    use ntex::web::{HttpResponse, test};
288
289    use super::*;
290
291    #[test]
292    fn session() {
293        let req = test::TestRequest::default().to_srv_request();
294
295        Session::set_session(
296            vec![("key".to_string(), "\"value\"".to_string())].into_iter(),
297            &req,
298        );
299        let session = Session::get_session(&mut req.extensions_mut());
300        let res = session.get::<String>("key").unwrap();
301        assert_eq!(res, Some("value".to_string()));
302
303        session.set("key2", "value2".to_string()).unwrap();
304        session.remove("key");
305
306        let mut res = req.into_response(HttpResponse::Ok().build());
307        let (_status, state) = Session::get_changes(&mut res);
308        let changes: Vec<_> = state.unwrap().collect();
309        assert_eq!(changes, [("key2".to_string(), "\"value2\"".to_string())]);
310    }
311
312    #[test]
313    fn get_session() {
314        let req = test::TestRequest::default().to_srv_request();
315
316        Session::set_session(
317            vec![("key".to_string(), "\"value\"".to_string())].into_iter(),
318            &req,
319        );
320
321        let session = req.get_session();
322        let res = session.get::<String>("key").unwrap();
323        assert_eq!(res, Some("value".to_string()));
324    }
325
326    #[test]
327    fn get_session_from_request_head() {
328        let mut req = test::TestRequest::default().to_srv_request();
329
330        Session::set_session(
331            vec![("key".to_string(), "\"value\"".to_string())].into_iter(),
332            &req,
333        );
334
335        let session = req.head_mut().get_session();
336        let res = session.get::<String>("key").unwrap();
337        assert_eq!(res, Some("value".to_string()));
338    }
339
340    /// STATEMENT: `Session::purge` removes all data and cannot be undone by later mutations.
341    ///
342    /// HOW:
343    /// - Store a value, purge the session, then attempt `set`, `remove`, `clear` and `renew`.
344    /// - Assert the value is absent and `get_changes` returns `Purged` with empty state.
345    #[test]
346    fn purge_session() {
347        let req = test::TestRequest::default().to_srv_request();
348        let session = req.get_session();
349        session.set("key", "value").unwrap();
350        session.purge();
351        session.set("key", "replacement").unwrap();
352        session.remove("key");
353        session.clear();
354        session.renew();
355        assert_eq!(session.get::<String>("key").unwrap(), None);
356
357        let mut res = req.into_response(HttpResponse::Ok().build());
358        let (status, state) = Session::get_changes(&mut res);
359        assert_eq!(status, SessionStatus::Purged);
360        assert_eq!(state.unwrap().count(), 0);
361    }
362
363    /// STATEMENT: `Session::renew` requests reissue without discarding loaded session data.
364    ///
365    /// HOW:
366    /// - Load a JSON-encoded value and renew the session without changing that value.
367    /// - Assert `get_changes` returns `Renewed` and the original key and encoded value.
368    #[test]
369    fn renew_session() {
370        let req = test::TestRequest::default().to_srv_request();
371        Session::set_session([("key".to_owned(), "42".to_owned())].into_iter(), &req);
372        req.get_session().renew();
373
374        let mut res = req.into_response(HttpResponse::Ok().build());
375        let (status, state) = Session::get_changes(&mut res);
376        assert_eq!(status, SessionStatus::Renewed);
377        assert_eq!(
378            state.unwrap().collect::<Vec<_>>(),
379            [("key".to_owned(), "42".to_owned())]
380        );
381    }
382
383    /// STATEMENT: Request session handles share mutations, and `get_changes` drains their state.
384    ///
385    /// HOW:
386    /// - Assert an untouched response has no session changes, then obtain two handles from one `HttpRequest`.
387    /// - Set values through both handles, clear them, and store a replacement value.
388    /// - Assert both handles see the changes and the response drains the JSON-encoded replacement.
389    #[test]
390    fn shared_session_handles_clear_and_drain_state() {
391        let mut untouched =
392            test::TestRequest::default().to_srv_response(HttpResponse::Ok().build());
393        let (status, state) = Session::get_changes(&mut untouched);
394        assert_eq!(status, SessionStatus::Unchanged);
395        assert!(state.is_none());
396
397        let req = test::TestRequest::default().to_http_request();
398        let first = req.get_session();
399        let second = req.clone().get_session();
400        first.set("first", 1).unwrap();
401        second.set("second", 2).unwrap();
402        assert_eq!(second.get::<u32>("first").unwrap(), Some(1));
403        assert_eq!(first.get::<u32>("second").unwrap(), Some(2));
404        second.clear();
405        assert_eq!(first.get::<u32>("first").unwrap(), None);
406        assert_eq!(first.get::<u32>("second").unwrap(), None);
407        first.set("replacement", 3).unwrap();
408
409        let mut res = WebRequest::from_request(req).into_response(HttpResponse::Ok().build());
410        let (status, state) = Session::get_changes(&mut res);
411        assert_eq!(status, SessionStatus::Changed);
412        assert_eq!(
413            state.unwrap().collect::<Vec<_>>(),
414            [("replacement".to_owned(), "3".to_owned())]
415        );
416        assert_eq!(second.get::<u32>("replacement").unwrap(), None);
417    }
418
419    /// STATEMENT: Session JSON errors are returned without overwriting an existing value.
420    ///
421    /// HOW:
422    /// - Load invalid JSON and a valid integer, then deserialize the invalid value and the integer as a string.
423    /// - Attempt to replace the integer with a serializer that fails and assert all errors are returned.
424    /// - Assert the original integer still appears in the session and its response changes.
425    #[test]
426    fn session_json_errors_preserve_existing_values() {
427        struct Unserializable;
428
429        impl Serialize for Unserializable {
430            fn serialize<S: serde::Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
431                Err(serde::ser::Error::custom("cannot serialize session value"))
432            }
433        }
434
435        let req = test::TestRequest::default().to_srv_request();
436        Session::set_session(
437            [
438                ("bad".to_owned(), "not-json".to_owned()),
439                ("good".to_owned(), "42".to_owned()),
440            ]
441            .into_iter(),
442            &req,
443        );
444        let session = req.get_session();
445        assert!(session.get::<u32>("bad").is_err());
446        assert!(session.get::<String>("good").is_err());
447        assert!(
448            session
449                .set("good", Unserializable)
450                .unwrap_err()
451                .to_string()
452                .contains("cannot serialize")
453        );
454        assert_eq!(session.get::<u32>("good").unwrap(), Some(42));
455
456        let mut res = req.into_response(HttpResponse::Ok().build());
457        let (_, state) = Session::get_changes(&mut res);
458        let state: HashMap<_, _> = state.unwrap().collect();
459        assert_eq!(state.get("good").map(String::as_str), Some("42"));
460    }
461}