Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6c1e42b8e
|
||
|
|
a77ae21a9e
|
+1
-4
@@ -7,9 +7,6 @@ edition = "2018"
|
|||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
|
||||||
serde_json = { version="1.0", features= ["preserve_order"] }
|
|
||||||
json_dotpath = "0.1.2"
|
|
||||||
rand = "0.7.2"
|
rand = "0.7.2"
|
||||||
rocket = { version="0.4.2", default-features = false}
|
rocket = "0.4.2"
|
||||||
parking_lot = "0.10.0"
|
parking_lot = "0.10.0"
|
||||||
|
|||||||
@@ -1,14 +1,27 @@
|
|||||||
# Sessions for Rocket.rs
|
# Sessions for Rocket.rs
|
||||||
|
|
||||||
Adding cookie-based sessions to a rocket application is extremely simple:
|
Adding cookie-based sessions to a rocket application is extremely simple with this crate.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
The session expiry time is configurable through the Fairing. When a session expires,
|
||||||
|
the data associated with it is dropped.
|
||||||
|
|
||||||
|
## Basic example
|
||||||
|
|
||||||
|
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`.
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
#![feature(proc_macro_hygiene, decl_macro)]
|
#![feature(proc_macro_hygiene, decl_macro)]
|
||||||
#[macro_use] extern crate rocket;
|
#[macro_use] extern crate rocket;
|
||||||
|
|
||||||
use rocket_session::Session;
|
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
|
// It's convenient to define a type alias:
|
||||||
|
pub type Session<'a> = rocket_session::Session<'a, u64>;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
rocket::ignite()
|
rocket::ignite()
|
||||||
.attach(Session::fairing(Duration::from_secs(3600)))
|
.attach(Session::fairing(Duration::from_secs(3600)))
|
||||||
@@ -18,16 +31,66 @@ fn main() {
|
|||||||
|
|
||||||
#[get("/")]
|
#[get("/")]
|
||||||
fn index(session: Session) -> String {
|
fn index(session: Session) -> String {
|
||||||
let mut count: usize = session.get_or_default("count");
|
let count = session.tap(|n| {
|
||||||
count += 1;
|
// Change the stored value (it is &mut)
|
||||||
session.set("count", count);
|
*n += 1;
|
||||||
|
|
||||||
|
// Return something to the caller.
|
||||||
|
// This can be any type, 'tap' is generic.
|
||||||
|
*n
|
||||||
|
});
|
||||||
|
|
||||||
format!("{} visits", count)
|
format!("{} visits", count)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Anything serializable can be stored in the session, just make sure to unpack it to the right type.
|
## Extending by a trait
|
||||||
|
|
||||||
The session driver internally uses `serde_json::Value` and the `json_dotpath` crate.
|
The `tap` method is powerful, but sometimes you may wish for something more convenient.
|
||||||
Therefore, it's possible to use dotted paths and store the session data in a more structured way.
|
|
||||||
|
Here is an example of using a custom trait and the `json_dotpath` crate to implement
|
||||||
|
a polymorphic store based on serde serialization:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use serde_json::Value;
|
||||||
|
use serde::de::DeserializeOwned;
|
||||||
|
use serde::Serialize;
|
||||||
|
use json_dotpath::DotPaths;
|
||||||
|
|
||||||
|
pub type Session<'a> = rocket_session::Session<'a, serde_json::Map<String, Value>>;
|
||||||
|
|
||||||
|
pub trait SessionAccess {
|
||||||
|
fn get<T: DeserializeOwned>(&self, path: &str) -> Option<T>;
|
||||||
|
|
||||||
|
fn take<T: DeserializeOwned>(&self, path: &str) -> Option<T>;
|
||||||
|
|
||||||
|
fn replace<O: DeserializeOwned, N: Serialize>(&self, path: &str, new: N) -> Option<O>;
|
||||||
|
|
||||||
|
fn set<T: Serialize>(&self, path: &str, value: T);
|
||||||
|
|
||||||
|
fn remove(&self, path: &str) -> bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> SessionAccess for Session<'a> {
|
||||||
|
fn get<T: DeserializeOwned>(&self, path: &str) -> Option<T> {
|
||||||
|
self.tap(|data| data.dot_get(path))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn take<T: DeserializeOwned>(&self, path: &str) -> Option<T> {
|
||||||
|
self.tap(|data| data.dot_take(path))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn replace<O: DeserializeOwned, N: Serialize>(&self, path: &str, new: N) -> Option<O> {
|
||||||
|
self.tap(|data| data.dot_replace(path, new))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set<T: Serialize>(&self, path: &str, value: T) {
|
||||||
|
self.tap(|data| data.dot_set(path, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove(&self, path: &str) -> bool {
|
||||||
|
self.tap(|data| data.dot_remove(path))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|||||||
+99
-70
@@ -1,37 +1,57 @@
|
|||||||
use json_dotpath::DotPaths;
|
|
||||||
use parking_lot::RwLock;
|
use parking_lot::RwLock;
|
||||||
use rand::Rng;
|
use rand::Rng;
|
||||||
use rocket::fairing::{self, Fairing, Info};
|
|
||||||
use rocket::request::FromRequest;
|
|
||||||
|
|
||||||
use rocket::{
|
use rocket::{
|
||||||
|
fairing::{self, Fairing, Info},
|
||||||
http::{Cookie, Status},
|
http::{Cookie, Status},
|
||||||
|
request::FromRequest,
|
||||||
Outcome, Request, Response, Rocket, State,
|
Outcome, Request, Response, Rocket, State,
|
||||||
};
|
};
|
||||||
use serde::de::DeserializeOwned;
|
|
||||||
use serde::Serialize;
|
|
||||||
use serde_json::{Map, Value};
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
use std::marker::PhantomData;
|
||||||
use std::ops::Add;
|
use std::ops::Add;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
const SESSION_ID: &str = "SESSID";
|
const SESSION_COOKIE: &str = "SESSID";
|
||||||
|
const SESSION_ID_LEN: usize = 16;
|
||||||
type SessionsMap = HashMap<String, SessionInstance>;
|
|
||||||
|
|
||||||
|
/// Session, as stored in the sessions store
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct SessionInstance {
|
struct SessionInstance<D>
|
||||||
data: serde_json::Map<String, Value>,
|
where
|
||||||
|
D: 'static + Sync + Send + Default,
|
||||||
|
{
|
||||||
|
/// Data object
|
||||||
|
data: D,
|
||||||
|
/// Expiry
|
||||||
expires: Instant,
|
expires: Instant,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Session store (shared state)
|
||||||
#[derive(Default, Debug)]
|
#[derive(Default, Debug)]
|
||||||
struct SessionStore {
|
pub struct SessionStore<D>
|
||||||
inner: RwLock<SessionsMap>,
|
where
|
||||||
|
D: 'static + Sync + Send + Default,
|
||||||
|
{
|
||||||
|
/// The internaly mutable map of sessions
|
||||||
|
inner: RwLock<HashMap<String, SessionInstance<D>>>,
|
||||||
|
/// Sessions lifespan
|
||||||
lifespan: Duration,
|
lifespan: Duration,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<D> SessionStore<D>
|
||||||
|
where
|
||||||
|
D: 'static + Sync + Send + Default,
|
||||||
|
{
|
||||||
|
/// Remove all expired sessions
|
||||||
|
pub fn remove_expired(&self) {
|
||||||
|
let now = Instant::now();
|
||||||
|
self.inner.write().retain(|_k, v| v.expires > now);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Session ID newtype for rocket's "local_cache"
|
||||||
#[derive(PartialEq, Hash, Clone, Debug)]
|
#[derive(PartialEq, Hash, Clone, Debug)]
|
||||||
struct SessionID(String);
|
struct SessionID(String);
|
||||||
|
|
||||||
@@ -40,7 +60,7 @@ impl<'a, 'r> FromRequest<'a, 'r> for &'a SessionID {
|
|||||||
|
|
||||||
fn from_request(request: &'a Request<'r>) -> Outcome<Self, (Status, Self::Error), ()> {
|
fn from_request(request: &'a Request<'r>) -> Outcome<Self, (Status, Self::Error), ()> {
|
||||||
Outcome::Success(request.local_cache(|| {
|
Outcome::Success(request.local_cache(|| {
|
||||||
if let Some(cookie) = request.cookies().get(SESSION_ID) {
|
if let Some(cookie) = request.cookies().get(SESSION_COOKIE) {
|
||||||
SessionID(cookie.value().to_string()) // FIXME avoid cloning (cow?)
|
SessionID(cookie.value().to_string()) // FIXME avoid cloning (cow?)
|
||||||
} else {
|
} else {
|
||||||
SessionID(
|
SessionID(
|
||||||
@@ -54,25 +74,34 @@ impl<'a, 'r> FromRequest<'a, 'r> for &'a SessionID {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Session instance
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Session<'a> {
|
pub struct Session<'a, D>
|
||||||
store: State<'a, SessionStore>,
|
where
|
||||||
|
D: 'static + Sync + Send + Default,
|
||||||
|
{
|
||||||
|
/// The shared state reference
|
||||||
|
store: State<'a, SessionStore<D>>,
|
||||||
|
/// Session ID
|
||||||
id: &'a SessionID,
|
id: &'a SessionID,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, 'r> FromRequest<'a, 'r> for Session<'a> {
|
impl<'a, 'r, D> FromRequest<'a, 'r> for Session<'a, D>
|
||||||
|
where
|
||||||
|
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), ()> {
|
||||||
Outcome::Success(Session {
|
Outcome::Success(Session {
|
||||||
id: request.local_cache(|| {
|
id: request.local_cache(|| {
|
||||||
if let Some(cookie) = request.cookies().get(SESSION_ID) {
|
if let Some(cookie) = request.cookies().get(SESSION_COOKIE) {
|
||||||
SessionID(cookie.value().to_string())
|
SessionID(cookie.value().to_string())
|
||||||
} else {
|
} else {
|
||||||
SessionID(
|
SessionID(
|
||||||
rand::thread_rng()
|
rand::thread_rng()
|
||||||
.sample_iter(&rand::distributions::Alphanumeric)
|
.sample_iter(&rand::distributions::Alphanumeric)
|
||||||
.take(16)
|
.take(SESSION_ID_LEN)
|
||||||
.collect(),
|
.collect(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -82,19 +111,52 @@ impl<'a, 'r> FromRequest<'a, 'r> for Session<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> Session<'a> {
|
impl<'a, D> Session<'a, D>
|
||||||
|
where
|
||||||
|
D: 'static + Sync + Send + Default,
|
||||||
|
{
|
||||||
|
/// Get the fairing object
|
||||||
pub fn fairing(lifespan: Duration) -> impl Fairing {
|
pub fn fairing(lifespan: Duration) -> impl Fairing {
|
||||||
SessionFairing { lifespan }
|
SessionFairing::<D> {
|
||||||
|
lifespan,
|
||||||
|
_phantom: PhantomData,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn tap<T>(&self, func: impl FnOnce(&mut serde_json::Map<String, Value>) -> T) -> T {
|
/// Access the session store
|
||||||
|
pub fn get_store(&self) -> &SessionStore<D> {
|
||||||
|
&self.store
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the session object to its default state
|
||||||
|
pub fn reset(&self) {
|
||||||
|
self.tap(|m| {
|
||||||
|
*m = D::default();
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renew the session without changing any data
|
||||||
|
pub fn renew(&self) {
|
||||||
|
self.tap(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run a closure with a mutable reference to the session object.
|
||||||
|
/// The closure's return value is send to the caller.
|
||||||
|
pub fn tap<T>(&self, func: impl FnOnce(&mut D) -> T) -> T {
|
||||||
let mut wg = self.store.inner.write();
|
let mut wg = self.store.inner.write();
|
||||||
if let Some(instance) = wg.get_mut(&self.id.0) {
|
if let Some(instance) = wg.get_mut(&self.id.0) {
|
||||||
|
// wipe session data if expired
|
||||||
|
if instance.expires <= Instant::now() {
|
||||||
|
instance.data = D::default();
|
||||||
|
}
|
||||||
|
// update expiry timestamp
|
||||||
instance.expires = Instant::now().add(self.store.lifespan);
|
instance.expires = Instant::now().add(self.store.lifespan);
|
||||||
|
|
||||||
func(&mut instance.data)
|
func(&mut instance.data)
|
||||||
} else {
|
} else {
|
||||||
let mut data = Map::new();
|
// no object in the store yet, start fresh
|
||||||
let rv = func(&mut data);
|
let mut data = D::default();
|
||||||
|
let result = func(&mut data);
|
||||||
wg.insert(
|
wg.insert(
|
||||||
self.id.0.clone(),
|
self.id.0.clone(),
|
||||||
SessionInstance {
|
SessionInstance {
|
||||||
@@ -102,57 +164,24 @@ impl<'a> Session<'a> {
|
|||||||
expires: Instant::now().add(self.store.lifespan),
|
expires: Instant::now().add(self.store.lifespan),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
rv
|
result
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn renew(&self) {
|
|
||||||
self.tap(|_| ())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn reset(&self) {
|
|
||||||
self.tap(|data| data.clear())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get<T: DeserializeOwned>(&self, path: &str) -> Option<T> {
|
|
||||||
self.tap(|data| data.dot_get(path))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_or<T: DeserializeOwned>(&self, path: &str, def: T) -> T {
|
|
||||||
self.get(path).unwrap_or(def)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_or_else<T: DeserializeOwned, F: FnOnce() -> T>(&self, path: &str, def: F) -> T {
|
|
||||||
self.get(path).unwrap_or_else(def)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_or_default<T: DeserializeOwned + Default>(&self, path: &str) -> T {
|
|
||||||
self.get(path).unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn take<T: DeserializeOwned>(&self, path: &str) -> Option<T> {
|
|
||||||
self.tap(|data| data.dot_take(path))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn replace<O: DeserializeOwned, N: Serialize>(&self, path: &str, new: N) -> Option<O> {
|
|
||||||
self.tap(|data| data.dot_replace(path, new))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set<T: Serialize>(&self, path: &str, value: T) {
|
|
||||||
self.tap(|data| data.dot_set(path, value));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn remove(&self, path: &str) -> bool {
|
|
||||||
self.tap(|data| data.dot_remove(path))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fairing struct
|
/// Fairing struct
|
||||||
struct SessionFairing {
|
struct SessionFairing<D>
|
||||||
lifespan: Duration
|
where
|
||||||
|
D: 'static + Sync + Send + Default,
|
||||||
|
{
|
||||||
|
lifespan: Duration,
|
||||||
|
_phantom: PhantomData<D>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Fairing for SessionFairing {
|
impl<D> Fairing for SessionFairing<D>
|
||||||
|
where
|
||||||
|
D: 'static + Sync + Send + Default,
|
||||||
|
{
|
||||||
fn info(&self) -> Info {
|
fn info(&self) -> Info {
|
||||||
Info {
|
Info {
|
||||||
name: "Session",
|
name: "Session",
|
||||||
@@ -161,7 +190,7 @@ impl Fairing for SessionFairing {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn on_attach(&self, rocket: Rocket) -> Result<Rocket, Rocket> {
|
fn on_attach(&self, rocket: Rocket) -> Result<Rocket, Rocket> {
|
||||||
Ok(rocket.manage(SessionStore {
|
Ok(rocket.manage(SessionStore::<D> {
|
||||||
inner: Default::default(),
|
inner: Default::default(),
|
||||||
lifespan: self.lifespan,
|
lifespan: self.lifespan,
|
||||||
}))
|
}))
|
||||||
@@ -171,7 +200,7 @@ impl Fairing for SessionFairing {
|
|||||||
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(Cookie::build(SESSION_ID, session.0.clone()).finish());
|
response.adjoin_header(Cookie::build(SESSION_COOKIE, session.0.clone()).finish());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user