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(expiry: Option<Expiry>) -> Self
pub fn new(expiry: Option<Expiry>) -> Self
Create a new session with the given expiry.
Examples
use time::{Duration, OffsetDateTime};
use tower_sessions::{Expiry, Session};
// Uses a so-called "session cookie".
let expiry = Expiry::OnSessionEnd;
Session::new(Some(expiry));
// Uses an inactivity expiry.
let expiry = Expiry::OnInactivity(Duration::hours(1));
Session::new(Some(expiry));
// Uses a date and time expiry.
let expired_at = OffsetDateTime::now_utc().saturating_add(Duration::hours(1));
let expiry = Expiry::AtDateTime(expired_at);
Session::new(Some(expiry));sourcepub fn insert(&self, key: &str, value: impl Serialize) -> Result<(), Error>
pub fn insert(&self, key: &str, value: impl Serialize) -> Result<(), Error>
Inserts a impl Serialize value into the session.
Examples
use tower_sessions::Session;
let session = Session::default();
session.insert("foo", 42).expect("Serialization error.");Errors
This method can fail when serde_json::to_value fails.
sourcepub fn insert_value(&self, key: &str, value: Value) -> Option<Value>
pub fn insert_value(&self, key: &str, value: Value) -> Option<Value>
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 tower_sessions::Session;
let session = Session::default();
let value = session.insert_value("foo", serde_json::json!(42));
assert!(value.is_none());
let value = session.insert_value("foo", serde_json::json!(42));
assert!(value.is_none());
let value = session.insert_value("foo", serde_json::json!("bar"));
assert_eq!(value, Some(serde_json::json!(42)));sourcepub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>, Error>
pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>, Error>
Gets a value from the store.
Examples
use tower_sessions::Session;
let session = Session::default();
session.insert("foo", 42).unwrap();
let value = session.get::<usize>("foo").unwrap();
assert_eq!(value, Some(42));Errors
This method can fail when serde_json::from_value fails.
sourcepub fn get_value(&self, key: &str) -> Option<Value>
pub fn get_value(&self, key: &str) -> Option<Value>
Gets a serde_json::Value from the store.
Examples
use tower_sessions::Session;
let session = Session::default();
session.insert("foo", 42).unwrap();
let value = session.get_value("foo").unwrap();
assert_eq!(value, serde_json::json!(42));sourcepub fn remove<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>, Error>
pub 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 tower_sessions::Session;
let session = Session::default();
session.insert("foo", 42).unwrap();
let value: Option<usize> = session.remove("foo").unwrap();
assert_eq!(value, Some(42));
let value: Option<usize> = session.get("foo").unwrap();
assert!(value.is_none());Errors
This method can fail when serde_json::from_value fails.
sourcepub fn remove_value(&self, key: &str) -> Option<Value>
pub fn remove_value(&self, key: &str) -> Option<Value>
Removes a serde_json::Value from the store.
Examples
use tower_sessions::Session;
let session = Session::default();
session.insert("foo", 42).unwrap();
let value = session.remove_value("foo").unwrap();
assert_eq!(value, serde_json::json!(42));
let value: Option<usize> = session.get("foo").unwrap();
assert!(value.is_none());sourcepub fn replace_if_equal(
&self,
key: &str,
old_value: impl Serialize,
new_value: impl Serialize
) -> Result<bool, Error>
pub fn replace_if_equal( &self, key: &str, old_value: impl Serialize, new_value: impl Serialize ) -> Result<bool, Error>
Replaces a value in the session with a new value if the current value matches the old value.
If the key was not present in the underlying map or the current value
does not match, false is returned, indicating failure.
If the key was present and its value matches the old value, the new
value is inserted, and true is returned, indicating success.
This method is essential for scenarios where data races need to be
prevented. For instance, reading from and writing to a session is
not transactional. To ensure that read values are not stale, itโs
crucial to use replace_if_equal when modifying the session.
Examples
use tower_sessions::Session;
let session = Session::default();
session.insert("foo", 42).unwrap();
let success = session.replace_if_equal("foo", 42, 43).unwrap();
assert_eq!(success, true);
let success = session.replace_if_equal("foo", 42, 44).unwrap();
assert_eq!(success, false);Errors
This method can fail when serde_json::to_value fails.
sourcepub fn clear(&self)
pub fn clear(&self)
Clears the session data.
Examples
use tower_sessions::Session;
let session = Session::default();
session.insert("foo", 42).unwrap();
session.clear();
assert!(session.get_value("foo").is_none());sourcepub fn delete(&self)
pub fn delete(&self)
Sets deleted on the session to Deletion::Deleted.
Setting this flag indicates the session should be deleted from the underlying store.
This flag is consumed by a session management system to ensure session life cycle progression.
Examples
use tower_sessions::{session::Deletion, Session};
let session = Session::default();
session.delete();
assert!(matches!(session.deleted(), Some(Deletion::Deleted)));sourcepub fn cycle_id(&self)
pub fn cycle_id(&self)
Sets deleted on the session to Deletion::Cycled(self.id)).
Setting this flag indicates the session ID should be cycled while retaining the sessionโs data.
This flag is consumed by a session management system to ensure session life cycle progression.
Examples
use tower_sessions::{session::Deletion, Session};
let session = Session::default();
session.insert("foo", 42);
session.cycle_id();
assert!(matches!(
session.deleted(),
Some(Deletion::Cycled(ref cycled_id)) if cycled_id == session.id()
));sourcepub fn flush(&self)
pub fn flush(&self)
Sets deleted on the session to Deletion::Deleted and clears
the session data.
This helps ensure that session data cannot be accessed beyond this invocation.
Examples
use tower_sessions::{session::Deletion, Session};
let session = Session::default();
session.insert("foo", 42).unwrap();
session.flush();
assert!(session.get_value("foo").is_none());
assert!(matches!(session.deleted(), Some(Deletion::Deleted)));sourcepub fn id(&self) -> &Id
pub fn id(&self) -> &Id
Get the session ID.
Examples
use tower_sessions::Session;
let session = Session::default();
session.id();sourcepub fn expiry(&self) -> Option<Expiry>
pub fn expiry(&self) -> Option<Expiry>
Get the session expiry.
Examples
use time::{Duration, OffsetDateTime};
use tower_sessions::{Expiry, Session};
let expiry = Expiry::OnInactivity(Duration::hours(1));
let session = Session::default();
session.set_expiry(Some(expiry));
assert_eq!(
session.expiry(),
Some(Expiry::OnInactivity(Duration::hours(1)))
);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 time::{Duration, OffsetDateTime};
use tower_sessions::{Expiry, Session};
let session = Session::default();
let expiry = Expiry::AtDateTime(OffsetDateTime::from_unix_timestamp(0).unwrap());
session.set_expiry(Some(expiry));
session.insert("foo", 42);
assert!(session.is_modified());
let expiry = Expiry::OnInactivity(Duration::weeks(2));
session.set_expiry(Some(expiry));
assert!(session.is_modified());sourcepub fn expiry_date(&self) -> OffsetDateTime
pub fn expiry_date(&self) -> OffsetDateTime
Get session expiry as OffsetDateTime.
Examples
use time::OffsetDateTime;
use tower_sessions::Session;
let session = Session::default();
assert!(session.expiry_date() > OffsetDateTime::now_utc());sourcepub fn expiry_age(&self) -> Duration
pub fn expiry_age(&self) -> Duration
Get session expiry as Duration.
Examples
use time::Duration;
use tower_sessions::Session;
let session = Session::default();
assert!(session.expiry_age() > Duration::days(11)); sourcepub fn is_modified(&self) -> bool
pub fn is_modified(&self) -> bool
Returns true if the session has been modified and false otherwise.
Examples
use tower_sessions::Session;
let session = Session::default();
assert!(!session.is_modified());
session.insert("foo", 42);
assert!(session.is_modified());sourcepub fn deleted(&self) -> Option<Deletion>
pub fn deleted(&self) -> Option<Deletion>
Returns Some(Deletion) if one has been set and None
otherwise.
Examples
use tower_sessions::{session::Deletion, Session};
let session = Session::default();
session.insert("foo", 42);
assert!(session.deleted().is_none());
session.delete();
assert!(matches!(session.deleted(), Some(Deletion::Deleted)));
session.cycle_id();
assert!(matches!(session.deleted(), Some(Deletion::Cycled(_))))Trait Implementationsยง
sourceยงimpl<'de> Deserialize<'de> for Session
impl<'de> Deserialize<'de> for Session
sourceยงfn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>,
sourceยงimpl<S> FromRequestParts<S> for Sessionwhere
S: Sync + Send,
Available on crate feature axum-core only.
impl<S> FromRequestParts<S> for Sessionwhere S: Sync + Send,
axum-core only.ยงtype Rejection = (StatusCode, &'static str)
type Rejection = (StatusCode, &'static str)
sourceยงimpl PartialEq for Session
impl PartialEq for Session
impl Eq for Session
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<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,
ยงfn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
ยงimpl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,
ยงfn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.sourceยงimpl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,
sourceยงfn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.ยง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,
sourceยงimpl<S, B, T> FromRequest<S, B, ViaParts> for Twhere
B: Send + 'static,
S: Send + Sync,
T: FromRequestParts<S>,
impl<S, B, T> FromRequest<S, B, ViaParts> for Twhere B: Send + 'static, S: Send + Sync, T: FromRequestParts<S>,
ยงtype Rejection = <T as FromRequestParts<S>>::Rejection
type Rejection = <T as FromRequestParts<S>>::Rejection
ยง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) -> Rwhere
Self: Borrow<B>,
B: 'a + ?Sized,
R: 'a,
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> Rwhere Self: Borrow<B>, B: 'a + ?Sized, R: 'a,
ยงfn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R
) -> Rwhere
Self: BorrowMut<B>,
B: 'a + ?Sized,
R: 'a,
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R ) -> Rwhere Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,
ยงfn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> Rwhere
Self: AsRef<U>,
U: 'a + ?Sized,
R: 'a,
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> Rwhere Self: AsRef<U>, U: 'a + ?Sized, R: 'a,
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) -> Rwhere
Self: AsMut<U>,
U: 'a + ?Sized,
R: 'a,
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> Rwhere Self: AsMut<U>, U: 'a + ?Sized, R: 'a,
self, then passes self.as_mut() 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)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Selfwhere Self: Borrow<B>, B: ?Sized,
Borrow<B> of a value. Read moreยงfn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere Self: BorrowMut<B>, B: ?Sized,
BorrowMut<B> of a value. Read moreยงfn tap_ref<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Selfwhere Self: AsRef<R>, R: ?Sized,
AsRef<R> view of a value. Read moreยงfn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere Self: AsMut<R>, R: ?Sized,
AsMut<R> view of a value. Read moreยงfn tap_deref<T>(self, func: impl FnOnce(&T)) -> Selfwhere
Self: Deref<Target = T>,
T: ?Sized,
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Selfwhere Self: Deref<Target = T>, T: ?Sized,
Deref::Target of a value. Read moreยงfn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Selfwhere
Self: DerefMut<Target = T> + Deref,
T: ?Sized,
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Selfwhere Self: DerefMut<Target = T> + Deref, T: ?Sized,
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)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Selfwhere Self: Borrow<B>, B: ?Sized,
.tap_borrow() only in debug builds, and is erased in release
builds.ยงfn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere Self: BorrowMut<B>, B: ?Sized,
.tap_borrow_mut() only in debug builds, and is erased in release
builds.ยงfn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Selfwhere Self: AsRef<R>, R: ?Sized,
.tap_ref() only in debug builds, and is erased in release
builds.ยงfn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere Self: AsMut<R>, R: ?Sized,
.tap_ref_mut() only in debug builds, and is erased in release
builds.