• Stars
    star
    214
  • Rank 184,092 (Top 4 %)
  • Language
    Rust
  • License
    MIT License
  • Created about 1 year ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸ₯  Sessions as a `tower` and `axum` middleware.

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-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.0"

🀸 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!

More Repositories

1

flask-login

Flask user session management.
Python
3,532
star
2

axum-login

πŸͺͺ User identification, authentication, and authorization for Axum.
Rust
550
star
3

flask-bcrypt

Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application.
Python
323
star
4

flask-uploads

File uploads for Flask.
Python
208
star
5

flask-seasurf

SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF).
Python
190
star
6

logmon

Realtime log reader in Flask
Python
176
star
7

flake

Decentralized, k-ordered unique IDs in Clojure
Clojure
142
star
8

atomos

Atomic primitives for Python.
Python
119
star
9

warc-parquet

πŸ—„οΈ A simple CLI for converting WARC to Parquet.
Rust
103
star
10

axum-sessions

πŸ₯  Cookie-based sessions for Axum via async-session.
Rust
74
star
11

aquamarine

A demo of zero-downtime deploys with Docker Compose and Traefik
Shell
53
star
12

irctk

A simple framework for writing IRC applications
Python
44
star
13

quanta

Distributed CRDT of sparse integer vectors.
Clojure
33
star
14

forma

🐚 An opinionated SQL formatter.
Rust
27
star
15

axum-messages

πŸ›ŽοΈ One-time notification messages for Axum.
Rust
26
star
16

tower-sessions-stores

πŸšƒ Previously bundled session stores for `tower-sessions`.
Rust
23
star
17

hyperlight

A performance-focused HTTP reverse proxy
Clojure
19
star
18

flask-themes

Flask Themes
Python
19
star
19

cryptotrade

A simple Python API wrapper for Bitcoin trading platforms such as MtGox and TradeHill
Python
14
star
20

flog

A blog written with Flask
Python
9
star
21

flask-wepay

A Flask wrapper for WePay's Python API
Python
8
star
22

blizzard

HTTP unique ID generation service
Clojure
8
star
23

st

Fast and simple statistics on the command line.
Rust
6
star
24

markov-domains

Finds available domains using Markov chains.
Clojure
6
star
25

nautilus

User authentication and management service
Clojure
5
star
26

yelp-api

A wrapper for Yelp's public API
PHP
4
star
27

affinis

An IRC library for Clojure.
Clojure
4
star
28

wtforms

Python
4
star
29

rauth

A Python library for OAuth 1.0/a, 2.0, and Ofly
Python
4
star
30

simpleirc

An IRC connection layer written in Python.
Python
4
star
31

headers-accept

🀝 The missing `Accept` implementation for `headers::Header`.
Rust
4
star
32

pyxine-branch

Branch of the Python extension for xine
Python
3
star
33

fluyt

ClojureScript HTTP requests
Clojure
3
star
34

cozy

A modern Node API template for the weary traveller
JavaScript
3
star
35

ewt

EDN Web Tokens
Clojure
3
star
36

dotfiles

Development environment configuration files.
Shell
3
star
37

flask-simpleoauth

A dead simple OAuth 1.0a provider in Flask
Python
3
star
38

simpleoauth

Simple, correct OAuth 1.0 and 2.0 signing methods.
Python
2
star
39

kaa

Kaa is the resident IRC bot on VoxInfinitus, written with IrcTK
Python
2
star
40

voxinfinitus

Basic Django apps providing CMS and blog functionality for Voxi
Python
2
star
41

mage

A Clojure-like Lisp.
Python
2
star
42

tasker

simple task manager
Python
2
star
43

ChatOnMacWebAPI-Swift

Swift
2
star
44

chatter

Chatter is a quick and dirty realtime chat application written in Flask
Python
2
star
45

bitpit-https-bridge

A simple Flask app to bridge the unsecured service with a secured page
Python
1
star
46

conceptis.org

My personal site and blog
Python
1
star
47

primes

A simple Clojure program for generating a multiplication table of primes
Clojure
1
star
48

konvej

Httpbin in Clojure.
Clojure
1
star
49

atrium

HTTP Authentication Service
1
star
50

clasp

A dead simple routing DSL for Clojure's ring.
Clojure
1
star
51

celeb

Incomplete Flask gallery project, now abandoned
Python
1
star
52

accord

A simple OAuth 1.0/a, 2.0 consumer client for Clojure.
Clojure
1
star
53

mtgox-trader

BitCoin MTGox trading bot/library
Python
1
star
54

locksmithing

Lock-free, concurrent data structure experiments.
Clojure
1
star