2 stable releases

2.0.0 Dec 22, 2020
1.0.0 Jul 31, 2020

#239 in HTTP server

MIT/Apache

30KB
111 lines

async-mongodb-session

An async-session implementation for MongoDB

Installation

$ cargo add async-mongodb-session

Overview

This library utilises the document expiration feature in mongodb and is based on specific clock time.

The expiry index is applied to the collection when a new session object is created.

As document expiration is a background task some stale sessions may be present in the database but won't be returned by this library.

Example with tide

Create an HTTP server that keep track of user visits in the session.

#[async_std::main]
async fn main() -> tide::Result<()> {
    tide::log::start();
    let mut app = tide::new();

    app.with(tide::sessions::SessionMiddleware::new(
        MongodbSessionStore::new("mongodb://127.0.0.1:27017", "db_name", "collection").await?,
        std::env::var("TIDE_SECRET")
            .expect(
                "Please provide a TIDE_SECRET value of at \
                      least 32 bytes in order to run this example",
            )
            .as_bytes(),
    ));

    app.with(tide::utils::Before(
        |mut request: tide::Request<()>| async move {
            let session = request.session_mut();
            let visits: usize = session.get("visits").unwrap_or_default();
            session.insert("visits", visits + 1).unwrap();
            request
        },
    ));

    app.at("/").get(|req: tide::Request<()>| async move {
        let visits: usize = req.session().get("visits").unwrap();
        Ok(format!("you have visited this website {} times", visits))
    });

    app.at("/reset")
        .get(|mut req: tide::Request<()>| async move {
            req.session_mut().destroy();
            Ok(tide::Redirect::new("/"))
        });

    app.listen("127.0.0.1:8080").await?;

    Ok(())
}

Test

The tests rely on an running instance of mongodb either on your local machine or remote. The quickest way to get an instance up and running locally is using the following docker command:

$ docker run -d -p 27017:27017 -v ~/data:/data/db mongo:4.2

The tests can then be executed with

$ cargo test

The default settings for the mongodb instance is set to 127.0.0.1:27017 but that can be over ridden by setting the HOST and PORT environment variables.

$ HOST=mymongo.com PORT=1234 cargo test

Safety

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

Contributing

Want to join us? Check out our "Contributing" guide and take a look at some of these issues:

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~25MB
~556K SLoC