tower-sessions

🥠 Sessions as a `tower` and `axum` middleware.

🎨 Overview

This crate provides sessions, key-value pairs associated with a site visitor, as a tower middleware.

It offers:

📦 Install

To use the crate in your project, add the following to your Cargo.toml file:

toml [dependencies] tower-sessions = "0.1.0"

🤸 Usage

axum Example

```rust use std::net::SocketAddr;

use axum::{ errorhandling::HandleErrorLayer, response::IntoResponse, routing::get, BoxError, Router, }; use http::StatusCode; use serde::{Deserialize, Serialize}; use tower::ServiceBuilder; use towersessions::{time::Duration, MemoryStore, Session, SessionManagerLayer};

const COUNTER_KEY: &str = "counter";

[derive(Default, Deserialize, Serialize)]

struct Counter(usize);

[tokio::main]

async fn main() { let sessionstore = MemoryStore::default(); let sessionservice = ServiceBuilder::new() .layer(HandleErrorLayer::new(|: BoxError| async { StatusCode::BADREQUEST })) .layer( SessionManagerLayer::new(sessionstore) .withsecure(false) .withmaxage(Duration::seconds(10)), );

let app = Router::new()
    .route("/", get(handler))
    .layer(session_service);

let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
axum::Server::bind(&addr)
    .serve(app.into_make_service())
    .await
    .unwrap();

}

async fn handler(session: Session) -> impl IntoResponse { let counter: Counter = session .get(COUNTERKEY) .expect("Could not deserialize.") .unwrapor_default();

session
    .insert(COUNTER_KEY, counter.0 + 1)
    .expect("Could not serialize.");

format!("Current count: {}", counter.0)

} ```

You can find this example as well as other example projects in the example directory.

See the crate documentation for more usage information.

🦺 Safety

This crate uses #![forbid(unsafe_code)] to ensure everything is implemented in 100% safe Rust.

👯 Contributing

We appreciate all kinds of contributions, thank you!