Struct 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

Source

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);
Source

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
Source

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.
Source

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
Source

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.
Source

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
Source

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.
Source

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));
Source

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);
Source

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());
Source

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);
Source

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));
Source

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)));
Source

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)));
Source

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());
Source

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
Source

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.
Source

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.
Source

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.
Source

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 Clone for Session

Source§

fn clone(&self) -> Session

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Session

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<S> FromRequestParts<S> for Session
where S: Sync + Send,

Source§

type Rejection = (StatusCode, &'static str)

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

fn from_request_parts<'life0, 'life1, 'async_trait>( parts: &'life0 mut Parts, _state: &'life1 S, ) -> Pin<Box<dyn Future<Output = Result<Self, Self::Rejection>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Perform the extraction.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<S, T> FromRequest<S, ViaParts> for T
where S: Send + Sync, T: FromRequestParts<S>,

Source§

type Rejection = <T as FromRequestParts<S>>::Rejection

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

fn from_request<'life0, 'async_trait>( req: Request<Body>, state: &'life0 S, ) -> Pin<Box<dyn Future<Output = Result<T, <T as FromRequest<S, ViaParts>>::Rejection>> + Send + 'async_trait>>
where 'life0: 'async_trait, T: 'async_trait,

Perform the extraction.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more