Skip to content

Commit

Permalink
simplfy strongly-typed example
Browse files Browse the repository at this point in the history
  • Loading branch information
maxcountryman committed Jan 22, 2024
1 parent 7631331 commit 1313c26
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 45 deletions.
54 changes: 21 additions & 33 deletions examples/strongly-typed.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
use std::{fmt::Display, net::SocketAddr};
use std::{fmt, net::SocketAddr};

use async_trait::async_trait;
use axum::{extract::FromRequestParts, response::IntoResponse, routing::get, Router};
use http::{request::Parts, StatusCode};
use serde::{Deserialize, Serialize};
use time::{Duration, OffsetDateTime};
use tower_sessions::{session::Id, Expiry, MemoryStore, Session, SessionManagerLayer};
use time::OffsetDateTime;
use tower_sessions::{MemoryStore, Session, SessionManagerLayer};

#[derive(Clone, Deserialize, Serialize)]
struct GuestData {
id: Id,
pageviews: usize,
first_seen: OffsetDateTime,
last_seen: OffsetDateTime,
Expand All @@ -18,7 +17,6 @@ struct GuestData {
impl Default for GuestData {
fn default() -> Self {
Self {
id: Id::default(),
pageviews: 0,
first_seen: OffsetDateTime::now_utc(),
last_seen: OffsetDateTime::now_utc(),
Expand All @@ -34,10 +32,6 @@ struct Guest {
impl Guest {
const GUEST_DATA_KEY: &'static str = "guest.data";

fn id(&self) -> &Id {
&self.guest_data.id
}

fn first_seen(&self) -> OffsetDateTime {
self.guest_data.first_seen
}
Expand All @@ -63,17 +57,13 @@ impl Guest {
}
}

impl Display for Guest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let now = OffsetDateTime::now_utc();
write!(
f,
"Guest ID {}\n\nPageviews {}\n\nFirst seen {} ago\n\nLast seen {} ago\n\n",
self.id(),
self.pageviews(),
now - self.first_seen(),
now - self.last_seen()
)
impl fmt::Display for Guest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Guest")
.field("pageviews", &self.pageviews())
.field("first_seen", &self.first_seen())
.field("last_seen", &self.last_seen())
.finish()
}
}

Expand Down Expand Up @@ -104,12 +94,20 @@ where
}
}

// This demonstrates a `Guest` extractor, but we could have any number of
// namespaced, strongly-typed "buckets" like `Guest` in the same session.
//
// Use cases could include buckets for site preferences, analytics,
// feature flags, etc.
async fn handler(mut guest: Guest) -> impl IntoResponse {
guest.mark_pageview().await;
format!("{}", guest)
}

#[tokio::main]
async fn main() {
let session_store = MemoryStore::default();
let session_layer = SessionManagerLayer::new(session_store)
.with_secure(false)
.with_expiry(Expiry::OnInactivity(Duration::seconds(10)));
let session_layer = SessionManagerLayer::new(session_store).with_secure(false);

let app = Router::new().route("/", get(handler)).layer(session_layer);

Expand All @@ -119,13 +117,3 @@ async fn main() {
.await
.unwrap();
}

// This demonstrates a `Guest` extractor, but we could have any number of
// namespaced, strongly-typed "buckets" like `Guest` in the same session.
//
// Use cases could include buckets for site preferences, analytics,
// feature flags, etc.
async fn handler(mut guest: Guest) -> impl IntoResponse {
guest.mark_pageview().await;
format!("{}", guest)
}
19 changes: 7 additions & 12 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,10 +149,9 @@
//! # use http::{request::Parts, StatusCode};
//! # use serde::{Deserialize, Serialize};
//! # use time::OffsetDateTime;
//! # use tower_sessions::{session::Id, SessionStore, Session};
//! # use tower_sessions::{SessionStore, Session};
//! #[derive(Clone, Deserialize, Serialize)]
//! struct GuestData {
//! id: Id,
//! pageviews: usize,
//! first_seen: OffsetDateTime,
//! last_seen: OffsetDateTime,
Expand All @@ -161,7 +160,6 @@
//! impl Default for GuestData {
//! fn default() -> Self {
//! Self {
//! id: Id::default(),
//! pageviews: 0,
//! first_seen: OffsetDateTime::now_utc(),
//! last_seen: OffsetDateTime::now_utc(),
Expand All @@ -177,10 +175,6 @@
//! impl Guest {
//! const GUEST_DATA_KEY: &'static str = "guest_data";
//!
//! fn id(&self) -> &Id {
//! &self.guest_data.id
//! }
//!
//! fn first_seen(&self) -> OffsetDateTime {
//! self.guest_data.first_seen
//! }
Expand Down Expand Up @@ -329,11 +323,12 @@
//! ### Secure nature of cookies
//!
//! Session IDs are considered secure if sent over encrypted channels, and
//! therefore are not signed or encrypted. Note that this assumption is predicated
//! on the secure nature of the [`rand`](https://docs.rs/rand/latest/rand) crate
//! and its ability to generate securely-random values using the ChaCha block cipher
//! with 12 rounds. It's also important to note that session cookies **must never**
//! be sent over a public, insecure channel. Doing so is **not** secure.
//! therefore are not signed or encrypted. Note that this assumption is
//! predicated on the secure nature of the [`rand`](https://docs.rs/rand/latest/rand) crate
//! and its ability to generate securely-random values using the ChaCha block
//! cipher with 12 rounds. It's also important to note that session cookies
//! **must never** be sent over a public, insecure channel. Doing so is **not**
//! secure.
//!
//! ## Key-value API
//!
Expand Down

0 comments on commit 1313c26

Please sign in to comment.