pub struct SessionMiddleware<Store> { /* private fields */ }
Expand description

Middleware to enable sessions.

See sessions for an overview of tide’s approach to sessions.

Example

let mut app = tide::new();

app.with(tide::sessions::SessionMiddleware::new(
    tide::sessions::MemoryStore::new(),
    b"we recommend you use std::env::var(\"TIDE_SECRET\").unwrap().as_bytes() instead of a fixed value"
));

app.with(tide::utils::Before(|mut request: tide::Request<()>| async move {
    let session = request.session_mut();
    let visits: usize = session.get("visits").unwrap_or_default();
    session.insert("visits", visits + 1).unwrap();
    request
}));

app.at("/").get(|req: tide::Request<()>| async move {
    let visits: usize = req.session().get("visits").unwrap();
    Ok(format!("you have visited this website {} times", visits))
});

app.at("/reset")
    .get(|mut req: tide::Request<()>| async move {
        req.session_mut().destroy();
        Ok(tide::Redirect::new("/"))
     });

Implementations§

source§

impl<Store> SessionMiddleware<Store>where Store: SessionStore,

source

pub fn new(store: Store, secret: &[u8]) -> SessionMiddleware<Store>

Creates a new SessionMiddleware with a mandatory cookie signing secret. The secret MUST be at least 32 bytes long, and MUST be cryptographically random to be secure. It is recommended to retrieve this at runtime from the environment instead of compiling it into your application.

Panics

SessionMiddleware::new will panic if the secret is fewer than 32 bytes.

Defaults

The defaults for SessionMiddleware are:

  • cookie path: “/”
  • cookie name: “tide.sid”
  • session ttl: one day
  • same site: strict
  • save unchanged: enabled
Customization

Although the above defaults are appropriate for most applications, they can be overridden. Please be careful changing these settings, as they can weaken your application’s security:

let mut app = tide::new();
app.with(
    SessionMiddleware::new(MemoryStore::new(), b"please do not hardcode your secret")
        .with_cookie_name("custom.cookie.name")
        .with_cookie_path("/some/path")
        .with_cookie_domain("www.rust-lang.org")
        .with_same_site_policy(SameSite::Lax)
        .with_session_ttl(Some(Duration::from_secs(1)))
        .without_save_unchanged(),
);

Sets a cookie path for this session middleware. The default for this value is “/”

source

pub fn with_session_ttl( self, session_ttl: Option<Duration> ) -> SessionMiddleware<Store>

Sets a session ttl. This will be used both for the cookie expiry and also for the session-internal expiry.

The default for this value is one day. Set this to None to not set a cookie or session expiry. This is not recommended.

Sets the name of the cookie that the session is stored with or in.

If you are running multiple tide applications on the same domain, you will need different values for each application. The default value is “tide.sid”

source

pub fn without_save_unchanged(self) -> SessionMiddleware<Store>

Disables the save_unchanged setting. When save_unchanged is enabled, a session will cookie will always be set. With save_unchanged disabled, the session data must be modified from the Default value in order for it to save. If a session already exists and its data unmodified in the course of a request, the session will only be persisted if save_unchanged is enabled.

source

pub fn with_same_site_policy(self, policy: SameSite) -> SessionMiddleware<Store>

Sets the same site policy for the session cookie. Defaults to SameSite::Strict. See incrementally better cookies for more information about this setting

Sets the domain of the cookie.

Trait Implementations§

source§

impl<Store> Debug for SessionMiddleware<Store>where Store: SessionStore,

source§

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

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

impl<Store, State> Middleware<State> for SessionMiddleware<Store>where Store: SessionStore, State: Clone + Send + Sync + 'static,

source§

fn handle<'life0, 'life1, 'async_trait>( &'life0 self, request: Request<State>, next: Next<'life1, State> ) -> Pin<Box<dyn Future<Output = Result<Response, Error>> + Send + 'async_trait, Global>>where 'life0: 'async_trait, 'life1: 'async_trait, SessionMiddleware<Store>: 'async_trait,

Asynchronously handle the request, and return a response.
source§

fn name(&self) -> &str

Set the middleware’s name. By default it uses the type signature.

Auto Trait Implementations§

§

impl<Store> RefUnwindSafe for SessionMiddleware<Store>where Store: RefUnwindSafe,

§

impl<Store> Send for SessionMiddleware<Store>where Store: Send,

§

impl<Store> Sync for SessionMiddleware<Store>where Store: Sync,

§

impl<Store> Unpin for SessionMiddleware<Store>where Store: Unpin,

§

impl<Store> UnwindSafe for SessionMiddleware<Store>where Store: UnwindSafe,

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere 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<T> for T

§

type Output = T

Should always be Self
source§

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

§

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 Twhere U: TryFrom<T>,

§

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

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

§

fn vzip(self) -> V