#axum #tower #sq-lx #session

axum_database_sessions

Library to Provide a SQLx Database Session management layer

17 releases (9 stable)

Uses new Rust 2021

new 3.0.2 Jun 26, 2022
2.1.0 Jun 14, 2022
1.2.0 May 17, 2022
1.0.0 Mar 31, 2022
0.3.0 Mar 17, 2022

#90 in Database interfaces

Download history 34/week @ 2022-03-07 59/week @ 2022-03-14 36/week @ 2022-03-21 27/week @ 2022-03-28 59/week @ 2022-04-04 8/week @ 2022-04-11 14/week @ 2022-04-18 34/week @ 2022-04-25 77/week @ 2022-05-02 45/week @ 2022-05-09 273/week @ 2022-05-16 68/week @ 2022-05-23 135/week @ 2022-05-30 63/week @ 2022-06-06 51/week @ 2022-06-13 78/week @ 2022-06-20

344 downloads per month
Used in axum_sessions_auth

MIT license

63KB
884 lines

Axum_database_Sessions

Library to Provide a Sqlx Database Session management layer.

You must choose only one of ['postgres', 'mysql', 'sqlite'] features to use this library.

https://crates.io/crates/axum_database_sessions Docs

Install

Axum Database Sessions uses tokio runtime along with sqlx; it supports native-tls and rustls TLS backends. When adding the dependency, you must chose a database feature that is DatabaseType and a tls backend. You can only choose one database type and one TLS Backend.

sqlx current version used is 0.6.0

# Cargo.toml
[dependencies]
# Postgres + rustls
axum_database_sessions = { version = "3.0.2", features = [ "postgres", "rustls"] }

Cargo Feature Flags

sqlite: Sqlx support for the self-contained SQLite database engine. postgres: Sqlx support for the Postgres database server. mysql: Sqlx support for the MySQL/MariaDB database server. native-tls: Use the tokio runtime and native-tls TLS backend. rustls: Use the tokio runtime and rustls TLS backend.

Example

use sqlx::{ConnectOptions, postgres::{PgPoolOptions, PgConnectOptions}};
use std::net::SocketAddr;
use axum_database_sessions::{AxumSession, AxumSessionConfig, AxumSessionStore, AxumSessionLayer};
use axum::{
    Router,
    routing::get,
};

#[tokio::main]
async fn main() {

    let poll = connect_to_database().await.unwrap();

    //This Defaults as normal Cookies.
    //To enable Private cookies for integrity, and authenticity please check the next Example.
    let session_config = AxumSessionConfig::default()
        .with_table_name("test_table");

    let session_store = AxumSessionStore::new(Some(poll.clone().into()), session_config);
    session_store.migrate().await.unwrap();

    // build our application with some routes
    let app = Router::new()
        .route("/greet", get(greet))
        .layer(AxumSessionLayer::new(session_store));

    // run it
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    tracing::debug!("listening on {}", addr);
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();
}

async fn greet(session: AxumSession) -> String {
    let mut count: usize = session.get("count").await.unwrap_or(0);

    count += 1;
    session.set("count", count).await;

    count.to_string()
}

async fn connect_to_database() -> anyhow::Result<sqlx::Pool<sqlx::Postgres>> {
    // ...
    unimplemented!()
}

To enable private cookies for confidentiality, integrity, and authenticity. When a Key is set it will automatically set the Cookie into an encypted Private cookie which both protects the cookies data from prying eye's it also ensures the authenticity of the cookie.

Example

use sqlx::{ConnectOptions, postgres::{PgPoolOptions, PgConnectOptions}};
use std::net::SocketAddr;
use axum_database_sessions::{AxumSession, AxumSessionConfig, AxumSessionStore, AxumSessionLayer, AxumSessionMode, Key};
use axum::{
    Router,
    routing::get,
};

#[tokio::main]
async fn main() {
    let session_config = AxumSessionConfig::default()
        .with_table_name("test_table")
        // 'Key::generate()' will generate a new key each restart of the server.
        // If you want it to be more permanent then generate and set it to a config file.
        // If with_key() is used it will set all cookies as private, which guarantees integrity, and authenticity.
        .with_key(Key::generate());

    let session_store = AxumSessionStore::new(None, session_config);
    session_store.migrate().await.unwrap();

    // build our application with some routes
    let app = Router::new()
        .route("/greet", get(greet))
        .layer(AxumSessionLayer::new(session_store));

    // run it
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    tracing::debug!("listening on {}", addr);
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();
}

To use Axum_database_session in non_persistant mode Set the client to None.

Example

use sqlx::{ConnectOptions, postgres::{PgPoolOptions, PgConnectOptions}};
use std::net::SocketAddr;
use axum_database_sessions::{AxumSession, AxumSessionConfig, AxumSessionStore, AxumSessionLayer};
use axum::{
    Router,
    routing::get,
};

#[tokio::main]
async fn main() {
    let session_config = AxumSessionConfig::default()
        .with_table_name("test_table");

    let session_store = AxumSessionStore::new(None, session_config);

    // build our application with some routes
    let app = Router::new()
        .route("/greet", get(greet))
        .layer(AxumSessionLayer::new(session_store));

    // run it
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    tracing::debug!("listening on {}", addr);
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();
}

async fn greet(session: AxumSession) -> String {
    let mut count: usize = session.get("count").await.unwrap_or(0);

    count += 1;
    session.set("count", count).await;

    count.to_string()
}

To use Axum_database_session with session mode set as Storable.

Example

use sqlx::{ConnectOptions, postgres::{PgPoolOptions, PgConnectOptions}};
use std::net::SocketAddr;
use axum_database_sessions::{AxumSession, AxumSessionConfig, AxumSessionStore, AxumSessionLayer, AxumSessionMode};
use axum::{
    Router,
    routing::get,
};

#[tokio::main]
async fn main() {
    let session_config = AxumSessionConfig::default()
        .with_table_name("test_table").with_mode(AxumSessionMode::AcceptedOnly);

    let session_store = AxumSessionStore::new(None, session_config);
    session_store.migrate().await.unwrap();

    // build our application with some routes
    let app = Router::new()
        .route("/greet", get(greet))
        .layer(AxumSessionLayer::new(session_store));

    // run it
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    tracing::debug!("listening on {}", addr);
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();
}

//No need to set the sessions accepted or not with gdpr mode disabled
async fn greet(session: AxumSession) -> String {
    let mut count: usize = session.get("count").await.unwrap_or(0);

    // Allow the Session data to be keep in memory and the database for the lifetime.
    session.set_store(true).await;
    count += 1;
    session.set("count", count).await;

    count.to_string()
}

Help

If you need help with this library or have suggestions please go to our Discord Group

Dependencies

~13–26MB
~506K SLoC