Skip to main content

Sessions

Struct Sessions 

Source
pub struct Sessions<St, S = Uuid> { /* private fields */ }
Available on crate feature axum only.
Expand description

Login, logout and step-up for handlers: the guard, the request’s ClientContext and the session cookie it carries, in one extractor.

It takes the guard from the router state (anything with FromRef for Guard<St, S>, including the guard itself) and needs ConnectInfo<SocketAddr> like the layer; without it the request fails closed with MissingConnectInfo. It does not authenticate anything, so put step-up routes outside the GuardLayer: the layer would answer step_up_required before the handler runs.

Every result converts into a response: NewSession and IssuedToken set the cookie, LoggedOut deletes it, and GuardError and StepUpError become the matching error. Verifying credentials, and rate limiting the routes that do, stays with the app.

use std::net::SocketAddr;

use axum::{Router, http::StatusCode, routing::post};
use session_guard::{
    Guard, GuardError, IssuedToken, MemoryStore, NewSession,
    axum::{LoggedOut, Sessions, StepUpError},
};
use uuid::Uuid;

// Stands in for the app's own credential check.
async fn verify() -> Uuid {
    Uuid::nil()
}

async fn login(sessions: Sessions<MemoryStore>) -> Result<(NewSession, StatusCode), GuardError> {
    let user = verify().await;
    Ok((sessions.login(&user).await?, StatusCode::NO_CONTENT))
}

async fn step_up(sessions: Sessions<MemoryStore>) -> Result<(IssuedToken, StatusCode), StepUpError> {
    let user = verify().await;
    Ok((sessions.complete_step_up(&user).await?, StatusCode::NO_CONTENT))
}

async fn logout(sessions: Sessions<MemoryStore>) -> Result<(LoggedOut, StatusCode), GuardError> {
    Ok((sessions.logout().await?, StatusCode::NO_CONTENT))
}

let guard = Guard::new(MemoryStore::new());
let app = Router::new()
    .route("/login", post(login))
    .route("/step-up", post(step_up))
    .route("/logout", post(logout))
    .with_state(guard);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await

Implementations§

Source§

impl<St: SessionStore, S: Subject> Sessions<St, S>

Source

pub async fn login(&self, subject: &S) -> Result<NewSession, GuardError>

Guard::login for subject, revoking the session the request presented, if any. Call it only after verifying the subject’s credentials.

§Errors

As Guard::login.

Source

pub async fn logout(&self) -> Result<LoggedOut, GuardError>

Guard::logout for the presented session. The result deletes the cookie even when there was no session to revoke.

§Errors

As Guard::logout.

Source

pub async fn complete_step_up( &self, verified_subject: &S, ) -> Result<IssuedToken, StepUpError>

Guard::complete_step_up for the presented session, once the app has verified verified_subject’s credentials again.

§Errors

A StepUpError: the subject does not own the session, there is no live session (including no cookie at all), or the guard failed.

Source

pub fn guard(&self) -> &Guard<St, S>

The guard, for anything else (listing or revoking sessions).

Source

pub fn client(&self) -> &ClientContext

The request’s client context.

Source

pub fn token(&self) -> Option<&str>

The session cookie’s value, if the request carried one. Not validated.

Trait Implementations§

Source§

impl<St, S> Debug for Sessions<St, S>

Source§

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

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

impl<T, St, S> FromRequestParts<T> for Sessions<St, S>
where T: Send + Sync, Guard<St, S>: FromRef<T>, St: SessionStore, S: Subject,

Source§

type Rejection = MissingConnectInfo

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( parts: &mut Parts, state: &T, ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send

Perform the extraction.
Source§

impl<St, S> OperationInput for Sessions<St, S>

Available on crate feature aide only.
Source§

fn operation_input(ctx: &mut GenContext, operation: &mut Operation)

Modify the operation. Read more
Source§

fn inferred_early_responses( ctx: &mut GenContext, operation: &mut Operation, ) -> Vec<(Option<u16>, Response)>

Inferred early responses are used to document early returns for extractors, guards inside handlers. For example these could represent JSON parsing errors, authentication failures. Read more

Auto Trait Implementations§

§

impl<St, S = Uuid> !RefUnwindSafe for Sessions<St, S>

§

impl<St, S = Uuid> !UnwindSafe for Sessions<St, S>

§

impl<St, S> Freeze for Sessions<St, S>
where Guard<St, S>: Freeze,

§

impl<St, S> Send for Sessions<St, S>
where Guard<St, S>: Send,

§

impl<St, S> Sync for Sessions<St, S>
where Guard<St, S>: Sync,

§

impl<St, S> Unpin for Sessions<St, S>
where Guard<St, S>: Unpin,

§

impl<St, S> UnsafeUnpin for Sessions<St, S>
where Guard<St, S>: UnsafeUnpin,

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

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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

Source§

fn into_api<A>(self) -> UseApi<T, A>
where T: Sized,

into UseApi
Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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