Skip to content

Commit

Permalink
Tide sessions
Browse files Browse the repository at this point in the history
  • Loading branch information
jbr committed Jul 26, 2020
1 parent 724afc9 commit 5283dae
Show file tree
Hide file tree
Showing 8 changed files with 661 additions and 3 deletions.
5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,18 @@ features = ["docs"]
rustdoc-args = ["--cfg", "feature=\"docs\""]

[features]
default = ["h1-server", "logger"]
default = ["h1-server", "logger", "sessions"]
h1-server = ["async-h1"]
logger = []
docs = ["unstable"]
sessions = ["async-session"]
unstable = []
# DO NOT USE. Only exists to expose internals so they can be benchmarked.
__internal__bench = []

[dependencies]
async-h1 = { version = "2.0.1", optional = true }
async-session = { version = "2.0.0", optional = true }
async-sse = "4.0.0"
async-std = { version = "1.6.0", features = ["unstable"] }
async-trait = "0.1.36"
Expand Down Expand Up @@ -65,4 +67,3 @@ required-features = ["unstable"]
[[bench]]
name = "router"
harness = false

39 changes: 39 additions & 0 deletions examples/sessions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#[async_std::main]
async fn main() -> Result<(), std::io::Error> {
tide::log::start();
let mut app = tide::new();

app.middleware(tide::sessions::SessionMiddleware::new(
tide::sessions::MemoryStore::new(),
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.middleware(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(())
}
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,9 @@ pub mod security;
pub mod sse;
pub mod utils;

#[cfg(feature = "sessions")]
pub mod sessions;

pub use endpoint::Endpoint;
pub use middleware::{Middleware, Next};
pub use redirect::Redirect;
Expand Down
32 changes: 32 additions & 0 deletions src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,12 @@ impl<State> Request<State> {
self.req.ext().get()
}

/// Get a mutable reference to value stored in request extensions.
#[must_use]
pub fn ext_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
self.req.ext_mut().get_mut()
}

/// Set a request extension value.
pub fn set_ext<T: Send + Sync + 'static>(&mut self, val: T) -> Option<T> {
self.req.ext_mut().insert(val)
Expand Down Expand Up @@ -506,6 +512,32 @@ impl<State> Request<State> {
.and_then(|cookie_data| cookie_data.content.read().unwrap().get(name).cloned())
}

/// Retrieves a reference to the current session.
///
/// # Panics
///
/// This method will panic if a tide::sessions:SessionMiddleware has not
/// been run.
#[cfg(feature = "sessions")]
pub fn session(&self) -> &crate::sessions::Session {
self.ext::<crate::sessions::Session>().expect(
"request session not initialized, did you enable tide::sessions::SessionMiddleware?",
)
}

/// Retrieves a mutable reference to the current session.
///
/// # Panics
///
/// This method will panic if a tide::sessions:SessionMiddleware has not
/// been run.
#[cfg(feature = "sessions")]
pub fn session_mut(&mut self) -> &mut crate::sessions::Session {
self.ext_mut().expect(
"request session not initialized, did you enable tide::sessions::SessionMiddleware?",
)
}

/// Get the length of the body stream, if it has been set.
///
/// This value is set when passing a fixed-size object into as the body. E.g. a string, or a
Expand Down
Loading

0 comments on commit 5283dae

Please sign in to comment.