Struct tower_sessions::Session
source ยท pub struct Session { /* private fields */ }Expand description
A session which allows HTTP applications to associate key-value pairs with visitors.
Implementationsยง
sourceยงimpl Session
impl Session
sourcepub fn new(
session_id: Option<Id>,
store: Arc<impl SessionStore>,
expiry: Option<Expiry>,
) -> Session
pub fn new( session_id: Option<Id>, store: Arc<impl SessionStore>, expiry: Option<Expiry>, ) -> Session
Creates a new session with the session ID, store, and expiry.
This method is lazy and does not invoke the overhead of talking to the backing store.
ยงExamples
use std::sync::Arc;
use tower_sessions::{MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
Session::new(None, store, None);sourcepub async fn insert(
&self,
key: &str,
value: impl Serialize,
) -> Result<(), Error>
pub async fn insert( &self, key: &str, value: impl Serialize, ) -> Result<(), Error>
Inserts a impl Serialize value into the session.
ยงExamples
use std::sync::Arc;
use tower_sessions::{MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
let session = Session::new(None, store, None);
session.insert("foo", 42).await.unwrap();
let value = session.get::<usize>("foo").await.unwrap();
assert_eq!(value, Some(42));ยงErrors
- This method can fail when
serde_json::to_valuefails. - If the session has not been hydrated and loading from the store fails,
we fail with
Error::Store.
sourcepub async fn insert_value(
&self,
key: &str,
value: Value,
) -> Result<Option<Value>, Error>
pub async fn insert_value( &self, key: &str, value: Value, ) -> Result<Option<Value>, Error>
Inserts a serde_json::Value into the session.
If the key was not present in the underlying map, None is returned and
modified is set to true.
If the underlying map did have the key and its value is the same as the
provided value, None is returned and modified is not set.
ยงExamples
use std::sync::Arc;
use tower_sessions::{MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
let session = Session::new(None, store, None);
let value = session
.insert_value("foo", serde_json::json!(42))
.await
.unwrap();
assert!(value.is_none());
let value = session
.insert_value("foo", serde_json::json!(42))
.await
.unwrap();
assert!(value.is_none());
let value = session
.insert_value("foo", serde_json::json!("bar"))
.await
.unwrap();
assert_eq!(value, Some(serde_json::json!(42)));ยงErrors
- If the session has not been hydrated and loading from the store fails,
we fail with
Error::Store.
sourcepub async fn get<T>(&self, key: &str) -> Result<Option<T>, Error>where
T: DeserializeOwned,
pub async fn get<T>(&self, key: &str) -> Result<Option<T>, Error>where
T: DeserializeOwned,
Gets a value from the store.
ยงExamples
use std::sync::Arc;
use tower_sessions::{MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
let session = Session::new(None, store, None);
session.insert("foo", 42).await.unwrap();
let value = session.get::<usize>("foo").await.unwrap();
assert_eq!(value, Some(42));ยงErrors
- This method can fail when
serde_json::from_valuefails. - If the session has not been hydrated and loading from the store fails,
we fail with
Error::Store.
sourcepub async fn get_value(&self, key: &str) -> Result<Option<Value>, Error>
pub async fn get_value(&self, key: &str) -> Result<Option<Value>, Error>
Gets a serde_json::Value from the store.
ยงExamples
use std::sync::Arc;
use tower_sessions::{MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
let session = Session::new(None, store, None);
session.insert("foo", 42).await.unwrap();
let value = session.get_value("foo").await.unwrap().unwrap();
assert_eq!(value, serde_json::json!(42));ยงErrors
- If the session has not been hydrated and loading from the store fails,
we fail with
Error::Store.
sourcepub async fn remove<T>(&self, key: &str) -> Result<Option<T>, Error>where
T: DeserializeOwned,
pub async fn remove<T>(&self, key: &str) -> Result<Option<T>, Error>where
T: DeserializeOwned,
Removes a value from the store, retuning the value of the key if it was present in the underlying map.
ยงExamples
use std::sync::Arc;
use tower_sessions::{MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
let session = Session::new(None, store, None);
session.insert("foo", 42).await.unwrap();
let value: Option<usize> = session.remove("foo").await.unwrap();
assert_eq!(value, Some(42));
let value: Option<usize> = session.get("foo").await.unwrap();
assert!(value.is_none());ยงErrors
- This method can fail when
serde_json::from_valuefails. - If the session has not been hydrated and loading from the store fails,
we fail with
Error::Store.
sourcepub async fn remove_value(&self, key: &str) -> Result<Option<Value>, Error>
pub async fn remove_value(&self, key: &str) -> Result<Option<Value>, Error>
Removes a serde_json::Value from the session.
ยงExamples
use std::sync::Arc;
use tower_sessions::{MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
let session = Session::new(None, store, None);
session.insert("foo", 42).await.unwrap();
let value = session.remove_value("foo").await.unwrap().unwrap();
assert_eq!(value, serde_json::json!(42));
let value: Option<usize> = session.get("foo").await.unwrap();
assert!(value.is_none());ยงErrors
- If the session has not been hydrated and loading from the store fails,
we fail with
Error::Store.
sourcepub async fn clear(&self)
pub async fn clear(&self)
Clears the session of all data but does not delete it from the store.
ยงExamples
use std::sync::Arc;
use tower_sessions::{MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
let session = Session::new(None, store.clone(), None);
session.insert("foo", 42).await.unwrap();
assert!(!session.is_empty().await);
session.save().await.unwrap();
session.clear().await;
// Not empty! (We have an ID still.)
assert!(!session.is_empty().await);
// Data is cleared...
assert!(session.get::<usize>("foo").await.unwrap().is_none());
// ...data is cleared before loading from the backend...
let session = Session::new(session.id(), store.clone(), None);
session.clear().await;
assert!(session.get::<usize>("foo").await.unwrap().is_none());
let session = Session::new(session.id(), store, None);
// ...but data is not deleted from the store.
assert_eq!(session.get::<usize>("foo").await.unwrap(), Some(42));sourcepub async fn is_empty(&self) -> bool
pub async fn is_empty(&self) -> bool
Returns true if there is no session ID and the session is empty.
ยงExamples
use std::sync::Arc;
use tower_sessions::{session::Id, MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
let session = Session::new(None, store.clone(), None);
// Empty if we have no ID and record is not loaded.
assert!(session.is_empty().await);
let session = Session::new(Some(Id::default()), store.clone(), None);
// Not empty if we have an ID but no record. (Record is not loaded here.)
assert!(!session.is_empty().await);
let session = Session::new(Some(Id::default()), store.clone(), None);
session.insert("foo", 42).await.unwrap();
// Not empty after inserting.
assert!(!session.is_empty().await);
session.save().await.unwrap();
// Not empty after saving.
assert!(!session.is_empty().await);
let session = Session::new(session.id(), store.clone(), None);
session.load().await.unwrap();
// Not empty after loading from store...
assert!(!session.is_empty().await);
// ...and not empty after accessing the session.
session.get::<usize>("foo").await.unwrap();
assert!(!session.is_empty().await);
let session = Session::new(session.id(), store.clone(), None);
session.delete().await.unwrap();
// Not empty after deleting from store...
assert!(!session.is_empty().await);
session.get::<usize>("foo").await.unwrap();
// ...but empty after trying to access the deleted session.
assert!(session.is_empty().await);
let session = Session::new(None, store, None);
session.insert("foo", 42).await.unwrap();
session.flush().await.unwrap();
// Empty after flushing.
assert!(session.is_empty().await);sourcepub fn id(&self) -> Option<Id>
pub fn id(&self) -> Option<Id>
Get the session ID.
ยงExamples
use std::sync::Arc;
use tower_sessions::{session::Id, MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
let session = Session::new(None, store.clone(), None);
assert!(session.id().is_none());
let id = Some(Id::default());
let session = Session::new(id, store, None);
assert_eq!(id, session.id());sourcepub fn expiry(&self) -> Option<Expiry>
pub fn expiry(&self) -> Option<Expiry>
Get the session expiry.
ยงExamples
use std::sync::Arc;
use tower_sessions::{session::Expiry, MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
let session = Session::new(None, store, None);
assert_eq!(session.expiry(), None);sourcepub fn set_expiry(&self, expiry: Option<Expiry>)
pub fn set_expiry(&self, expiry: Option<Expiry>)
Set expiry to the given value.
This may be used within applications directly to alter the sessionโs time to live.
ยงExamples
use std::sync::Arc;
use time::OffsetDateTime;
use tower_sessions::{session::Expiry, MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
let session = Session::new(None, store, None);
let expiry = Expiry::AtDateTime(OffsetDateTime::now_utc());
session.set_expiry(Some(expiry));
assert_eq!(session.expiry(), Some(expiry));sourcepub fn expiry_date(&self) -> OffsetDateTime
pub fn expiry_date(&self) -> OffsetDateTime
Get session expiry as OffsetDateTime.
ยงExamples
use std::sync::Arc;
use time::{Duration, OffsetDateTime};
use tower_sessions::{MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
let session = Session::new(None, store, None);
// Our default duration is two weeks.
let expected_expiry = OffsetDateTime::now_utc().saturating_add(Duration::weeks(2));
assert!(session.expiry_date() > expected_expiry.saturating_sub(Duration::seconds(1)));
assert!(session.expiry_date() < expected_expiry.saturating_add(Duration::seconds(1)));sourcepub fn expiry_age(&self) -> Duration
pub fn expiry_age(&self) -> Duration
Get session expiry as Duration.
ยงExamples
use std::sync::Arc;
use time::Duration;
use tower_sessions::{MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
let session = Session::new(None, store, None);
let expected_duration = Duration::weeks(2);
assert!(session.expiry_age() > expected_duration.saturating_sub(Duration::seconds(1)));
assert!(session.expiry_age() < expected_duration.saturating_add(Duration::seconds(1)));sourcepub fn is_modified(&self) -> bool
pub fn is_modified(&self) -> bool
Returns true if the session has been modified during the request.
ยงExamples
use std::sync::Arc;
use tower_sessions::{MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
let session = Session::new(None, store, None);
// Not modified initially.
assert!(!session.is_modified());
// Getting doesn't count as a modification.
session.get::<usize>("foo").await.unwrap();
assert!(!session.is_modified());
// Insertions and removals do though.
session.insert("foo", 42).await.unwrap();
assert!(session.is_modified());sourcepub async fn save(&self) -> Result<(), Error>
pub async fn save(&self) -> Result<(), Error>
Saves the session record to the store.
Note that this method is generally not needed and is reserved for situations where the session store must be updated during the request.
ยงExamples
use std::sync::Arc;
use tower_sessions::{MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
let session = Session::new(None, store.clone(), None);
session.insert("foo", 42).await.unwrap();
session.save().await.unwrap();
let session = Session::new(session.id(), store, None);
assert_eq!(session.get::<usize>("foo").await.unwrap().unwrap(), 42);ยงErrors
- If saving to the store fails, we fail with
Error::Store.
sourcepub async fn load(&self) -> Result<(), Error>
pub async fn load(&self) -> Result<(), Error>
Loads the session record from the store.
Note that this method is generally not needed and is reserved for situations where the session must be updated during the request.
ยงExamples
use std::sync::Arc;
use tower_sessions::{session::Id, MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
let id = Some(Id::default());
let session = Session::new(id, store.clone(), None);
session.insert("foo", 42).await.unwrap();
session.save().await.unwrap();
let session = Session::new(session.id(), store, None);
session.load().await.unwrap();
assert_eq!(session.get::<usize>("foo").await.unwrap().unwrap(), 42);ยงErrors
- If loading from the store fails, we fail with
Error::Store.
sourcepub async fn delete(&self) -> Result<(), Error>
pub async fn delete(&self) -> Result<(), Error>
Deletes the session from the store.
ยงExamples
use std::sync::Arc;
use tower_sessions::{session::Id, MemoryStore, Session, SessionStore};
let store = Arc::new(MemoryStore::default());
let session = Session::new(Some(Id::default()), store.clone(), None);
// Save before deleting.
session.save().await.unwrap();
// Delete from the store.
session.delete().await.unwrap();
assert!(store.load(&session.id().unwrap()).await.unwrap().is_none());ยงErrors
- If deleting from the store fails, we fail with
Error::Store.
sourcepub async fn flush(&self) -> Result<(), Error>
pub async fn flush(&self) -> Result<(), Error>
Flushes the session by removing all data contained in the session and then deleting it from the store.
ยงExamples
use std::sync::Arc;
use tower_sessions::{MemoryStore, Session, SessionStore};
let store = Arc::new(MemoryStore::default());
let session = Session::new(None, store.clone(), None);
session.insert("foo", "bar").await.unwrap();
session.save().await.unwrap();
let id = session.id().unwrap();
session.flush().await.unwrap();
assert!(session.id().is_none());
assert!(session.is_empty().await);
assert!(store.load(&id).await.unwrap().is_none());ยงErrors
- If deleting from the store fails, we fail with
Error::Store.
sourcepub async fn cycle_id(&self) -> Result<(), Error>
pub async fn cycle_id(&self) -> Result<(), Error>
Cycles the session ID while retaining any data that was associated with it.
Using this method helps prevent session fixation attacks by ensuring a new ID is assigned to the session.
ยงExamples
use std::sync::Arc;
use tower_sessions::{session::Id, MemoryStore, Session};
let store = Arc::new(MemoryStore::default());
let session = Session::new(None, store.clone(), None);
session.insert("foo", 42).await.unwrap();
session.save().await.unwrap();
let id = session.id();
let session = Session::new(session.id(), store.clone(), None);
session.cycle_id().await.unwrap();
assert!(!session.is_empty().await);
assert!(session.is_modified());
session.save().await.unwrap();
let session = Session::new(session.id(), store, None);
assert_ne!(id, session.id());
assert_eq!(session.get::<usize>("foo").await.unwrap().unwrap(), 42);ยงErrors
- If deleting from the store fails or saving to the store fails, we fail
with
Error::Store.
Trait Implementationsยง
sourceยงimpl<S> FromRequestParts<S> for Session
impl<S> FromRequestParts<S> for Session
sourceยงtype Rejection = (StatusCode, &'static str)
type Rejection = (StatusCode, &'static str)
sourceยงfn from_request_parts<'life0, 'life1, 'async_trait>(
parts: &'life0 mut Parts,
_state: &'life1 S,
) -> Pin<Box<dyn Future<Output = Result<Session, <Session as FromRequestParts<S>>::Rejection>> + Send + 'async_trait>>where
'life0: 'async_trait,
'life1: 'async_trait,
Session: 'async_trait,
fn from_request_parts<'life0, 'life1, 'async_trait>(
parts: &'life0 mut Parts,
_state: &'life1 S,
) -> Pin<Box<dyn Future<Output = Result<Session, <Session as FromRequestParts<S>>::Rejection>> + Send + 'async_trait>>where
'life0: 'async_trait,
'life1: 'async_trait,
Session: 'async_trait,
Auto Trait Implementationsยง
impl Freeze for Session
impl !RefUnwindSafe for Session
impl Send for Session
impl Sync for Session
impl Unpin for Session
impl !UnwindSafe for Session
Blanket Implementationsยง
sourceยงimpl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
sourceยงfn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
sourceยงimpl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
sourceยงunsafe fn clone_to_uninit(&self, dst: *mut T)
unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit)