Compare commits

..

No commits in common. 'f8d5445cdc10919db5486c2e0e4cc3a6578bd972' and 'af30c552ac4aaa9a59ba8e5e56b0b08122fd7b1f' have entirely different histories.

  1. 2
      Cargo.toml
  2. 40
      README.md
  3. 77
      examples/dog_list/main.rs
  4. 74
      examples/visit_counter/main.rs
  5. 303
      src/lib.rs

@ -1,6 +1,6 @@
[package] [package]
name = "rocket_session" name = "rocket_session"
version = "0.2.0" version = "0.1.1"
authors = ["Ondřej Hruška <ondra@ondrovo.com>"] authors = ["Ondřej Hruška <ondra@ondrovo.com>"]
edition = "2018" edition = "2018"
license = "MIT" license = "MIT"

@ -2,38 +2,17 @@
Adding cookie-based sessions to a rocket application is extremely simple with this crate. Adding cookie-based sessions to a rocket application is extremely simple with this crate.
Sessions are used to share data between related requests, such as user authentication, shopping basket,
form values that failed validation for re-filling, etc.
## Configuration
The implementation is generic to support any type as session data: a custom struct, `String`, The implementation is generic to support any type as session data: a custom struct, `String`,
`HashMap`, or perhaps `serde_json::Value`. You're free to choose. `HashMap`, or perhaps `serde_json::Value`. You're free to choose.
The session lifetime, cookie name, and other parameters can be configured by calling chained The session expiry time is configurable through the Fairing. When a session expires,
methods on the fairing. When a session expires, the data associated with it is dropped. the data associated with it is dropped. All expired sessions may be cleared by calling `.remove_expired()`
on the `SessionStore`, which is be obtained in routes as `State<SessionStore>`, or from a
## Usage session instance by calling `.get_store()`.
To use session in a route, first make sure you have the fairing attached by calling
`rocket.attach(Session::fairing())` at start-up, and then add something like `session : Session`
to the parameter list of your route(s). Everything else--session init, expiration, cookie
management--is done for you behind the scenes.
Session data is accessed in a closure run in the session context, using the `session.tap()` The session cookie is currently hardcoded to "SESSID" and contains 16 random characters.
method. This closure runs inside a per-session mutex, avoiding simultaneous mutation
from different requests. Try to *avoid lengthy operations inside the closure*,
as it effectively blocks any other request to session-enabled routes by the client.
Every request to a session-enabled route extends the session's lifetime to the full ## Basic Example
configured time (defaults to 1 hour). Automatic clean-up removes expired sessions to make sure
the session list does not waste memory.
## Examples
(More examples are in the examples folder)
### Basic Example
This simple example uses u64 as the session variable; note that it can be a struct, map, or anything else, This simple example uses u64 as the session variable; note that it can be a struct, map, or anything else,
it just needs to implement `Send + Sync + Default`. it just needs to implement `Send + Sync + Default`.
@ -49,7 +28,7 @@ pub type Session<'a> = rocket_session::Session<'a, u64>;
fn main() { fn main() {
rocket::ignite() rocket::ignite()
.attach(Session::fairing()) .attach(Session::fairing(Duration::from_secs(3600)))
.mount("/", routes![index]) .mount("/", routes![index])
.launch(); .launch();
} }
@ -74,10 +53,7 @@ fn index(session: Session) -> String {
The `.tap()` method is powerful, but sometimes you may wish for something more convenient. The `.tap()` method is powerful, but sometimes you may wish for something more convenient.
Here is an example of using a custom trait and the `json_dotpath` crate to implement Here is an example of using a custom trait and the `json_dotpath` crate to implement
a polymorphic store based on serde serialization. a polymorphic store based on serde serialization:
Note that this approach is prone to data races, since every method contains its own `.tap()`.
It may be safer to simply call the `.dot_*()` methods manually in one shared closure.
```rust ```rust
use serde_json::Value; use serde_json::Value;

@ -1,77 +0,0 @@
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
use rocket::request::Form;
use rocket::response::content::Html;
use rocket::response::Redirect;
type Session<'a> = rocket_session::Session<'a, Vec<String>>;
fn main() {
rocket::ignite()
.attach(Session::fairing())
.mount("/", routes![index, add, remove])
.launch();
}
#[get("/")]
fn index(session: Session) -> Html<String> {
let mut page = String::new();
page.push_str(
r#"
<!DOCTYPE html>
<h1>My Dogs</h1>
<form method="POST" action="/add">
Add Dog: <input type="text" name="name"> <input type="submit" value="Add">
</form>
<ul>
"#,
);
session.tap(|sess| {
for (n, dog) in sess.iter().enumerate() {
page.push_str(&format!(
r#"
<li>&#x1F436; {} <a href="/remove/{}">Remove</a></li>
"#,
dog, n
));
}
});
page.push_str(
r#"
</ul>
"#,
);
Html(page)
}
#[derive(FromForm)]
struct AddForm {
name: String,
}
#[post("/add", data = "<dog>")]
fn add(session: Session, dog: Form<AddForm>) -> Redirect {
session.tap(move |sess| {
sess.push(dog.into_inner().name);
});
Redirect::found("/")
}
#[get("/remove/<dog>")]
fn remove(session: Session, dog: usize) -> Redirect {
session.tap(|sess| {
if dog < sess.len() {
sess.remove(dog);
}
});
Redirect::found("/")
}

@ -1,74 +0,0 @@
//! This demo is a page visit counter, with a custom cookie name, length, and expiry time.
//!
//! The expiry time is set to 10 seconds to illustrate how a session is cleared if inactive.
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
use rocket::response::content::Html;
use std::time::Duration;
#[derive(Default, Clone)]
struct SessionData {
visits1: usize,
visits2: usize,
}
// It's convenient to define a type alias:
type Session<'a> = rocket_session::Session<'a, SessionData>;
fn main() {
rocket::ignite()
.attach(
Session::fairing()
// 10 seconds of inactivity until session expires
// (wait 10s and refresh, the numbers will reset)
.with_lifetime(Duration::from_secs(10))
// custom cookie name and length
.with_cookie_name("my_cookie")
.with_cookie_len(20),
)
.mount("/", routes![index, about])
.launch();
}
#[get("/")]
fn index(session: Session) -> Html<String> {
// Here we build the entire response inside the 'tap' closure.
// While inside, the session is locked to parallel changes, e.g.
// from a different browser tab.
session.tap(|sess| {
sess.visits1 += 1;
Html(format!(
r##"
<!DOCTYPE html>
<h1>Home</h1>
<a href="/">Refresh</a> &bull; <a href="/about/">go to About</a>
<p>Visits: home {}, about {}</p>
"##,
sess.visits1, sess.visits2
))
})
}
#[get("/about")]
fn about(session: Session) -> Html<String> {
// Here we return a value from the tap function and use it below
let count = session.tap(|sess| {
sess.visits2 += 1;
sess.visits2
});
Html(format!(
r##"
<!DOCTYPE html>
<h1>About</h1>
<a href="/about">Refresh</a> &bull; <a href="/">go home</a>
<p>Page visits: {}</p>
"##,
count
))
}

@ -1,4 +1,4 @@
use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard}; use parking_lot::RwLock;
use rand::Rng; use rand::Rng;
use rocket::{ use rocket::{
@ -8,109 +8,67 @@ use rocket::{
Outcome, Request, Response, Rocket, State, Outcome, Request, Response, Rocket, State,
}; };
use std::borrow::Cow;
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt::{self, Display, Formatter};
use std::marker::PhantomData; use std::marker::PhantomData;
use std::ops::Add; use std::ops::Add;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
/// Session store (shared state) const SESSION_COOKIE: &str = "SESSID";
#[derive(Debug)] const SESSION_ID_LEN: usize = 16;
pub struct SessionStore<D>
where
D: 'static + Sync + Send + Default,
{
/// The internally mutable map of sessions
inner: RwLock<StoreInner<D>>,
// Session config
config: SessionConfig,
}
/// Session config object
#[derive(Debug, Clone)]
struct SessionConfig {
/// Sessions lifespan
lifespan: Duration,
/// Session cookie name
cookie_name: Cow<'static, str>,
/// Session cookie path
cookie_path: Cow<'static, str>,
/// Session ID character length
cookie_len: usize,
}
impl Default for SessionConfig { /// Session, as stored in the sessions store
fn default() -> Self {
Self {
lifespan: Duration::from_secs(3600),
cookie_name: "rocket_session".into(),
cookie_path: "/".into(),
cookie_len: 16,
}
}
}
/// Mutable object stored inside SessionStore behind a RwLock
#[derive(Debug)] #[derive(Debug)]
struct StoreInner<D> struct SessionInstance<D>
where where
D: 'static + Sync + Send + Default, D: 'static + Sync + Send + Default,
{ {
sessions: HashMap<String, Mutex<SessionInstance<D>>>, /// Data object
last_expiry_sweep: Instant, data: D,
/// Expiry
expires: Instant,
} }
impl<D> Default for StoreInner<D> /// Session store (shared state)
where #[derive(Default, Debug)]
pub struct SessionStore<D>
where
D: 'static + Sync + Send + Default, D: 'static + Sync + Send + Default,
{ {
fn default() -> Self { /// The internaly mutable map of sessions
Self { inner: RwLock<HashMap<String, SessionInstance<D>>>,
sessions: Default::default(), /// Sessions lifespan
// the first expiry sweep is scheduled one lifetime from start-up lifespan: Duration,
last_expiry_sweep: Instant::now(),
}
}
} }
/// Session, as stored in the sessions store impl<D> SessionStore<D>
#[derive(Debug)] where
struct SessionInstance<D>
where
D: 'static + Sync + Send + Default, D: 'static + Sync + Send + Default,
{ {
/// Data object /// Remove all expired sessions
data: D, pub fn remove_expired(&self) {
/// Expiry let now = Instant::now();
expires: Instant, self.inner.write().retain(|_k, v| v.expires > now);
}
} }
/// Session ID newtype for rocket's "local_cache" /// Session ID newtype for rocket's "local_cache"
#[derive(Clone, Debug)] #[derive(PartialEq, Hash, Clone, Debug)]
struct SessionID(String); struct SessionID(String);
impl SessionID { impl SessionID {
fn as_str(&self) -> &str { fn as_str(&self) -> &str {
self.0.as_str() self.0.as_str()
} }
}
impl Display for SessionID { fn to_string(&self) -> String {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { self.0.clone()
f.write_str(&self.0)
} }
} }
/// Session instance /// Session instance
///
/// To access the active session, simply add it as an argument to a route function.
///
/// Sessions are started, restored, or expired in the `FromRequest::from_request()` method
/// when a `Session` is prepared for one of the route functions.
#[derive(Debug)] #[derive(Debug)]
pub struct Session<'a, D> pub struct Session<'a, D>
where where
D: 'static + Sync + Send + Default, D: 'static + Sync + Send + Default,
{ {
/// The shared state reference /// The shared state reference
@ -120,82 +78,51 @@ where
} }
impl<'a, 'r, D> FromRequest<'a, 'r> for Session<'a, D> impl<'a, 'r, D> FromRequest<'a, 'r> for Session<'a, D>
where where
D: 'static + Sync + Send + Default, D: 'static + Sync + Send + Default,
{ {
type Error = (); type Error = ();
fn from_request(request: &'a Request<'r>) -> Outcome<Self, (Status, Self::Error), ()> { fn from_request(request: &'a Request<'r>) -> Outcome<Self, (Status, Self::Error), ()> {
let store: State<SessionStore<D>> = request.guard().unwrap(); let store : State<SessionStore<D>> = request.guard().unwrap();
Outcome::Success(Session { Outcome::Success(Session {
id: request.local_cache(|| { id: request.local_cache(|| {
let store_ug = store.inner.upgradable_read();
// Resolve session ID // Resolve session ID
let id = if let Some(cookie) = request.cookies().get(&store.config.cookie_name) { let id = if let Some(cookie) = request.cookies().get(SESSION_COOKIE) {
Some(SessionID(cookie.value().to_string())) SessionID(cookie.value().to_string())
} else {
None
};
let expires = Instant::now().add(store.config.lifespan);
if let Some(m) = id
.as_ref()
.and_then(|token| store_ug.sessions.get(token.as_str()))
{
// --- ID obtained from a cookie && session found in the store ---
let mut inner = m.lock();
if inner.expires <= Instant::now() {
// Session expired, reuse the ID but drop data.
inner.data = D::default();
}
// Session is extended by making a request with valid ID
inner.expires = expires;
id.unwrap()
} else { } else {
// --- ID missing or session not found --- SessionID(
rand::thread_rng()
// Get exclusive write access to the map
let mut store_wg = RwLockUpgradableReadGuard::upgrade(store_ug);
// This branch runs less often, and we already have write access,
// let's check if any sessions expired. We don't want to hog memory
// forever by abandoned sessions (e.g. when a client lost their cookie)
// Throttle by lifespan - e.g. sweep every hour
if store_wg.last_expiry_sweep.elapsed() > store.config.lifespan {
let now = Instant::now();
store_wg.sessions.retain(|_k, v| v.lock().expires > now);
store_wg.last_expiry_sweep = now;
}
// Find a new unique ID - we are still safely inside the write guard
let new_id = SessionID(loop {
let token: String = rand::thread_rng()
.sample_iter(&rand::distributions::Alphanumeric) .sample_iter(&rand::distributions::Alphanumeric)
.take(store.config.cookie_len) .take(SESSION_ID_LEN)
.collect(); .collect(),
)
};
if !store_wg.sessions.contains_key(&token) { let new_expiration = Instant::now().add(store.lifespan);
break token; let mut wg = store.inner.write();
match wg.get_mut(id.as_str()) {
Some(ses) => {
// Check expiration
if ses.expires <= Instant::now() {
ses.data = D::default();
}
// Update expiry timestamp
ses.expires = new_expiration;
},
None => {
// New session
wg.insert(
id.to_string(),
SessionInstance {
data: D::default(),
expires: new_expiration,
} }
});
store_wg.sessions.insert(
new_id.to_string(),
Mutex::new(SessionInstance {
data: Default::default(),
expires,
}),
); );
new_id
} }
};
id
}), }),
store, store,
}) })
@ -203,99 +130,53 @@ where
} }
impl<'a, D> Session<'a, D> impl<'a, D> Session<'a, D>
where where
D: 'static + Sync + Send + Default, D: 'static + Sync + Send + Default,
{ {
/// Create the session fairing. /// Get the fairing object
/// pub fn fairing(lifespan: Duration) -> impl Fairing {
/// You can configure the session store by calling chained methods on the returned value SessionFairing::<D> {
/// before passing it to `rocket.attach()` lifespan,
pub fn fairing() -> SessionFairing<D> { _phantom: PhantomData,
SessionFairing::<D>::new() }
} }
/// Clear session data (replace the value with default) /// Access the session store
pub fn clear(&self) { pub fn get_store(&self) -> &SessionStore<D> {
self.tap(|m| { &self.store
}
/// Set the session object to its default state
pub fn reset(&self) {
self.tap_mut(|m| {
*m = D::default(); *m = D::default();
}) })
} }
/// Access the session's data using a closure. pub fn tap<T>(&self, func: impl FnOnce(&D) -> T) -> T {
/// let rg = self.store.inner.read();
/// The closure is called with the data value as a mutable argument, let instance = rg.get(self.id.as_str()).unwrap();
/// and can return any value to be is passed up to the caller. func(&instance.data)
pub fn tap<T>(&self, func: impl FnOnce(&mut D) -> T) -> T { }
// Use a read guard, so other already active sessions are not blocked
// from accessing the store. New incoming clients may be blocked until
// the tap() call finishes
let store_rg = self.store.inner.read();
// Unlock the session's mutex.
// Expiry was checked and prolonged at the beginning of the request
let mut instance = store_rg
.sessions
.get(self.id.as_str())
.expect("Session data unexpectedly missing")
.lock();
pub fn tap_mut<T>(&self, func: impl FnOnce(&mut D) -> T) -> T {
let mut wg = self.store.inner.write();
let instance = wg.get_mut(self.id.as_str()).unwrap();
func(&mut instance.data) func(&mut instance.data)
} }
} }
/// Fairing struct /// Fairing struct
#[derive(Default)] struct SessionFairing<D>
pub struct SessionFairing<D> where
where
D: 'static + Sync + Send + Default,
{
config: SessionConfig,
phantom: PhantomData<D>,
}
impl<D> SessionFairing<D>
where
D: 'static + Sync + Send + Default, D: 'static + Sync + Send + Default,
{ {
fn new() -> Self { lifespan: Duration,
Self::default() _phantom: PhantomData<D>,
}
/// Set session lifetime (expiration time).
///
/// Call on the fairing before passing it to `rocket.attach()`
pub fn with_lifetime(mut self, time: Duration) -> Self {
self.config.lifespan = time;
self
}
/// Set session cookie name and length
///
/// Call on the fairing before passing it to `rocket.attach()`
pub fn with_cookie_name(mut self, name: impl Into<Cow<'static, str>>) -> Self {
self.config.cookie_name = name.into();
self
}
/// Set session cookie name and length
///
/// Call on the fairing before passing it to `rocket.attach()`
pub fn with_cookie_len(mut self, length: usize) -> Self {
self.config.cookie_len = length;
self
}
/// Set session cookie name and length
///
/// Call on the fairing before passing it to `rocket.attach()`
pub fn with_cookie_path(mut self, path: impl Into<Cow<'static, str>>) -> Self {
self.config.cookie_path = path.into();
self
}
} }
impl<D> Fairing for SessionFairing<D> impl<D> Fairing for SessionFairing<D>
where where
D: 'static + Sync + Send + Default, D: 'static + Sync + Send + Default,
{ {
fn info(&self) -> Info { fn info(&self) -> Info {
@ -309,7 +190,7 @@ where
// install the store singleton // install the store singleton
Ok(rocket.manage(SessionStore::<D> { Ok(rocket.manage(SessionStore::<D> {
inner: Default::default(), inner: Default::default(),
config: self.config.clone(), lifespan: self.lifespan,
})) }))
} }
@ -318,11 +199,7 @@ where
let session = request.local_cache(|| SessionID("".to_string())); let session = request.local_cache(|| SessionID("".to_string()));
if !session.0.is_empty() { if !session.0.is_empty() {
response.adjoin_header( response.adjoin_header(Cookie::build(SESSION_COOKIE, session.0.clone()).finish());
Cookie::build(self.config.cookie_name.clone(), session.to_string())
.path("/")
.finish(),
);
} }
} }
} }

Loading…
Cancel
Save