Git Product home page Git Product logo

tower-sessions's Introduction

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:

  • Pluggable Storage Backends: Bring your own backend simply by implementing the SessionStore trait, fully decoupling sessions from their storage.
  • Minimal Overhead: Sessions are only loaded from their backing stores when they're actually used and only in e.g. the handler they're used in. That means this middleware can be installed anywhere in your route graph with minimal overhead.
  • An axum Extractor for Session: Applications built with axum can use Session as an extractor directly in their handlers. This makes using sessions as easy as including Session in your handler.
  • Simple Key-Value Interface: Sessions offer a key-value interface that supports native Rust types. So long as these types are Serialize and can be converted to JSON, it's straightforward to insert, get, and remove any value.
  • Strongly-Typed Sessions: Strong typing guarantees are easy to layer on top of this foundational key-value interface.

This crate's session implementation is inspired by the Django sessions middleware and it provides a transliteration of those semantics.

Session stores

Session data persistence is managed by user-provided types that implement SessionStore. What this means is that applications can and should implement session stores to fit their specific needs.

That said, a number of session store implmentations already exist and may be useful starting points.

Crate Persistent Description
tower-sessions-dynamodb-store Yes DynamoDB session store
tower-sessions-firestore-store Yes Firestore session store
tower-sessions-libsql-store Yes libSQL session store
tower-sessions-mongodb-store Yes MongoDB session store
tower-sessions-moka-store No Moka session store
tower-sessions-redis-store Yes Redis via fred session store
tower-sessions-rorm-store Yes SQLite, Postgres and Mysql session store provided by rorm
tower-sessions-rusqlite-store Yes Rusqlite session store
tower-sessions-sled-store Yes Sled session store
tower-sessions-sqlx-store Yes SQLite, Postgres, and MySQL session stores
tower-sessions-surrealdb-store Yes SurrealDB session store

Have a store to add? Please open a PR adding it.

User session management

To facilitate authentication and authorization, we've built axum-login on top of this crate. Please check it out if you're looking for a generalized auth solution.

๐Ÿ“ฆ Install

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

[dependencies]
tower-sessions = "0.12.2"

๐Ÿคธ Usage

axum Example

use std::net::SocketAddr;

use axum::{response::IntoResponse, routing::get, Router};
use serde::{Deserialize, Serialize};
use time::Duration;
use tower_sessions::{Expiry, MemoryStore, Session, SessionManagerLayer};

const COUNTER_KEY: &str = "counter";

#[derive(Default, Deserialize, Serialize)]
struct Counter(usize);

async fn handler(session: Session) -> impl IntoResponse {
    let counter: Counter = session.get(COUNTER_KEY).await.unwrap().unwrap_or_default();
    session.insert(COUNTER_KEY, counter.0 + 1).await.unwrap();
    format!("Current count: {}", counter.0)
}

#[tokio::main]
async fn main() {
    let session_store = MemoryStore::default();
    let session_layer = SessionManagerLayer::new(session_store)
        .with_secure(false)
        .with_expiry(Expiry::OnInactivity(Duration::seconds(10)));

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

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

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

Note

See the crate documentation for more usage information.

๐Ÿฆบ Safety

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

๐Ÿ›Ÿ Getting Help

We've put together a number of examples to help get you started. You're also welcome to open a discussion and ask additional questions you might have.

๐Ÿ‘ฏ Contributing

We appreciate all kinds of contributions, thank you!

tower-sessions's People

Contributors

and-reas-se avatar beckend avatar bekriebel avatar calum4 avatar cole-h avatar czocher avatar daybowbow-dev avatar dependabot[bot] avatar dominicwrege avatar imbolc avatar justmangoou avatar katze864 avatar martinetd avatar maxcountryman avatar myomikron avatar nul-reference avatar patte avatar plasticbox avatar rynov avatar thallada avatar weiznich avatar wt avatar zatzou avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.