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());
let session = Session::new(session.id(), store, None);
// ...but 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 give 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
ยง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 !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
ยงimpl<T> Conv for T
impl<T> Conv for T
ยงimpl<T> FmtForward for T
impl<T> FmtForward for T
ยงfn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self to use its Binary implementation when Debug-formatted.ยงfn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self to use its Display implementation when
Debug-formatted.ยงfn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self to use its LowerExp implementation when
Debug-formatted.ยงfn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self to use its LowerHex implementation when
Debug-formatted.ยงfn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self to use its Octal implementation when Debug-formatted.ยงfn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self to use its Pointer implementation when
Debug-formatted.ยงfn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self to use its UpperExp implementation when
Debug-formatted.ยงfn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self to use its UpperHex implementation when
Debug-formatted.ยงfn fmt_list(self) -> FmtList<Self>where
&'a Self: for<'a> IntoIterator,
fn fmt_list(self) -> FmtList<Self>where
&'a Self: for<'a> IntoIterator,
ยงimpl<S, T> FromRequest<S, ViaParts> for T
impl<S, T> FromRequest<S, ViaParts> for T
ยงimpl<T> Instrument for T
impl<T> Instrument for T
ยงfn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
ยงfn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
ยงimpl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
ยงfn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
ยงfn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreยงfn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreยงfn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
ยงfn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R ) -> R
ยงfn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
self, then passes self.as_ref() into the pipe function.ยงfn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
self, then passes self.as_mut() into the pipe
function.ยงfn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self, then passes self.deref() into the pipe function.ยงimpl<T> Pointable for T
impl<T> Pointable for T
ยงimpl<T> Tap for T
impl<T> Tap for T
ยงfn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B> of a value. Read moreยงfn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B> of a value. Read moreยงfn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R> view of a value. Read moreยงfn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R> view of a value. Read moreยงfn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target of a value. Read moreยงfn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target of a value. Read moreยงfn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap() only in debug builds, and is erased in release builds.ยงfn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut() only in debug builds, and is erased in release
builds.ยงfn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.tap_borrow() only in debug builds, and is erased in release
builds.ยงfn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.tap_borrow_mut() only in debug builds, and is erased in release
builds.ยงfn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.tap_ref() only in debug builds, and is erased in release
builds.ยงfn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.tap_ref_mut() only in debug builds, and is erased in release
builds.ยงfn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref() only in debug builds, and is erased in release
builds.