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(expiration_time: Option<OffsetDateTime>) -> Self
pub fn new(expiration_time: Option<OffsetDateTime>) -> Self
Create a new session with defaults.
If an expiration_time is not specified, the session will use an
expiration strategy of โSession,โ which means it will persist only
until the userโs session ends.
Examples
use tower_sessions::Session;
let session = Session::default();sourcepub fn insert(
&self,
key: &str,
value: impl Serialize
) -> Result<(), SessionError>
pub fn insert( &self, key: &str, value: impl Serialize ) -> Result<(), SessionError>
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>, SessionError>
pub fn get<T: DeserializeOwned>( &self, key: &str ) -> Result<Option<T>, SessionError>
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>, SessionError>
pub fn remove<T: DeserializeOwned>( &self, key: &str ) -> Result<Option<T>, SessionError>
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, SessionError>
pub fn replace_if_equal( &self, key: &str, old_value: impl Serialize, new_value: impl Serialize ) -> Result<bool, SessionError>
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 SessionDeletion::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::SessionDeletion, Session};
let session = Session::default();
session.delete();
assert!(matches!(session.deleted(), Some(SessionDeletion::Deleted)));sourcepub fn cycle_id(&self)
pub fn cycle_id(&self)
Sets deleted on the session to SessionDeletion::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::SessionDeletion, Session};
let session = Session::default();
session.insert("foo", 42);
session.cycle_id();
assert!(matches!(
session.deleted(),
Some(SessionDeletion::Cycled(ref cycled_id)) if cycled_id == session.id()
));sourcepub fn flush(&self)
pub fn flush(&self)
Sets deleted on the session to SessionDeletion::Deleted and clears
the session data.
This helps ensure that session data cannot be accessed beyond this invocation.
Examples
use tower_sessions::{session::SessionDeletion, Session};
let session = Session::default();
session.insert("foo", 42).unwrap();
session.flush();
assert!(session.get_value("foo").is_none());
assert!(matches!(session.deleted(), Some(SessionDeletion::Deleted)));sourcepub fn id(&self) -> &SessionId
pub fn id(&self) -> &SessionId
Get the session ID.
Examples
use tower_sessions::Session;
let session = Session::default();
session.id();sourcepub fn expiration_time(&self) -> Option<OffsetDateTime>
pub fn expiration_time(&self) -> Option<OffsetDateTime>
Get the session expiration time.
Examples
use time::{Duration, OffsetDateTime};
use tower_sessions::Session;
let expiration_time = OffsetDateTime::now_utc().saturating_add(Duration::hours(1));
let session = Session::new(Some(expiration_time));
assert!(session
.expiration_time()
.is_some_and(|et| et > OffsetDateTime::now_utc()));sourcepub fn set_expiration_time(&self, expiration_time: OffsetDateTime)
pub fn set_expiration_time(&self, expiration_time: OffsetDateTime)
Set expiration_time 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::Session;
let session = Session::default();
session.set_expiration_time(OffsetDateTime::now_utc());
session.insert("foo", 42);
assert!(!session.active());
assert!(session.modified());
session.set_expiration_time(OffsetDateTime::now_utc().saturating_add(Duration::hours(1)));
assert!(session.active());
assert!(session.modified());sourcepub fn set_expiration_time_from_max_age(&self, max_age: Duration)
pub fn set_expiration_time_from_max_age(&self, max_age: Duration)
Set expiration_time to current time in UTC plus the given max_age
duration.
This may be used within applications directly to alter the sessionโs time to live.
Examples
use time::Duration;
use tower_sessions::Session;
let session = Session::default();
session.insert("foo", 42);
session.set_expiration_time_from_max_age(Duration::minutes(5));
assert!(session.active());
assert!(session.modified());
session.set_expiration_time_from_max_age(Duration::ZERO);
assert!(!session.active());
assert!(session.modified());sourcepub fn active(&self) -> bool
pub fn active(&self) -> bool
Returns true if the session is active and false otherwise.
Examples
use time::{Duration, OffsetDateTime};
use tower_sessions::Session;
let session = Session::default();
assert!(session.active());
let expiration_time = OffsetDateTime::now_utc().saturating_add(Duration::hours(1));
let session = Session::new(Some(expiration_time));
assert!(session.active());
let expiration_time = OffsetDateTime::now_utc().saturating_add(Duration::ZERO);
let session = Session::new(Some(expiration_time));
assert!(!session.active());sourcepub fn modified(&self) -> bool
pub fn 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.modified());
session.insert("foo", 42);
assert!(session.modified());sourcepub fn deleted(&self) -> Option<SessionDeletion>
pub fn deleted(&self) -> Option<SessionDeletion>
Returns Some(SessionDeletion) if one has been set and None
otherwise.
Examples
use tower_sessions::{session::SessionDeletion, Session};
let session = Session::default();
session.insert("foo", 42);
assert!(session.deleted().is_none());
session.delete();
assert!(matches!(session.deleted(), Some(SessionDeletion::Deleted)));
session.cycle_id();
assert!(matches!(
session.deleted(),
Some(SessionDeletion::Cycled(_))
))Trait Implementationsยง
sourceยงimpl From<&CookieConfig> for Session
impl From<&CookieConfig> for Session
sourceยงfn from(cookie_config: &CookieConfig) -> Self
fn from(cookie_config: &CookieConfig) -> Self
sourceยงimpl From<&Session> for SessionRecord
impl From<&Session> for SessionRecord
sourceยงimpl From<SessionRecord> for Session
impl From<SessionRecord> for Session
sourceยงfn from(_: SessionRecord) -> Self
fn from(_: SessionRecord) -> Self
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
sourceยงimpl<T> Instrument for T
impl<T> Instrument for T
sourceยงfn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
sourceยง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.