### Example: Storing a Session in Axum Session Source: https://docs.rs/axum_session/latest/src/axum_session/session_store.rs_search=std%3A%3Avec Demonstrates how to initialize a SessionStore with a null pool, create session configuration, generate a session token, and store session data using the `store_session` method. This example requires the `axum_session` and `uuid` crates. ```Rust use axum_session::{SessionNullPool, SessionConfig, SessionStore, SessionData}; use uuid::Uuid; let config = SessionConfig::default(); let session_store = SessionStore::::new(None, config.clone()).await.unwrap(); let token = Uuid::new_v4(); let session_data = SessionData::new(token, true, &config); async { let _ = session_store.store_session(&session_data).await.unwrap(); }; ``` -------------------------------- ### Default Axum Session Setup with SQLx Source: https://docs.rs/axum_session/latest/axum_session/index Demonstrates a default setup for Axum session management using SQLx for database persistence. It configures the session store, applies the SessionLayer to the Axum router, and includes a basic greet handler that increments a session counter. ```rust use sqlx::{ConnectOptions, postgres::{PgPoolOptions, PgConnectOptions}}; use std::net::SocketAddr; use axum_session::{Session, SessionPgPool, SessionConfig, SessionStore, SessionLayer}; use axum::{ Router, routing::get, }; use tokio::net::TcpListener; #[tokio::main] async fn main() { let pool = connect_to_database().await.unwrap(); //This Defaults as normal Cookies. //To enable signed cookies for integrity, and authenticity please check the enable_signed_cookies_headers Example. let session_config = SessionConfig::default() .with_table_name("sessions_table"); // create SessionStore and initiate the database tables let session_store = SessionStore::::new(Some(pool.clone().into()), session_config).await.unwrap(); // build our application with some routes let app = Router::new() .route("/greet", get(greet)) .layer(SessionLayer::new(session_store)); // run it let addr = SocketAddr::from(([0, 0, 0, 0], 8000)); println!("listening on {}", addr); let listener = TcpListener::bind(addr).await.unwrap(); axum::serve(listener, app).await.unwrap(); } async fn greet(session: Session) -> String { let mut count: usize = session.get("count").unwrap_or(0); count += 1; session.set("count", count); count.to_string() } async fn connect_to_database() -> anyhow::Result> { // ... unimplemented!() } ``` -------------------------------- ### Example: Generate Random Key in Rust Source: https://docs.rs/axum_session/latest/axum_session/config/struct.Key_search= Shows how to generate a new `Key` using a secure, random source provided by the operating system. It includes examples for both the panicking `generate()` method and the fallible `try_generate()` method, which returns an `Option`. ```Rust use cookie::Key; let key = Key::generate(); ``` ```Rust use cookie::Key; let key = Key::try_generate(); ``` -------------------------------- ### Get Default SessionConfig (Rust) Source: https://docs.rs/axum_session/latest/axum_session/struct.SessionConfig_search= Provides an example of how to obtain the default configuration for `SessionConfig`. This is the starting point for most custom configurations. ```rust impl Default for SessionConfig { fn default() -> Self { // Implementation details for default value } } ``` -------------------------------- ### Example: Clearing All Sessions from Database in Axum Session Source: https://docs.rs/axum_session/latest/src/axum_session/session_store.rs_search=std%3A%3Avec Shows how to initialize a SessionStore with a null pool and session configuration, then use the `clear_store` method to remove all sessions from the underlying database. This example requires the `axum_session` crate. ```Rust use axum_session::{SessionNullPool, SessionConfig, SessionStore}; let config = SessionConfig::default(); let session_store = SessionStore::::new(None, config.clone()).await.unwrap(); async { let _ = session_store.clear_store().await.unwrap(); }; ``` -------------------------------- ### SessionConfig Methods Source: https://docs.rs/axum_session/latest/axum_session/struct.SessionConfig Detailed documentation for individual SessionConfig methods, explaining their purpose and providing usage examples. ```APIDOC ## SessionConfig Methods ### `with_filter_false_positive_probability(probability: f64)` #### Description Sets the false positive probability for the session's bloom filter. A lower probability reduces false positives but increases memory usage. #### Method POST #### Endpoint /websites/rs_axum_session/session_config/with_filter_false_positive_probability #### Query Parameters - **probability** (f64) - Required - The desired false positive probability (e.g., 0.01). #### Request Example ```json { "probability": 0.01 } ``` #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "False positive probability set to 0.01." } ``` ### `with_bloom_filter(enable: bool)` #### Description Enables or disables the session's bloom filters. Bloom filters help in quickly checking for the potential existence of a session. #### Method POST #### Endpoint /websites/rs_axum_session/session_config/with_bloom_filter #### Query Parameters - **enable** (bool) - Required - `true` to enable, `false` to disable. #### Request Example ```json { "enable": true } ``` #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Bloom filter enabled." } ``` ### `get_session_name()` #### Description Retrieves the name of the session cookie or header. #### Method GET #### Endpoint /websites/rs_axum_session/session_config/get_session_name #### Success Response (200) - **session_name** (string) - The name of the session. #### Response Example ```json { "session_name": "_axum_session_id" } ``` ### `get_store_name()` #### Description Retrieves the name used for storing session data (e.g., in cookies or headers). #### Method GET #### Endpoint /websites/rs_axum_session/session_config/get_store_name #### Success Response (200) - **store_name** (string) - The name of the session store. #### Response Example ```json { "store_name": "session_store" } ``` ### `with_clear_check_on_load(enable: bool)` #### Description Configures whether to clear session data if checks fail upon loading. If `true`, data is unloaded; if `false`, checks are bypassed. #### Method POST #### Endpoint /websites/rs_axum_session/session_config/with_clear_check_on_load #### Query Parameters - **enable** (bool) - Required - `true` to enable clearing on check failure, `false` to bypass. #### Request Example ```json { "enable": true } ``` #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Clear check on load enabled." } ``` ### `with_prefix_with_host(enable: bool)` #### Description Determines whether the `__Host-` prefix is added to cookie names. This prefix enforces secure cookie settings (secure flag, HTTPS, root path, no domain). #### Method POST #### Endpoint /websites/rs_axum_session/session_config/with_prefix_with_host #### Query Parameters - **enable** (bool) - Required - `true` to enable `__Host-` prefix, `false` otherwise. #### Request Example ```json { "enable": true } ``` #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "__Host- prefix enabled." } ``` ### `with_ip_and_user_agent(enable: bool)` #### Description Enables or disables the use of IP address and user agent for signing session cookies and header values. This enhances security by making it harder to spoof sessions. #### Method POST #### Endpoint /websites/rs_axum_session/session_config/with_ip_and_user_agent #### Query Parameters - **enable** (bool) - Required - `true` to enable IP and user agent signing, `false` otherwise. #### Request Example ```json { "enable": false } ``` #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "IP and user agent signing disabled." } ``` ### `with_hashed_ip(enable: bool)` #### Description Configures whether to use the connected IP address for hashing and verifying cookie integrity. This option is only effective if `with_ip_and_user_agent` is also enabled. #### Method POST #### Endpoint /websites/rs_axum_session/session_config/with_hashed_ip #### Query Parameters - **enable** (bool) - Required - `true` to enable IP hashing, `false` otherwise. #### Request Example ```json { "enable": true } ``` #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "IP hashing enabled." } ``` ### `with_hashed_xforward(enable: bool)` #### Description Configures whether to use `X-Forwarded-For` header information for hashing and verifying cookie integrity. This option is only effective if `with_ip_and_user_agent` is also enabled. #### Method POST #### Endpoint /websites/rs_axum_session/session_config/with_hashed_xforward #### Query Parameters - **enable** (bool) - Required - `true` to enable X-Forwarded-For hashing, `false` otherwise. #### Request Example ```json { "enable": true } ``` #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "X-Forwarded-For hashing enabled." } ``` ### `with_hashed_forward(enable: bool)` #### Description Configures whether to use `Forwarded` header information for hashing and verifying cookie integrity. This option is only effective if `with_ip_and_user_agent` is also enabled. #### Method POST #### Endpoint /websites/rs_axum_session/session_config/with_hashed_forward #### Query Parameters - **enable** (bool) - Required - `true` to enable Forwarded hashing, `false` otherwise. #### Request Example ```json { "enable": true } ``` #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Forwarded hashing enabled." } ``` ### `with_hashed_real_ip(enable: bool)` #### Description Configures whether to use the `X-Real-IP` header information for hashing and verifying cookie integrity. This option is only effective if `with_ip_and_user_agent` is also enabled. #### Method POST #### Endpoint /websites/rs_axum_session/session_config/with_hashed_real_ip #### Query Parameters - **enable** (bool) - Required - `true` to enable X-Real-IP hashing, `false` otherwise. #### Request Example ```json { "enable": true } ``` #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "X-Real-IP hashing enabled." } ``` ### `with_hashed_user_agent(enable: bool)` #### Description Configures whether to use the browser's user agent information for hashing and verifying cookie integrity. This option is only effective if `with_ip_and_user_agent` is also enabled. #### Method POST #### Endpoint /websites/rs_axum_session/session_config/with_hashed_user_agent #### Query Parameters - **enable** (bool) - Required - `true` to enable user agent hashing, `false` otherwise. #### Request Example ```json { "enable": true } ``` #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "User agent hashing enabled." } ``` ``` -------------------------------- ### Example: Get Verified Cookie Source: https://docs.rs/axum_session/latest/axum_session/sec/signed/struct.AdditionalSignedJar_search=std%3A%3Avec Illustrates how to retrieve and verify a cookie using the `get` method. It shows the scenario where a cookie does not exist, then how to add a cookie using a mutable signed jar, and finally how to retrieve and assert its verified value. ```rust use cookie::{CookieJar, Cookie, Key}; let key = Key::generate(); let jar = CookieJar::new(); assert!(jar.message_signed(&key, "".to_owned()).get("name").is_none()); let mut jar = jar; let mut signed_jar = jar.message_signed_mut(&key, "".to_owned()); signed_jar.add(Cookie::new("name", "value")); assert_eq!(signed_jar.get("name").unwrap().value(), "value"); ``` -------------------------------- ### Example: Add and Verify Signed Cookie Source: https://docs.rs/axum_session/latest/axum_session/sec/signed/struct.AdditionalSignedJar_search=std%3A%3Avec Demonstrates adding a cookie using `add` and then verifying it using `get`. It shows that the value retrieved by `get` is the original value, while the value directly from the jar is signed. This highlights the signing and verification process. ```rust use cookie::{CookieJar, Cookie, Key}; let key = Key::generate(); let mut jar = CookieJar::new(); jar.message_signed_mut(&key, "".to_owned()).add(("name", "value")); assert_ne!(jar.get("name").unwrap().value(), "value"); assert!(jar.get("name").unwrap().value().contains("value")); assert_eq!(jar.message_signed(&key, "".to_owned()).get("name").unwrap().value(), "value"); ``` -------------------------------- ### SessionStore Initialization Source: https://docs.rs/axum_session/latest/axum_session/session_store/struct.SessionStore_search=std%3A%3Avec Demonstrates how to create a new SessionStore with default configuration and no database client. ```APIDOC ## POST /initialize-session-store ### Description Constructs a new `SessionStore` and creates the database table needed for the session if it does not exist, provided a client is not `None`. ### Method POST ### Endpoint /initialize-session-store ### Parameters #### Query Parameters - **client** (Option) - Required - Client for the database. - **config** (SessionConfig) - Required - Session Configuration. ### Request Body ```json { "client": null, "config": { "cookie_name": "session", "cookie_secure": true, "cookie_http_only": true, "cookie_same_site": "Lax", "cookie_path": "/", "cookie_max_age": null, "session_lifetime": 3600, "key_store_path": null } } ``` ### Response #### Success Response (200) - **session_store** (SessionStore) - The newly created SessionStore instance. #### Response Example ```json { "session_store": { "client": null, "inner": {}, "config": { "cookie_name": "session", "cookie_secure": true, "cookie_http_only": true, "cookie_same_site": "Lax", "cookie_path": "/", "cookie_max_age": null, "session_lifetime": 3600, "key_store_path": null }, "timers": {}, "filter": {} } } ``` ``` -------------------------------- ### Session Store Access Source: https://docs.rs/axum_session/latest/axum_session/databases/any_db/type.SessionAnySession_search=u32+-%3E+bool Provides methods to get and get mutable references to the session store. ```APIDOC ## GET /session/store ### Description Returns the session store, which contains shared data for all sessions. ### Method GET ### Endpoint /session/store ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **store** (SessionStore) - The session store object. #### Response Example ```json { "store": "..." } ``` ## GET /session/store/mut ### Description Returns a mutable reference to the session store, allowing modification of shared session data. ### Method GET ### Endpoint /session/store/mut ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **store** (SessionStore) - A mutable reference to the session store object. #### Response Example ```json { "store": "..." } ``` ``` -------------------------------- ### Example: Create Key from Byte Slice in Rust Source: https://docs.rs/axum_session/latest/axum_session/config/struct.Key_search= Demonstrates how to create a `Key` instance from a byte slice. It highlights the requirement for the key to be at least 64 bytes long and shows a successful creation. A non-panicking version using `try_from` is also illustrated. ```Rust use cookie::Key; let key = { /* a cryptographically random key >= 64 bytes */ }; let key = Key::from(key); ``` ```Rust use cookie::Key; let key = { /* a cryptographically random key >= 64 bytes */ }; assert!(Key::try_from(key).is_ok()); // A key that's far too short to use. let key = &[1, 2, 3, 4][..]; assert!(Key::try_from(key).is_err()); ``` -------------------------------- ### Get Type ID of SessionConfig (Rust) Source: https://docs.rs/axum_session/latest/axum_session/struct.SessionConfig_search= Demonstrates the use of the `Any` trait to get the `TypeId` of a `SessionConfig` instance. This is part of Rust's dynamic typing capabilities. ```rust impl Any for T where T: 'static + ?Sized { fn type_id(&self) -> TypeId { // Implementation details for type_id } } ``` -------------------------------- ### Service Readiness and Execution Methods Source: https://docs.rs/axum_session/latest/axum_session/service/struct.SessionService_search= These methods provide ways to interact with a service's readiness state and execute requests. They include obtaining mutable references, consuming the service, processing streams of requests, and handling futures. ```rust fn ready(&mut self) -> Ready<'_, Self, Request> fn ready_oneshot(self) -> ReadyOneshot fn oneshot(self, req: Request) -> Oneshot fn call_all(self, reqs: S) -> CallAll where Self: Sized, S: Stream ``` -------------------------------- ### Get Session Store Name Source: https://docs.rs/axum_session/latest/src/axum_session/config.rs Retrieves the name associated with the session store. This function is intended to get the store name, though its specific use case is not detailed in the provided context. ```rust /// Get's the session's store booleans Cookie/Header name /// /// # Examples /// ```rust /// use axum_session::SessionConfig; /// /// let name = SessionConfig::default().get_store_name(); /// ``` ``` -------------------------------- ### Type Conversion Utilities Source: https://docs.rs/axum_session/latest/axum_session/config/struct.CookieAndHeaderConfig Provides documentation for `TryFrom` and `TryInto` traits used for type conversions, including error handling. ```APIDOC ## Type Conversion Utilities ### Description This section details the `TryFrom` and `TryInto` traits, which are used for fallible type conversions. It includes the definition of the `Error` type for conversion failures and the methods for performing these conversions. ### `TryFrom` Trait #### `type Error` - **Description**: The type returned in the event of a conversion error. #### `fn try_from(value: U) -> Result>::Error>` - **Description**: Performs the conversion from type `U` to type `T`. - **Method**: N/A (Trait method) - **Parameters**: - `value` (U): The value to convert. - **Response**: - `Result`: Ok(T) on success, Err(Error) on failure. ### `TryInto` Trait #### `type Error` - **Description**: The type returned in the event of a conversion error. This is a type alias for the `Error` type of the corresponding `TryFrom` implementation. #### `fn try_into(self) -> Result>::Error>` - **Description**: Performs the conversion from type `T` to type `U`. - **Method**: N/A (Trait method) - **Parameters**: - `self` (T): The value to convert. - **Response**: - `Result`: Ok(U) on success, Err(Error) on failure. ``` -------------------------------- ### Session Data Retrieval and Modification Source: https://docs.rs/axum_session/latest/axum_session/databases/type.SessionAnySession Functions for getting, getting and removing, setting, and removing specific data items from the session's HashMap. These operations allow for dynamic management of session data. ```rust pub fn get(&self, key: &str) -> Option pub fn get_remove(&self, key: &str) -> Option pub fn set(&self, key: &str, value: impl Serialize) pub fn remove(&self, key: &str) ``` -------------------------------- ### Create New SessionStore Instance in Rust Source: https://docs.rs/axum_session/latest/axum_session/databases/any_db/type.SessionAnySessionStore_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to construct a new `SessionStore` instance. It takes an optional database client and a `SessionConfig`. If the client is provided, it ensures the necessary database table for sessions is created. ```rust use axum_session::{SessionNullPool, SessionConfig, SessionStore}; let config = SessionConfig::default(); let session_store = SessionStore::::new(None, config).await.unwrap(); ``` -------------------------------- ### Get Data from Session HashMap (Rust) Source: https://docs.rs/axum_session/latest/axum_session/databases/any_db/type.SessionAnySession The `get` function retrieves data from the session's HashMap using a specified key. It returns an `Option` which is `None` if the key doesn't exist or deserialization fails. ```rust pub fn get(&self, key: &str) -> Option ``` -------------------------------- ### Session Store Initialization and Basic Usage Source: https://docs.rs/axum_session/latest/axum_session/databases/type.SessionAnySessionStore_search=u32+-%3E+bool Demonstrates how to initialize the SessionStore with a default configuration and perform basic operations like storing session data. ```APIDOC ## Session Store Initialization and Basic Usage ### Description Initializes the `SessionStore` with default configuration and demonstrates storing session data. ### Method Initialization and `store_session` ### Endpoint N/A (In-memory/Database operations) ### Parameters N/A for initialization example. ### Request Example ```rust use axum_session::{SessionNullPool, SessionConfig, SessionStore, SessionData}; use uuid::Uuid; let config = SessionConfig::default(); let session_store = SessionStore::::new(None, config.clone()).await.unwrap(); let token = Uuid::new_v4(); let session_data = SessionData::new(token, true, &config); async { let _ = session_store.store_session(&session_data).await.unwrap(); }; ``` ### Response #### Success Response (200) N/A (Operations are typically asynchronous and return results) #### Response Example N/A ``` -------------------------------- ### Get Data from Session HashMap in Rust Source: https://docs.rs/axum_session/latest/axum_session/databases/type.SessionNullSession The `get` function retrieves data from the session's `HashMap` using a specified key. It returns an `Option`, deserializing the data if found and valid, or `None` if the key doesn't exist or deserialization fails. ```rust pub fn get(&self, key: &str) -> Option // Example usage: let id = session.get("user-id").unwrap_or(0); ``` -------------------------------- ### SessionStore Implementations Source: https://docs.rs/axum_session/latest/axum_session/databases/any_db/type.SessionAnySessionStore_search=u32+-%3E+bool Core methods for initializing, managing, and interacting with the session store. ```APIDOC ## impl SessionStore This block details the implementation of the `SessionStore` for various database pool types `T` that satisfy the `DatabasePool` trait and other necessary bounds. ### `new(client: Option, config: SessionConfig) -> Result` #### Description Constructs a new `SessionStore`. If a `client` is provided, it ensures the necessary database table for sessions exists. If `client` is `None`, it initializes an in-memory session store. #### Method `async fn new` #### Parameters * **`client`** (`Option`) - The database connection pool. `None` for in-memory storage. * **`config`** (`SessionConfig`) - The configuration for the session store. #### Returns * `Result` - A `SessionStore` instance on success, or a `SessionError` on failure. #### Examples ```rust use axum_session::{SessionNullPool, SessionConfig, SessionStore}; let config = SessionConfig::default(); let session_store = SessionStore::::new(None, config).await.unwrap(); ``` ### `create_filter(client: &Option, config: &SessionConfig) -> Result` #### Description (Available on `key-store` feature only) Initializes and populates a Bloom filter used for efficient session ID tracking. #### Method `async fn create_filter` #### Parameters * **`client`** (`&Option`) - A reference to the database client. * **`config`** (`&SessionConfig`) - A reference to the session configuration. #### Returns * `Result` - The created `CountingBloomFilter` on success, or a `SessionError` on failure. ### `is_persistent(&self) -> bool` #### Description Checks if the session store is configured to use a persistent database backend. #### Method `fn is_persistent` #### Returns * `bool` - `true` if a `client` is present (persistent), `false` otherwise (in-memory). #### Examples ```rust use axum_session::{SessionNullPool, SessionConfig, SessionStore}; let config = SessionConfig::default(); let session_store = SessionStore::::new(None, config).await.unwrap(); let is_persistent = session_store.is_persistent(); ``` ### `cleanup(&self) -> Result, SessionError>` #### Description Removes expired sessions from the persistent database. If no database client is configured, this operation is a no-op. #### Method `async fn cleanup` #### Returns * `Result, SessionError>` - A `Vec` of expired session IDs removed on success, or a `SessionError` if a database operation fails. #### Errors * `SessionError::Sqlx`: If there's a database connection issue or permission error. #### Examples ```rust use axum_session::{SessionNullPool, SessionConfig, SessionStore}; let config = SessionConfig::default(); let session_store = SessionStore::::new(None, config).await.unwrap(); async { let _ = session_store.cleanup().await.unwrap(); }; ``` ### `count(&self) -> Result` #### Description Retrieves the total number of active sessions stored in the database. Returns 0 if no database client is configured. #### Method `async fn count` #### Returns * `Result` - The count of sessions on success, or a `SessionError` if a database operation fails. #### Errors * `SessionError::Sqlx`: If there's a database connection issue or permission error. #### Examples ```rust use axum_session::{SessionNullPool, SessionConfig, SessionStore}; let config = SessionConfig::default(); let session_store = SessionStore::::new(None, config).await.unwrap(); async { let count = session_store.count().await.unwrap(); }; ``` ### `load_session(&self, cookie_value: String) -> Result, SessionError>` #### Description (Internal function) Loads session data from the database using a session ID (typically from a cookie). #### Method `async fn load_session` #### Parameters * **`cookie_value`** (`String`) - The session ID string to look up. #### Returns * `Result, SessionError>` - An `Option` containing `SessionData` if found, or `None` if not found. Returns a `SessionError` on database or deserialization issues. #### Errors * `SessionError::Sqlx`: If there's a database connection issue or permission error. * `SessionError::SerdeJson`: If session data deserialization fails. #### Examples ```rust use axum_session::{SessionNullPool, SessionConfig, SessionStore}; use uuid::Uuid; let config = SessionConfig::default(); let session_store = SessionStore::::new(None, config).await.unwrap(); let token = Uuid::new_v4(); async { let session_data = session_store.load_session(token.to_string()).await.unwrap(); }; ``` ### `store_session(&self, session: &SessionData) -> Result<(), SessionError>` #### Description (Internal function) Stores or updates session data in the database. #### Method `async fn store_session` #### Parameters * **`session`** (`&SessionData`) - A reference to the `SessionData` to store. #### Returns * `Result<(), SessionError>` - `Ok(())` on success, or a `SessionError` if a database or serialization issue occurs. #### Errors * `SessionError::Sqlx`: If there's a database connection issue or permission error. * `SessionError::SerdeJson`: If session data serialization fails. ``` -------------------------------- ### Initialize Axum SessionStore with Database Client Source: https://docs.rs/axum_session/latest/src/axum_session/session_store.rs Provides the `new` constructor for `SessionStore`. This function initializes the store, optionally creates the necessary database table if a client is provided, and preloads session IDs into the bloom filter if enabled and a database client exists. ```rust impl SessionStore where T: DatabasePool + Clone + Debug + Sync + Send + 'static, { /// Constructs a New `SessionStore` and Creates the Database Table /// needed for the Session if it does not exist if client is not `None`. /// /// # Examples /// ```rust ignore /// use axum_session::{SessionNullPool, SessionConfig, SessionStore}; /// /// let config = SessionConfig::default(); /// let session_store = SessionStore::::new(None, config).await.unwrap(); /// ``` /// #[inline] pub async fn new(client: Option, config: SessionConfig) -> Result { if let Some(client) = &client { client.initiate(&config.database.table_name).await?; } // If we have a database client then lets also get any SessionId's that Exist within the database // that are not yet expired. #[cfg(feature = "key-store")] let filter = Self::create_filter(&client, &config).await?; Ok(Self { client, inner: Default::default(), config, timers: Arc::new(RwLock::new(SessionTimers { // the first expiry sweep is scheduled one lifetime from start-up last_expiry_sweep: Utc::now() + Duration::try_hours(1).unwrap_or_default(), // the first expiry sweep is scheduled one lifetime from start-up last_database_expiry_sweep: Utc::now() + Duration::try_hours(6).unwrap_or_default(), })), #[cfg(feature = "key-store")] filter: Arc::new(RwLock::new(filter)), }) } /// Used to create and Fill the Filter. #[cfg(feature = "key-store")] pub(crate) async fn create_filter( client: &Option, config: &SessionConfig, ) -> Result { let mut filter = FilterBuilder::new( config.memory.filter_expected_elements, config.memory.filter_false_positive_probability, ) .build_counting_bloom_filter(); if config.memory.use_bloom_filters { // If client exist then lets preload the id's within the database so the filter is accurate. if let Some(client) = &client { let ids = client.get_ids(&config.database.table_name).await?; ids.iter().for_each(|id| filter.add(id.as_bytes())); } } Ok(filter) } /// Checks if the database is in persistent mode. /// /// Returns true if client is Some(). /// /// # Examples /// ```rust ignore ``` -------------------------------- ### Example: Add Original Cookie Source: https://docs.rs/axum_session/latest/axum_session/sec/signed/struct.AdditionalSignedJar_search=std%3A%3Avec Shows how to use `add_original` to add a cookie. The example verifies that adding an original cookie increases the total number of cookies in the jar but does not affect the delta count, which is important for tracking changes. ```rust use cookie::{CookieJar, Cookie, Key}; let key = Key::generate(); let mut jar = CookieJar::new(); jar.message_signed_mut(&key, "".to_owned()).add_original(("name", "value")); assert_eq!(jar.iter().count(), 1); assert_eq!(jar.delta().count(), 0); ``` -------------------------------- ### SessionStore Initialization Source: https://docs.rs/axum_session/latest/axum_session/struct.SessionStore_search=std%3A%3Avec Demonstrates how to create a new SessionStore instance with default configuration and no database client. ```APIDOC ## POST /initialize-session-store ### Description Constructs a new `SessionStore` and creates the necessary database table for sessions if it doesn't exist. This is typically done during application startup. ### Method POST ### Endpoint /initialize-session-store ### Parameters #### Query Parameters - **client** (Option) - Optional - The database client to use for persistent sessions. If `None`, sessions will be stored in memory. - **config** (SessionConfig) - Required - The configuration settings for the session management. ### Request Body ```json { "client": null, "config": { "cookie_name": "session_id", "cookie_secure": false, "cookie_http_only": true, "cookie_same_site": "Lax", "cookie_path": "/", "cookie_max_age": null, "session_lifetime": 1800, "key_storage": false } } ``` ### Response #### Success Response (200) - **session_store** (SessionStore) - The newly created SessionStore instance. #### Response Example ```json { "message": "SessionStore initialized successfully" } ``` ``` -------------------------------- ### Type Conversion (TryFrom/TryInto) Source: https://docs.rs/axum_session/latest/axum_session/config/struct.CookieAndHeaderConfig_search= Provides documentation for the `TryFrom` and `TryInto` traits, enabling fallible type conversions. It details the `try_from` and `try_into` methods and their associated error types. ```APIDOC ## Type Conversion (TryFrom/TryInto) ### Description Provides methods for fallible type conversions between types. ### Methods #### `fn try_from(value: U) -> Result>::Error>` Performs the conversion from type `U` to type `T`. #### `fn try_into(self) -> Result>::Error>` Performs the conversion from the current type `T` to type `U`. ### Error Type #### `type Error = >::Error` The type returned in the event of a conversion error. ``` -------------------------------- ### TypeId Method Source: https://docs.rs/axum_session/latest/axum_session/session_store/struct.SessionStore_search=u32+-%3E+bool Gets the TypeId of an instance. ```APIDOC ## TypeId Method ### Description Gets the `TypeId` of `self`. ### Method #### `type_id(&self) -> TypeId` ``` -------------------------------- ### Generic Type Implementations Source: https://docs.rs/axum_session/latest/axum_session/struct.AdditionalSignedJar_search=u32+-%3E+bool This section covers blanket implementations for generic types, including Any, Borrow, BorrowMut, From, Instrument, Into, Same, TryFrom, TryInto, VZip, and WithSubscriber. ```APIDOC ## Blanket Implementations ### impl Any for T where T: 'static + ?Sized #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. ### impl Borrow for T where T: ?Sized #### fn borrow(&self) -> &T Immutably borrows from an owned value. ### impl BorrowMut for T where T: ?Sized #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. ### impl From for T #### fn from(t: T) -> T Returns the argument unchanged. ### impl Instrument for T #### fn instrument(self, span: Span) -> Instrumented Instruments this type with the provided `Span`, returning an `Instrumented` wrapper. #### fn in_current_span(self) -> Instrumented Instruments this type with the current `Span`, returning an `Instrumented` wrapper. ### impl Into for T where U: From #### fn into(self) -> U Calls `U::from(self)`. ### impl Same for T #### type Output = T Should always be `Self` ### impl TryFrom for T where U: Into #### type Error = Infallible The type returned in the event of a conversion error. #### fn try_from(value: U) -> Result>::Error> Performs the conversion. ### impl TryInto for T where U: TryFrom #### type Error = >::Error The type returned in the event of a conversion error. #### fn try_into(self) -> Result>::Error> Performs the conversion. ### impl VZip for T where V: MultiLane #### fn vzip(self) -> V ### impl WithSubscriber for T #### fn with_subscriber(self, subscriber: S) -> WithDispatch where S: Into Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. #### fn with_current_subscriber(self) -> WithDispatch Attaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. ``` -------------------------------- ### Rust: Implement From and Into Traits for Conversions Source: https://docs.rs/axum_session/latest/axum_session/databases/null/struct.SessionNullPool_search=std%3A%3Avec Demonstrates the blanket implementations for `From` for `T` and `Into` for `T` where `U: From`. These facilitate type conversions. ```rust impl From for T { fn from(t: T) -> T // Returns the argument unchanged. } impl Into for T where U: From, { fn into(self) -> U // Calls `U::from(self)`. } ``` -------------------------------- ### Get and Verify Cookie in Rust Source: https://docs.rs/axum_session/latest/src/axum_session/sec/signed.rs The `get` function retrieves a cookie by name from the parent `CookieJar` and then verifies its authenticity and integrity using the `verify` method. It returns the verified cookie if found and valid, otherwise `None`. This ensures that only trusted cookies are returned. ```rust /// Returns a reference to the `Cookie` inside this jar with the name `name` /// and verifies the authenticity and integrity of the cookie's value, /// returning a `Cookie` with the authenticated value. If the cookie cannot /// be found, or the cookie fails to verify, `None` is returned. /// /// # Example /// /// ```rust ignore /// use cookie::{CookieJar, Cookie, Key}; /// /// let key = Key::generate(); /// let jar = CookieJar::new(); /// assert!(jar.message_signed(&key, "".to_owned()).get("name").is_none()); /// /// let mut jar = jar; /// let mut signed_jar = jar.message_signed_mut(&key, "".to_owned()); /// signed_jar.add(Cookie::new("name", "value")); /// assert_eq!(signed_jar.get("name").unwrap().value(), "value"); /// ``` pub fn get(&self, name: &str) -> Option> { self.parent .borrow() .get(name) .and_then(|c| self.verify(c.clone())) } ``` -------------------------------- ### SessionConfig Initialization Source: https://docs.rs/axum_session/latest/axum_session/struct.SessionConfig_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to create a default SessionConfig and customize it. ```APIDOC ## SessionConfig Initialization ### `new()` Creates a default configuration of `SessionConfig`. #### Example ```rust use axum_session::SessionConfig; let config = SessionConfig::default(); ``` ### `with_id_generator(self, id_generator: impl IdGenerator) -> Self` Set a custom session ID generator. By default, session IDs are UUIDs, but this allows for custom session ID formats. #### Example ```rust use axum_session::{IdGenerator, SessionConfig}; #[derive(Debug)] struct CustomSessionId(); impl CustomSessionId { pub fn new() -> Self { CustomSessionId() } } impl IdGenerator for CustomSessionId { fn generate(&self) -> String { // Return a custom Session ID... "something random".into() } } let config = SessionConfig::default().with_id_generator(CustomSessionId::new()); ``` ``` -------------------------------- ### TryFrom and TryInto Conversions Source: https://docs.rs/axum_session/latest/axum_session/config/struct.CookieAndHeaderConfig_search=u32+-%3E+bool This section details the `TryFrom` and `TryInto` traits, which allow for fallible conversions between types. It includes methods for performing these conversions and defining the associated error types. ```APIDOC ## TryFrom and TryInto Conversions ### Description Provides methods for fallible type conversions. ### Methods #### `TryFrom` trait ##### `fn try_from(value: U) -> Result>::Error>` Performs the conversion from type `U` to type `T`. #### `TryInto` trait ##### `type Error = >::Error` Defines the error type returned when a conversion fails. ##### `fn try_into(self) -> Result>::Error>` Performs the conversion from type `T` to type `U`. ``` -------------------------------- ### Example: Verify Cookie Authenticity Source: https://docs.rs/axum_session/latest/axum_session/sec/signed/struct.AdditionalSignedJar_search=std%3A%3Avec Demonstrates the usage of the `verify` method for authenticating cookies. It shows how to generate a key, create a cookie jar, sign a cookie, and then verify its authenticity. The example highlights that a plain cookie will fail verification, while a properly signed one will succeed. ```rust use cookie::{CookieJar, Cookie, Key}; let key = Key::generate(); let mut jar = CookieJar::new(); assert!(jar.message_signed(&key, "".to_owned()).get("name").is_none()); jar.message_signed_mut(&key, "".to_owned()).add(("name", "value")); assert_eq!(jar.message_signed(&key, "".to_owned()).get("name").unwrap().value(), "value"); let plain = jar.get("name").cloned().unwrap(); assert_ne!(plain.value(), "value"); let verified = jar.message_signed(&key, "".to_owned()).verify(plain).unwrap(); assert_eq!(verified.value(), "value"); let plain = Cookie::new("plaintext", "hello"); assert!(jar.message_signed(&key, "".to_owned()).verify(plain).is_none()); ``` -------------------------------- ### Initiate Database Table Creation in Rust Source: https://docs.rs/axum_session/latest/axum_session/databases/database/trait.DatabasePool_search= The `initiate` method is called to create the session table in the database. It takes the table name as input and returns a `Result` indicating success or a `DatabaseError`. This is crucial for setting up the database schema before session operations. ```rust fn initiate<'life0, 'life1, 'async_trait>( &'life0 self, table_name: &'life1 str, ) -> Pin> + Send + 'async_trait>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait; ``` -------------------------------- ### GET /websites/rs_axum_session/get_ids Source: https://docs.rs/axum_session/latest/axum_session/databases/any_db/struct.SessionAnyPool_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves all IDs from the database for the last run. Propagates errors if they occur. ```APIDOC ## GET /websites/rs_axum_session/get_ids ### Description Retrieves all IDs from the database for the last run. Propagates errors if they occur. ### Method GET ### Endpoint /websites/rs_axum_session/get_ids ### Parameters #### Query Parameters - **table_name** (string) - Required - The name of the table to retrieve IDs from. ### Response #### Success Response (200) - **ids** (array of strings) - A list of IDs retrieved from the database. #### Response Example ```json { "ids": [ "id1", "id2", "id3" ] } ``` #### Error Response (500) - **error** (string) - A message describing the database error. #### Error Response Example ```json { "error": "DatabaseError: Failed to connect to database" } ``` ``` -------------------------------- ### Rust Type Conversion with TryFrom and TryInto Source: https://docs.rs/axum_session/latest/axum_session/config/struct.CookieAndHeaderConfig_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates Rust's `TryFrom` and `TryInto` traits for fallible type conversions. These traits provide methods like `try_from` and `try_into` that return a `Result` to handle potential conversion errors. ```rust /// Performs the conversion. fn try_from(value: U) -> Result>::Error>; /// The type returned in the event of a conversion error. type Error = >::Error; /// Performs the conversion. fn try_into(self) -> Result>::Error>; ``` -------------------------------- ### Get Type ID Source: https://docs.rs/axum_session/latest/axum_session/databases/any_db/struct.SessionAnyPool_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the unique TypeId of an object. This is part of the Any trait implementation. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Initialize SessionLayer in Rust Source: https://docs.rs/axum_session/latest/axum_session/layer/struct.SessionLayer_search= Demonstrates how to create a SessionLayer for Axum applications. This involves configuring session settings, initializing a session store (using SessionNullPool as an example), and then constructing the SessionLayer with the store. This layer is essential for enabling session management in Axum services. ```rust use axum_session::{SessionNullPool, SessionConfig, SessionStore, SessionLayer}; use uuid::Uuid; let config = SessionConfig::default(); let session_store = SessionStore::::new(None, config).await.unwrap(); let layer = SessionLayer::new(session_store); ``` -------------------------------- ### Get Session ID in Rust Source: https://docs.rs/axum_session/latest/axum_session/session/struct.Session_search= Returns the unique session ID string for the current session. ```rust pub fn get_session_id(&self) -> String { // ... implementation details ... } ```