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>,
) -> Self
pub fn new( session_id: Option<Id>, store: Arc<impl SessionStore>, expiry: Option<Expiry>, ) -> Self
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_value
fails. - 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: DeserializeOwned>(
&self,
key: &str,
) -> Result<Option<T>, Error>
pub async fn get<T: DeserializeOwned>( &self, key: &str, ) -> Result<Option<T>, Error>
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_value
fails. - 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: DeserializeOwned>(
&self,
key: &str,
) -> Result<Option<T>, Error>
pub async fn remove<T: DeserializeOwned>( &self, key: &str, ) -> Result<Option<T>, Error>
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_value
fails. - 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
.