Skip to main content

Module session

Module session 

Source
Expand description

Server-side session management.

SessionStore is a thread-safe, TTL-aware in-memory store. Store it inside your application state (AppWithState<S>) so every handler shares the same session map automatically.

Session holds the key/value data for one session. Retrieve it with SessionStore::load, mutate it, then persist changes with SessionStore::save.

Helper functions session_id_from_request, session_cookie, and destroy_cookie translate between the HTTP cookie layer and the store.

§Security note

Session IDs are generated from a non-cryptographic hash of the system clock and an atomic counter. Sufficient for most internal applications. For public-facing services requiring unpredictable IDs, supply your own CSPRNG via SessionStore::create_with_id.

§Example

use rust_web_server::app::App;
use rust_web_server::core::New;
use rust_web_server::session::{self, SessionStore};
use rust_web_server::header::Header;
use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};

struct State { sessions: SessionStore }

let app = App::with_state(State { sessions: SessionStore::new(3600) })
    .post("/login", |req, _params, _conn, state| {
        // verify credentials …
        let mut sess = state.sessions.create();
        sess.set("user_id", "42");
        state.sessions.save(&sess);

        let mut r = Response::new();
        r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
        r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
        r.headers.push(Header {
            name: "Set-Cookie".to_string(),
            value: session::session_cookie(&sess.id, "sid", 3600),
        });
        r
    })
    .get("/profile", |req, _params, _conn, state| {
        let mut r = Response::new();
        let sid = match session::session_id_from_request(&req, "sid") {
            Some(id) => id,
            None => {
                r.status_code = *STATUS_CODE_REASON_PHRASE.n401_unauthorized.status_code;
                r.reason_phrase = STATUS_CODE_REASON_PHRASE.n401_unauthorized.reason_phrase.to_string();
                return r;
            }
        };
        let sess = match state.sessions.load(&sid) {
            Some(s) => s,
            None => {
                r.status_code = *STATUS_CODE_REASON_PHRASE.n401_unauthorized.status_code;
                r.reason_phrase = STATUS_CODE_REASON_PHRASE.n401_unauthorized.reason_phrase.to_string();
                return r;
            }
        };
        let user_id = sess.get("user_id").unwrap_or("guest");
        r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
        r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
        r
    });

Structs§

Session
Data for a single session, keyed by Session::id.
SessionStore
Thread-safe in-memory session store with TTL-based expiry.

Functions§

destroy_cookie
Build a Set-Cookie header value that clears cookie_name in the browser (Max-Age=0). Use after calling SessionStore::destroy.
session_cookie
Build a Set-Cookie header value that stores session_id in cookie_name with HttpOnly, SameSite=Lax, Path=/, and Max-Age.
session_id_from_request
Extract the session ID from the named cookie in a request’s Cookie header. Returns None if the header is absent or the cookie is missing.