Skip to content

Commit

Permalink
Merge pull request #18 from AaronErhardt/update-deps
Browse files Browse the repository at this point in the history
Update dependencies
  • Loading branch information
No9 authored Aug 21, 2022
2 parents 4876e78 + c45c113 commit 5e5af7e
Show file tree
Hide file tree
Showing 5 changed files with 160 additions and 131 deletions.
33 changes: 19 additions & 14 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,34 +1,39 @@
[package]
name = "async-mongodb-session"
version = "2.1.0"
version = "3.0.0"
license = "MIT OR Apache-2.0"
repository = "https://github.com/yoshuawuyts/async-mongodb-session"
documentation = "https://docs.rs/async-mongodb-session"
description = "An async-session implementation for MongoDB"
readme = "README.md"
edition = "2018"
edition = "2021"
keywords = ["tide", "web", "async", "session", "mongodb"]
categories = [
"network-programming",
"asynchronous",
"web-programming::http-server"
"web-programming::http-server",
]
authors = [
"Yoshua Wuyts <yoshuawuyts@gmail.com>",
"Irina Shestak <shestak.irina@gmail.com>",
"Anton Whalley <anton@venshare.com>",
"Javier Viola <pepoviola@gmail.com>"
"Yoshua Wuyts <yoshuawuyts@gmail.com>",
"Irina Shestak <shestak.irina@gmail.com>",
"Anton Whalley <anton@venshare.com>",
"Javier Viola <pepoviola@gmail.com>",
"Aaron Erhardt <aaron.erhardt@t-online.de>",
]

[features]
default = ["async-std-runtime"]
async-std-runtime = ["mongodb/async-std-runtime"]
tokio-runtime = ["mongodb/tokio-runtime"]

[dependencies]
mongodb = { version = "2.2.1", default-features = false, features = ["async-std-runtime", "bson-chrono-0_4"] }
# can not go higher due to dev-dependencie "tide" which requires "async-session" in version 2.0.1
async-session = "2.0.1"
async-session = "3"
mongodb = { package = "mongodb", version = "2.3", default-features = false, features = [
"bson-chrono-0_4",
] }

[dev-dependencies]
async-std = { version = "1.11.0", features = ["attributes"] }
rand = {version = "0.8.5"}
lazy_static = "1.4.0"
tide = "0.16"
async-std = { version = "1.12", features = ["attributes"] }
lazy_static = "1.4"
rand = "0.8.5"
tokio = { version = "1.20", features = ["rt"] }
11 changes: 11 additions & 0 deletions examples/tide/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "tide"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
async-mongodb-session = { path = "../../" }
tide = "0.17.0-beta.1"
async-std = "1.10"
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
extern crate async_mongodb_session;
extern crate tide;

use async_mongodb_session::MongodbSessionStore;

#[async_std::main]
Expand Down
46 changes: 21 additions & 25 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,19 @@
#![forbid(unsafe_code, future_incompatible, rust_2018_idioms)]
#![deny(missing_debug_implementations, nonstandard_style)]
#![warn(missing_docs, missing_doc_code_examples, unreachable_pub)]
#![warn(missing_docs, rustdoc::missing_doc_code_examples, unreachable_pub)]

use async_session::chrono::{Duration, Utc};
use async_session::{async_trait, Result, Session, SessionStore};
use mongodb::{bson, Collection};
use mongodb::bson::{doc, Bson, Document};
use mongodb::bson::{self, doc, Bson, Document};
use mongodb::options::{ReplaceOptions, SelectionCriteria};
use mongodb::Client;

/// A MongoDB session store.
#[derive(Debug, Clone)]
pub struct MongodbSessionStore {
client: mongodb::Client,
db: String,
coll_name: String,
collection: mongodb::Collection<Document>,
database: mongodb::Database,
}

impl MongodbSessionStore {
Expand All @@ -40,9 +38,9 @@ impl MongodbSessionStore {
/// .await?;
/// # Ok(()) }) }
/// ```
pub async fn new(uri: &str, db: &str, coll_name: &str) -> mongodb::error::Result<Self> {
pub async fn new(uri: &str, db_name: &str, coll_name: &str) -> mongodb::error::Result<Self> {
let client = Client::with_uri_str(uri).await?;
let middleware = Self::from_client(client, db, coll_name);
let middleware = Self::from_client(client, db_name, coll_name);
middleware.create_expire_index("expireAt", 0).await?;
Ok(middleware)
}
Expand All @@ -66,16 +64,17 @@ impl MongodbSessionStore {
/// let store = MongodbSessionStore::from_client(client, "db_name", "collection");
/// # Ok(()) }) }
/// ```
pub fn from_client(client: Client, db: &str, coll_name: &str) -> Self {
pub fn from_client(client: Client, db_name: &str, coll_name: &str) -> Self {
let database = client.database(db_name);
let collection = database.collection(coll_name);
Self {
client,
db: db.to_string(),
coll_name: coll_name.to_string(),
database,
collection,
}
}

/// Initialize the default expiration mechanism, based on the document expiration
/// that mongodb provides https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time.
/// that mongodb provides <https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time>.
/// The default ttl applyed to sessions without expiry is 20 minutes.
/// If the `expireAt` date field contains a date in the past, mongodb considers the document expired and will be deleted.
/// Note: mongodb runs the expiration logic every 60 seconds.
Expand All @@ -89,8 +88,7 @@ impl MongodbSessionStore {
/// # Ok(()) }) }
/// ```
pub async fn initialize(&self) -> Result {
let _ = &self.index_on_expiry_at().await?;
Ok(())
self.index_on_expiry_at().await
}

/// private associated function
Expand All @@ -102,7 +100,7 @@ impl MongodbSessionStore {
expire_after_seconds: u32,
) -> mongodb::error::Result<()> {
let create_index = doc! {
"createIndexes": &self.coll_name,
"createIndexes": self.collection.name(),
"indexes": [
{
"key" : { field_name: 1 },
Expand All @@ -111,8 +109,7 @@ impl MongodbSessionStore {
}
]
};
self.client
.database(&self.db)
self.database
.run_command(
create_index,
SelectionCriteria::ReadPreference(mongodb::options::ReadPreference::Primary),
Expand All @@ -123,7 +120,7 @@ impl MongodbSessionStore {

/// Create a new index for the `expireAt` property, allowing to expire sessions at a specific clock time.
/// If the `expireAt` date field contains a date in the past, mongodb considers the document expired and will be deleted.
/// https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time
/// <https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time>
/// ```rust
/// # fn main() -> async_session::Result { async_std::task::block_on(async {
/// # use async_mongodb_session::MongodbSessionStore;
Expand All @@ -142,14 +139,13 @@ impl MongodbSessionStore {
#[async_trait]
impl SessionStore for MongodbSessionStore {
async fn store_session(&self, session: Session) -> Result<Option<String>> {
let coll = self.client.database(&self.db).collection(&self.coll_name);
let coll = &self.collection;

let value = bson::to_bson(&session)?;
let id = session.id();
let query = doc! { "session_id": id };
let expire_at = match session.expiry() {
None => Utc::now() + Duration::from_std(std::time::Duration::from_secs(1200)).unwrap(),

Some(expiry) => *{ expiry },
};
let replacement = doc! { "session_id": id, "session": value, "expireAt": expire_at, "created": Utc::now() };
Expand All @@ -162,7 +158,7 @@ impl SessionStore for MongodbSessionStore {

async fn load_session(&self, cookie_value: String) -> Result<Option<Session>> {
let id = Session::id_from_cookie_value(&cookie_value)?;
let coll:Collection<Document> = self.client.database(&self.db).collection(&self.coll_name);
let coll = &self.collection;
let filter = doc! { "session_id": id };
match coll.find_one(filter, None).await? {
None => Ok(None),
Expand All @@ -175,7 +171,7 @@ impl SessionStore for MongodbSessionStore {
// https://docs.mongodb.com/manual/core/index-ttl/#timing-of-the-delete-operation
// This prevents those documents being returned
if let Some(expiry_at) = doc.get("expireAt").and_then(Bson::as_datetime) {
if expiry_at < &Utc::now().into() {
if expiry_at.to_chrono() < Utc::now() {
return Ok(None);
}
}
Expand All @@ -185,14 +181,14 @@ impl SessionStore for MongodbSessionStore {
}

async fn destroy_session(&self, session: Session) -> Result {
let coll:Collection<Document> = self.client.database(&self.db).collection(&self.coll_name);
let coll = &self.collection;
coll.delete_one(doc! { "session_id": session.id() }, None)
.await?;
Ok(())
}

async fn clear_store(&self) -> Result {
let coll:Collection<Document> = self.client.database(&self.db).collection(&self.coll_name);
let coll = &self.collection;
coll.drop(None).await?;
self.initialize().await?;
Ok(())
Expand Down
Loading

0 comments on commit 5e5af7e

Please sign in to comment.