actix_session/
lib.rs

1//! Session management for Actix Web.
2//!
3//! The HTTP protocol, at a first glance, is stateless: the client sends a request, the server
4//! parses its content, performs some processing and returns a response. The outcome is only
5//! influenced by the provided inputs (i.e. the request content) and whatever state the server
6//! queries while performing its processing.
7//!
8//! Stateless systems are easier to reason about, but they are not quite as powerful as we need them
9//! to be - e.g. how do you authenticate a user? The user would be forced to authenticate **for
10//! every single request**. That is, for example, how 'Basic' Authentication works. While it may
11//! work for a machine user (i.e. an API client), it is impractical for a person—you do not want a
12//! login prompt on every single page you navigate to!
13//!
14//! There is a solution - **sessions**. Using sessions the server can attach state to a set of
15//! requests coming from the same client. They are built on top of cookies - the server sets a
16//! cookie in the HTTP response (`Set-Cookie` header), the client (e.g. the browser) will store the
17//! cookie and play it back to the server when sending new requests (using the `Cookie` header).
18//!
19//! We refer to the cookie used for sessions as a **session cookie**. Its content is called
20//! **session key** (or **session ID**), while the state attached to the session is referred to as
21//! **session state**.
22//!
23//! `actix-session` provides an easy-to-use framework to manage sessions in applications built on
24//! top of Actix Web. [`SessionMiddleware`] is the middleware underpinning the functionality
25//! provided by `actix-session`; it takes care of all the session cookie handling and instructs the
26//! **storage backend** to create/delete/update the session state based on the operations performed
27//! against the active [`Session`].
28//!
29//! `actix-session` provides some built-in storage backends: ([`CookieSessionStore`],
30//! [`RedisSessionStore`]) - you can create a custom storage backend by implementing the
31//! [`SessionStore`] trait.
32//!
33//! Further reading on sessions:
34//! - [RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265);
35//! - [OWASP's session management cheat-sheet](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html).
36//!
37//! # Getting started
38//! To start using sessions in your Actix Web application you must register [`SessionMiddleware`]
39//! as a middleware on your `App`:
40//!
41//! ```no_run
42//! use actix_web::{web, App, HttpServer, HttpResponse, Error};
43//! use actix_session::{Session, SessionMiddleware, storage::RedisSessionStore};
44//! use actix_web::cookie::Key;
45//!
46//! #[actix_web::main]
47//! async fn main() -> std::io::Result<()> {
48//!     // When using `Key::generate()` it is important to initialize outside of the
49//!     // `HttpServer::new` closure. When deployed the secret key should be read from a
50//!     // configuration file or environment variables.
51//!     let secret_key = Key::generate();
52//!
53//!     let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379")
54//!         .await
55//!         .unwrap();
56//!
57//!     HttpServer::new(move ||
58//!             App::new()
59//!             // Add session management to your application using Redis for session state storage
60//!             .wrap(
61//!                 SessionMiddleware::new(
62//!                     redis_store.clone(),
63//!                     secret_key.clone(),
64//!                 )
65//!             )
66//!             .default_service(web::to(|| HttpResponse::Ok())))
67//!         .bind(("127.0.0.1", 8080))?
68//!         .run()
69//!         .await
70//! }
71//! ```
72//!
73//! The session state can be accessed and modified by your request handlers using the [`Session`]
74//! extractor. Note that this doesn't work in the stream of a streaming response.
75//!
76//! ```no_run
77//! use actix_web::Error;
78//! use actix_session::Session;
79//!
80//! fn index(session: Session) -> Result<&'static str, Error> {
81//!     // access the session state
82//!     if let Some(count) = session.get::<i32>("counter")? {
83//!         println!("SESSION value: {}", count);
84//!         // modify the session state
85//!         session.insert("counter", count + 1)?;
86//!     } else {
87//!         session.insert("counter", 1)?;
88//!     }
89//!
90//!     Ok("Welcome!")
91//! }
92//! ```
93//!
94//! # Choosing A Backend
95//!
96//! By default, `actix-session` does not provide any storage backend to retrieve and save the state
97//! attached to your sessions. You can enable:
98//!
99//! - a purely cookie-based "backend", [`CookieSessionStore`], using the `cookie-session` feature
100//!   flag.
101//!
102//!   ```console
103//!   cargo add actix-session --features=cookie-session
104//!   ```
105//!
106//! - a Redis-based backend via the [`redis`] crate, [`RedisSessionStore`], using the
107//!   `redis-session` feature flag.
108//!
109//!   ```console
110//!   cargo add actix-session --features=redis-session
111//!   ```
112//!
113//!   Add the `redis-session-native-tls` feature flag if you want to connect to Redis using a secure
114//!   connection (via the `native-tls` crate):
115//!
116//!   ```console
117//!   cargo add actix-session --features=redis-session-native-tls
118//!   ```
119//!
120//!   If you, instead, prefer depending on `rustls`, use the `redis-session-rustls` feature flag:
121//!
122//!   ```console
123//!   cargo add actix-session --features=redis-session-rustls
124//!   ```
125//!
126//! You can implement your own session storage backend using the [`SessionStore`] trait.
127//!
128//! [`SessionStore`]: storage::SessionStore
129//! [`CookieSessionStore`]: storage::CookieSessionStore
130//! [`RedisSessionStore`]: storage::RedisSessionStore
131
132#![forbid(unsafe_code)]
133#![warn(missing_docs)]
134#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
135#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
136#![cfg_attr(docsrs, feature(doc_auto_cfg))]
137
138pub mod config;
139mod middleware;
140mod session;
141mod session_ext;
142pub mod storage;
143
144pub use self::{
145    middleware::SessionMiddleware,
146    session::{Session, SessionGetError, SessionInsertError, SessionStatus},
147    session_ext::SessionExt,
148};
149
150#[cfg(test)]
151pub mod test_helpers {
152    use actix_web::cookie::Key;
153
154    use crate::{config::CookieContentSecurity, storage::SessionStore};
155
156    /// Generate a random cookie signing/encryption key.
157    pub fn key() -> Key {
158        Key::generate()
159    }
160
161    /// A ready-to-go acceptance test suite to verify that sessions behave as expected
162    /// regardless of the underlying session store.
163    ///
164    /// `is_invalidation_supported` must be set to `true` if the backend supports
165    /// "remembering" that a session has been invalidated (e.g. by logging out).
166    /// It should be to `false` if the backend allows multiple cookies to be active
167    /// at the same time (e.g. cookie store backend).
168    pub async fn acceptance_test_suite<F, Store>(store_builder: F, is_invalidation_supported: bool)
169    where
170        Store: SessionStore + 'static,
171        F: Fn() -> Store + Clone + Send + 'static,
172    {
173        for policy in &[
174            CookieContentSecurity::Signed,
175            CookieContentSecurity::Private,
176        ] {
177            println!("Using {policy:?} as cookie content security policy.");
178            acceptance_tests::basic_workflow(store_builder.clone(), *policy).await;
179            acceptance_tests::expiration_is_refreshed_on_changes(store_builder.clone(), *policy)
180                .await;
181            acceptance_tests::expiration_is_always_refreshed_if_configured_to_refresh_on_every_request(
182                store_builder.clone(),
183                *policy,
184            )
185            .await;
186            acceptance_tests::complex_workflow(
187                store_builder.clone(),
188                is_invalidation_supported,
189                *policy,
190            )
191            .await;
192            acceptance_tests::guard(store_builder.clone(), *policy).await;
193        }
194    }
195
196    mod acceptance_tests {
197        use actix_web::{
198            cookie::time,
199            dev::{Service, ServiceResponse},
200            guard, middleware, test,
201            web::{self, get, post, resource, Bytes},
202            App, HttpResponse, Result,
203        };
204        use serde::{Deserialize, Serialize};
205        use serde_json::json;
206
207        use crate::{
208            config::{CookieContentSecurity, PersistentSession, TtlExtensionPolicy},
209            storage::SessionStore,
210            test_helpers::key,
211            Session, SessionExt, SessionMiddleware,
212        };
213
214        pub(super) async fn basic_workflow<F, Store>(
215            store_builder: F,
216            policy: CookieContentSecurity,
217        ) where
218            Store: SessionStore + 'static,
219            F: Fn() -> Store + Clone + Send + 'static,
220        {
221            let app = test::init_service(
222                App::new()
223                    .wrap(
224                        SessionMiddleware::builder(store_builder(), key())
225                            .cookie_path("/test/".into())
226                            .cookie_name("actix-test".into())
227                            .cookie_domain(Some("localhost".into()))
228                            .cookie_content_security(policy)
229                            .session_lifecycle(
230                                PersistentSession::default()
231                                    .session_ttl(time::Duration::seconds(100)),
232                            )
233                            .build(),
234                    )
235                    .service(web::resource("/").to(|ses: Session| async move {
236                        let _ = ses.insert("counter", 100);
237                        "test"
238                    }))
239                    .service(web::resource("/test/").to(|ses: Session| async move {
240                        let val: usize = ses.get("counter").unwrap().unwrap();
241                        format!("counter: {val}")
242                    })),
243            )
244            .await;
245
246            let request = test::TestRequest::get().to_request();
247            let response = app.call(request).await.unwrap();
248            let cookie = response.get_cookie("actix-test").unwrap().clone();
249            assert_eq!(cookie.path().unwrap(), "/test/");
250
251            let request = test::TestRequest::with_uri("/test/")
252                .cookie(cookie)
253                .to_request();
254            let body = test::call_and_read_body(&app, request).await;
255            assert_eq!(body, Bytes::from_static(b"counter: 100"));
256        }
257
258        pub(super) async fn expiration_is_always_refreshed_if_configured_to_refresh_on_every_request<
259            F,
260            Store,
261        >(
262            store_builder: F,
263            policy: CookieContentSecurity,
264        ) where
265            Store: SessionStore + 'static,
266            F: Fn() -> Store + Clone + Send + 'static,
267        {
268            let session_ttl = time::Duration::seconds(60);
269            let app = test::init_service(
270                App::new()
271                    .wrap(
272                        SessionMiddleware::builder(store_builder(), key())
273                            .cookie_content_security(policy)
274                            .session_lifecycle(
275                                PersistentSession::default()
276                                    .session_ttl(session_ttl)
277                                    .session_ttl_extension_policy(
278                                        TtlExtensionPolicy::OnEveryRequest,
279                                    ),
280                            )
281                            .build(),
282                    )
283                    .service(web::resource("/").to(|ses: Session| async move {
284                        let _ = ses.insert("counter", 100);
285                        "test"
286                    }))
287                    .service(web::resource("/test/").to(|| async move { "no-changes-in-session" })),
288            )
289            .await;
290
291            // Create session
292            let request = test::TestRequest::get().to_request();
293            let response = app.call(request).await.unwrap();
294            let cookie_1 = response.get_cookie("id").expect("Cookie is set");
295            assert_eq!(cookie_1.max_age(), Some(session_ttl));
296
297            // Fire a request that doesn't touch the session state, check
298            // that the session cookie is present and its expiry is set to the maximum we configured.
299            let request = test::TestRequest::with_uri("/test/")
300                .cookie(cookie_1)
301                .to_request();
302            let response = app.call(request).await.unwrap();
303            let cookie_2 = response.get_cookie("id").expect("Cookie is set");
304            assert_eq!(cookie_2.max_age(), Some(session_ttl));
305        }
306
307        pub(super) async fn expiration_is_refreshed_on_changes<F, Store>(
308            store_builder: F,
309            policy: CookieContentSecurity,
310        ) where
311            Store: SessionStore + 'static,
312            F: Fn() -> Store + Clone + Send + 'static,
313        {
314            let session_ttl = time::Duration::seconds(60);
315            let app = test::init_service(
316                App::new()
317                    .wrap(
318                        SessionMiddleware::builder(store_builder(), key())
319                            .cookie_content_security(policy)
320                            .session_lifecycle(
321                                PersistentSession::default().session_ttl(session_ttl),
322                            )
323                            .build(),
324                    )
325                    .service(web::resource("/").to(|ses: Session| async move {
326                        let _ = ses.insert("counter", 100);
327                        "test"
328                    }))
329                    .service(web::resource("/test/").to(|| async move { "no-changes-in-session" })),
330            )
331            .await;
332
333            let request = test::TestRequest::get().to_request();
334            let response = app.call(request).await.unwrap();
335            let cookie_1 = response.get_cookie("id").expect("Cookie is set");
336            assert_eq!(cookie_1.max_age(), Some(session_ttl));
337
338            let request = test::TestRequest::with_uri("/test/")
339                .cookie(cookie_1.clone())
340                .to_request();
341            let response = app.call(request).await.unwrap();
342            assert!(response.response().cookies().next().is_none());
343
344            let request = test::TestRequest::get().cookie(cookie_1).to_request();
345            let response = app.call(request).await.unwrap();
346            let cookie_2 = response.get_cookie("id").expect("Cookie is set");
347            assert_eq!(cookie_2.max_age(), Some(session_ttl));
348        }
349
350        pub(super) async fn guard<F, Store>(store_builder: F, policy: CookieContentSecurity)
351        where
352            Store: SessionStore + 'static,
353            F: Fn() -> Store + Clone + Send + 'static,
354        {
355            let srv = actix_test::start(move || {
356                App::new()
357                    .wrap(
358                        SessionMiddleware::builder(store_builder(), key())
359                            .cookie_name("test-session".into())
360                            .cookie_content_security(policy)
361                            .session_lifecycle(
362                                PersistentSession::default().session_ttl(time::Duration::days(7)),
363                            )
364                            .build(),
365                    )
366                    .wrap(middleware::Logger::default())
367                    .service(resource("/").route(get().to(index)))
368                    .service(resource("/do_something").route(post().to(do_something)))
369                    .service(resource("/login").route(post().to(login)))
370                    .service(resource("/logout").route(post().to(logout)))
371                    .service(
372                        web::scope("/protected")
373                            .guard(guard::fn_guard(|g| {
374                                g.get_session().get::<String>("user_id").unwrap().is_some()
375                            }))
376                            .service(resource("/count").route(get().to(count))),
377                    )
378            });
379
380            // Step 1: GET without session info
381            //   - response should be a unsuccessful status
382            let req_1 = srv.get("/protected/count").send();
383            let resp_1 = req_1.await.unwrap();
384            assert!(!resp_1.status().is_success());
385
386            // Step 2: POST to login
387            //   - set-cookie actix-session will be in response  (session cookie #1)
388            //   - updates session state: {"counter": 0, "user_id": "ferris"}
389            let req_2 = srv.post("/login").send_json(&json!({"user_id": "ferris"}));
390            let resp_2 = req_2.await.unwrap();
391            let cookie_1 = resp_2
392                .cookies()
393                .unwrap()
394                .clone()
395                .into_iter()
396                .find(|c| c.name() == "test-session")
397                .unwrap();
398
399            // Step 3: POST to do_something
400            //   - adds new session state:  {"counter": 1, "user_id": "ferris" }
401            //   - set-cookie actix-session should be in response (session cookie #2)
402            //   - response should be: {"counter": 1, "user_id": None}
403            let req_3 = srv.post("/do_something").cookie(cookie_1.clone()).send();
404            let mut resp_3 = req_3.await.unwrap();
405            let result_3 = resp_3.json::<IndexResponse>().await.unwrap();
406            assert_eq!(
407                result_3,
408                IndexResponse {
409                    user_id: Some("ferris".into()),
410                    counter: 1
411                }
412            );
413            let cookie_2 = resp_3
414                .cookies()
415                .unwrap()
416                .clone()
417                .into_iter()
418                .find(|c| c.name() == "test-session")
419                .unwrap();
420
421            // Step 4: GET using a existing user id
422            //   - response should be: {"counter": 3, "user_id": "ferris"}
423            let req_4 = srv.get("/protected/count").cookie(cookie_2.clone()).send();
424            let mut resp_4 = req_4.await.unwrap();
425            let result_4 = resp_4.json::<IndexResponse>().await.unwrap();
426            assert_eq!(
427                result_4,
428                IndexResponse {
429                    user_id: Some("ferris".into()),
430                    counter: 1
431                }
432            );
433        }
434
435        pub(super) async fn complex_workflow<F, Store>(
436            store_builder: F,
437            is_invalidation_supported: bool,
438            policy: CookieContentSecurity,
439        ) where
440            Store: SessionStore + 'static,
441            F: Fn() -> Store + Clone + Send + 'static,
442        {
443            let session_ttl = time::Duration::days(7);
444            let srv = actix_test::start(move || {
445                App::new()
446                    .wrap(
447                        SessionMiddleware::builder(store_builder(), key())
448                            .cookie_name("test-session".into())
449                            .cookie_content_security(policy)
450                            .session_lifecycle(
451                                PersistentSession::default().session_ttl(session_ttl),
452                            )
453                            .build(),
454                    )
455                    .wrap(middleware::Logger::default())
456                    .service(resource("/").route(get().to(index)))
457                    .service(resource("/do_something").route(post().to(do_something)))
458                    .service(resource("/login").route(post().to(login)))
459                    .service(resource("/logout").route(post().to(logout)))
460            });
461
462            // Step 1:  GET index
463            //   - set-cookie actix-session should NOT be in response (session data is empty)
464            //   - response should be: {"counter": 0, "user_id": None}
465            let req_1a = srv.get("/").send();
466            let mut resp_1 = req_1a.await.unwrap();
467            assert!(resp_1.cookies().unwrap().is_empty());
468            let result_1 = resp_1.json::<IndexResponse>().await.unwrap();
469            assert_eq!(
470                result_1,
471                IndexResponse {
472                    user_id: None,
473                    counter: 0
474                }
475            );
476
477            // Step 2: POST to do_something
478            //   - adds new session state in redis:  {"counter": 1}
479            //   - set-cookie actix-session should be in response (session cookie #1)
480            //   - response should be: {"counter": 1, "user_id": None}
481            let req_2 = srv.post("/do_something").send();
482            let mut resp_2 = req_2.await.unwrap();
483            let result_2 = resp_2.json::<IndexResponse>().await.unwrap();
484            assert_eq!(
485                result_2,
486                IndexResponse {
487                    user_id: None,
488                    counter: 1
489                }
490            );
491            let cookie_1 = resp_2
492                .cookies()
493                .unwrap()
494                .clone()
495                .into_iter()
496                .find(|c| c.name() == "test-session")
497                .unwrap();
498            assert_eq!(cookie_1.max_age(), Some(session_ttl));
499
500            // Step 3:  GET index, including session cookie #1 in request
501            //   - set-cookie will *not* be in response
502            //   - response should be: {"counter": 1, "user_id": None}
503            let req_3 = srv.get("/").cookie(cookie_1.clone()).send();
504            let mut resp_3 = req_3.await.unwrap();
505            assert!(resp_3.cookies().unwrap().is_empty());
506            let result_3 = resp_3.json::<IndexResponse>().await.unwrap();
507            assert_eq!(
508                result_3,
509                IndexResponse {
510                    user_id: None,
511                    counter: 1
512                }
513            );
514
515            // Step 4: POST again to do_something, including session cookie #1 in request
516            //   - set-cookie will be in response (session cookie #2)
517            //   - updates session state:  {"counter": 2}
518            //   - response should be: {"counter": 2, "user_id": None}
519            let req_4 = srv.post("/do_something").cookie(cookie_1.clone()).send();
520            let mut resp_4 = req_4.await.unwrap();
521            let result_4 = resp_4.json::<IndexResponse>().await.unwrap();
522            assert_eq!(
523                result_4,
524                IndexResponse {
525                    user_id: None,
526                    counter: 2
527                }
528            );
529            let cookie_2 = resp_4
530                .cookies()
531                .unwrap()
532                .clone()
533                .into_iter()
534                .find(|c| c.name() == "test-session")
535                .unwrap();
536            assert_eq!(cookie_2.max_age(), cookie_1.max_age());
537
538            // Step 5: POST to login, including session cookie #2 in request
539            //   - set-cookie actix-session will be in response  (session cookie #3)
540            //   - updates session state: {"counter": 2, "user_id": "ferris"}
541            let req_5 = srv
542                .post("/login")
543                .cookie(cookie_2.clone())
544                .send_json(&json!({"user_id": "ferris"}));
545            let mut resp_5 = req_5.await.unwrap();
546            let cookie_3 = resp_5
547                .cookies()
548                .unwrap()
549                .clone()
550                .into_iter()
551                .find(|c| c.name() == "test-session")
552                .unwrap();
553            assert_ne!(cookie_2.value(), cookie_3.value());
554
555            let result_5 = resp_5.json::<IndexResponse>().await.unwrap();
556            assert_eq!(
557                result_5,
558                IndexResponse {
559                    user_id: Some("ferris".into()),
560                    counter: 2
561                }
562            );
563
564            // Step 6: GET index, including session cookie #3 in request
565            //   - response should be: {"counter": 2, "user_id": "ferris"}
566            let req_6 = srv.get("/").cookie(cookie_3.clone()).send();
567            let mut resp_6 = req_6.await.unwrap();
568            let result_6 = resp_6.json::<IndexResponse>().await.unwrap();
569            assert_eq!(
570                result_6,
571                IndexResponse {
572                    user_id: Some("ferris".into()),
573                    counter: 2
574                }
575            );
576
577            // Step 7: POST again to do_something, including session cookie #3 in request
578            //   - updates session state: {"counter": 3, "user_id": "ferris"}
579            //   - response should be: {"counter": 3, "user_id": "ferris"}
580            let req_7 = srv.post("/do_something").cookie(cookie_3.clone()).send();
581            let mut resp_7 = req_7.await.unwrap();
582            let result_7 = resp_7.json::<IndexResponse>().await.unwrap();
583            assert_eq!(
584                result_7,
585                IndexResponse {
586                    user_id: Some("ferris".into()),
587                    counter: 3
588                }
589            );
590
591            // Step 8: GET index, including session cookie #2 in request
592            // If invalidation is supported, no state will be found associated to this session.
593            // If invalidation is not supported, the old state will still be retrieved.
594            let req_8 = srv.get("/").cookie(cookie_2.clone()).send();
595            let mut resp_8 = req_8.await.unwrap();
596            if is_invalidation_supported {
597                assert!(resp_8.cookies().unwrap().is_empty());
598                let result_8 = resp_8.json::<IndexResponse>().await.unwrap();
599                assert_eq!(
600                    result_8,
601                    IndexResponse {
602                        user_id: None,
603                        counter: 0
604                    }
605                );
606            } else {
607                let result_8 = resp_8.json::<IndexResponse>().await.unwrap();
608                assert_eq!(
609                    result_8,
610                    IndexResponse {
611                        user_id: None,
612                        counter: 2
613                    }
614                );
615            }
616
617            // Step 9: POST to logout, including session cookie #3
618            //   - set-cookie actix-session will be in response with session cookie #3
619            //     invalidation logic
620            let req_9 = srv.post("/logout").cookie(cookie_3.clone()).send();
621            let resp_9 = req_9.await.unwrap();
622            let cookie_3 = resp_9
623                .cookies()
624                .unwrap()
625                .clone()
626                .into_iter()
627                .find(|c| c.name() == "test-session")
628                .unwrap();
629            assert_eq!(0, cookie_3.max_age().map(|t| t.whole_seconds()).unwrap());
630            assert_eq!("/", cookie_3.path().unwrap());
631
632            // Step 10: GET index, including session cookie #3 in request
633            //   - set-cookie actix-session should NOT be in response if invalidation is supported
634            //   - response should be: {"counter": 0, "user_id": None}
635            let req_10 = srv.get("/").cookie(cookie_3.clone()).send();
636            let mut resp_10 = req_10.await.unwrap();
637            if is_invalidation_supported {
638                assert!(resp_10.cookies().unwrap().is_empty());
639            }
640            let result_10 = resp_10.json::<IndexResponse>().await.unwrap();
641            assert_eq!(
642                result_10,
643                IndexResponse {
644                    user_id: None,
645                    counter: 0
646                }
647            );
648        }
649
650        #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
651        pub struct IndexResponse {
652            user_id: Option<String>,
653            counter: i32,
654        }
655
656        async fn index(session: Session) -> Result<HttpResponse> {
657            let user_id: Option<String> = session.get::<String>("user_id").unwrap();
658            let counter: i32 = session
659                .get::<i32>("counter")
660                .unwrap_or(Some(0))
661                .unwrap_or(0);
662
663            Ok(HttpResponse::Ok().json(&IndexResponse { user_id, counter }))
664        }
665
666        async fn do_something(session: Session) -> Result<HttpResponse> {
667            let user_id: Option<String> = session.get::<String>("user_id").unwrap();
668            let counter: i32 = session
669                .get::<i32>("counter")
670                .unwrap_or(Some(0))
671                .map_or(1, |inner| inner + 1);
672            session.insert("counter", counter)?;
673
674            Ok(HttpResponse::Ok().json(&IndexResponse { user_id, counter }))
675        }
676
677        async fn count(session: Session) -> Result<HttpResponse> {
678            let user_id: Option<String> = session.get::<String>("user_id").unwrap();
679            let counter: i32 = session.get::<i32>("counter").unwrap().unwrap();
680
681            Ok(HttpResponse::Ok().json(&IndexResponse { user_id, counter }))
682        }
683
684        #[derive(Deserialize)]
685        struct Identity {
686            user_id: String,
687        }
688
689        async fn login(user_id: web::Json<Identity>, session: Session) -> Result<HttpResponse> {
690            let id = user_id.into_inner().user_id;
691            session.insert("user_id", &id)?;
692            session.renew();
693
694            let counter: i32 = session
695                .get::<i32>("counter")
696                .unwrap_or(Some(0))
697                .unwrap_or(0);
698
699            Ok(HttpResponse::Ok().json(&IndexResponse {
700                user_id: Some(id),
701                counter,
702            }))
703        }
704
705        async fn logout(session: Session) -> Result<HttpResponse> {
706            let id: Option<String> = session.get("user_id")?;
707
708            let body = if let Some(id) = id {
709                session.purge();
710                format!("Logged out: {id}")
711            } else {
712                "Could not log out anonymous user".to_owned()
713            };
714
715            Ok(HttpResponse::Ok().body(body))
716        }
717
718        trait ServiceResponseExt {
719            fn get_cookie(&self, cookie_name: &str) -> Option<actix_web::cookie::Cookie<'_>>;
720        }
721
722        impl ServiceResponseExt for ServiceResponse {
723            fn get_cookie(&self, cookie_name: &str) -> Option<actix_web::cookie::Cookie<'_>> {
724                self.response().cookies().find(|c| c.name() == cookie_name)
725            }
726        }
727    }
728}