Session

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>, ) -> 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);
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>(&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>(&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<(), Error>

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ยง

async fn from_request_parts( parts: &mut Parts, _state: &S, ) -> Result<Session, <Session as FromRequestParts<S>>::Rejection>

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( req: Request<Body>, state: &S, ) -> impl Future<Output = Result<T, <T as FromRequest<S, ViaParts>>::Rejection>>

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> Same for T

Sourceยง

type Output = T

Should always be Self
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