diff options
| author | Owen Jacobson <owen@grimoire.ca> | 2024-09-04 01:25:31 -0400 |
|---|---|---|
| committer | Owen Jacobson <owen@grimoire.ca> | 2024-09-04 01:25:54 -0400 |
| commit | 072dfa9a0bae5b7e9ea1caa97f6a90bd576a5d95 (patch) | |
| tree | 3194c56bbf1b9729d07198973815c0cb88a9e5c6 /src/clock.rs | |
| parent | 2965a788cfcf4a0386cb8832e0d96491bf54c1d3 (diff) | |
Expire sessions after 90 days.
Diffstat (limited to 'src/clock.rs')
| -rw-r--r-- | src/clock.rs | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/src/clock.rs b/src/clock.rs new file mode 100644 index 0000000..e53d825 --- /dev/null +++ b/src/clock.rs @@ -0,0 +1,51 @@ +use axum::{ + extract::{Extension, FromRequestParts, Request}, + http::{request::Parts, StatusCode}, + middleware::Next, + response::Response, +}; +use chrono::{DateTime, Utc}; + +/// Extractor that provides the "current time" for a request. This time is calculated +/// once per request, even if the extractor is used in multiple places. This requires +/// the [middleware] function to be installed with [axum::middleware::from_fn] around +/// the current route. +#[derive(Clone)] +pub struct RequestedAt(pub DateTime<Utc>); + +impl RequestedAt { + fn now() -> Self { + Self(Utc::now()) + } + + pub fn timestamp(&self) -> DateTime<Utc> { + self.0 + } +} + +#[async_trait::async_trait] +impl<S> FromRequestParts<S> for RequestedAt +where + S: Send + Sync, +{ + type Rejection = <Extension<RequestedAt> as FromRequestParts<S>>::Rejection; + + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { + // This is purely for ergonomics: it allows `RequestedAt` to be extracted + // without having to wrap it in `Extension<>`. Callers _can_ still do that, + // but they aren't forced to. + let Extension(requested_at) = + Extension::<RequestedAt>::from_request_parts(parts, state).await?; + + Ok(requested_at) + } +} + +/// Computes a canonical "requested at" time for each request it wraps. This +/// time can be recovered using the [RequestedAt] extractor. +pub async fn middleware(mut req: Request, next: Next) -> Result<Response, StatusCode> { + let now = RequestedAt::now(); + req.extensions_mut().insert(now); + + Ok(next.run(req).await) +} |
