Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change session renewal #42

Merged
merged 5 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion examples/turbo/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ async fn main() -> Result<(), Error> {
// Not mandatory, but helpful for this demo.
Migrations::migrate().await?;

#[cfg(debug_assertions)]
let static_files = StaticFiles::serve("static")?;
#[cfg(not(debug_assertions))]
let static_files = StaticFiles::cached("static", Duration::hours(1))?;

let mut routes = vec![
route!("/" => IndexController),
route!("/turbo-stream" => TurboStreamController),
Expand All @@ -49,7 +54,7 @@ async fn main() -> Result<(), Error> {
route!("/chat" => ChatController),
route!("/chat/typing" => TypingController),
engine!("/admin" => rwf_admin::engine()),
StaticFiles::serve("static")?,
static_files,
];
routes.extend(rwf_admin::routes()?);

Expand Down
2 changes: 1 addition & 1 deletion rwf/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "rwf"
version = "0.1.11"
version = "0.1.12"
edition = "2021"
license = "MIT"
description = "Framework for building web applications in the Rust programming language"
Expand Down
35 changes: 35 additions & 0 deletions rwf/src/controller/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,18 @@ impl Session {
self
}

/// The session is close to being expired and should be renewed automatically.
pub fn should_renew(&self) -> bool {
if let Ok(expiration) = OffsetDateTime::from_unix_timestamp(self.expiration) {
let now = OffsetDateTime::now_utc();
let remains = expiration - now;
let session_duration = get_config().general.session_duration();
remains < session_duration / 2 && remains.is_positive() // not expired
} else {
true
}
}

/// Check if the session has expired.
pub fn expired(&self) -> bool {
if let Ok(expiration) = OffsetDateTime::from_unix_timestamp(self.expiration) {
Expand Down Expand Up @@ -312,3 +324,26 @@ impl Authentication for SessionAuth {
}
}
}

#[cfg(test)]
mod test {
use super::*;

#[test]
fn test_should_renew() {
let mut session = Session::default();
assert!(!session.should_renew());

assert_eq!(get_config().general.session_duration(), Duration::weeks(4));

session.expiration = (OffsetDateTime::now_utc() + Duration::weeks(2)
- Duration::seconds(5))
.unix_timestamp();
assert!(session.should_renew());

session.expiration =
(OffsetDateTime::now_utc() + Duration::weeks(2) + Duration::seconds(5))
.unix_timestamp();
assert!(!session.should_renew());
}
}
37 changes: 28 additions & 9 deletions rwf/src/controller/middleware/request_tracker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,22 +48,24 @@ impl Middleware for RequestTracker {
((OffsetDateTime::now_utc() - request.received_at()).as_seconds_f64() * 1000.0) as f32;
let client = request.peer().ip();

let client_id = match request
let (client_id, missing) = match request
.cookies()
.get(COOKIE_NAME)
.map(|cookie| Uuid::parse_str(cookie.value()))
{
Some(Ok(cookie)) => cookie,
_ => Uuid::new_v4(),
Some(Ok(cookie)) => (cookie, false),
_ => (Uuid::new_v4(), true),
};

let cookie = CookieBuilder::new()
.name(COOKIE_NAME)
.value(client_id.to_string())
.max_age(Duration::weeks(4))
.build();
if missing {
let cookie = CookieBuilder::new()
.name(COOKIE_NAME)
.value(client_id.to_string())
.max_age(Duration::weeks(4))
.build();

response = response.cookie(cookie);
response = response.cookie(cookie);
}

if let Ok(mut conn) = Pool::connection().await {
let _ = AnalyticsRequest::create(&[
Expand All @@ -82,3 +84,20 @@ impl Middleware for RequestTracker {
Ok(response)
}
}

#[cfg(test)]
mod test {
use super::*;

#[tokio::test]
async fn test_request_tracker() {
let request = Request::default();
let response = Response::default();

let mut response = RequestTracker::new()
.handle_response(&request, response)
.await
.unwrap();
assert!(response.cookies().get(COOKIE_NAME).is_some());
}
}
2 changes: 1 addition & 1 deletion rwf/src/controller/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ pub use auth::{AllowAll, AuthHandler, Authentication, BasicAuth, DenyAll, Sessio
pub use engine::Engine;
pub use error::Error;
pub use middleware::{Middleware, MiddlewareHandler, MiddlewareSet, Outcome, RateLimiter};
pub use static_files::StaticFiles;
pub use static_files::{Cache, CacheControl, StaticFiles};
pub use turbo_stream::TurboStream;

use super::http::{
Expand Down
71 changes: 70 additions & 1 deletion rwf/src/controller/static_files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,59 @@ use std::{
};

use async_trait::async_trait;
use time::Duration;
use tokio::fs::File;
use tracing::debug;

/// Cache behavior.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Cache {
Public,
Private,
}

impl std::fmt::Display for Cache {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
use Cache::*;
let s = match self {
Public => "public",
Private => "private".into(),
};

write!(f, "{}", s)
}
}

/// Cache control header.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum CacheControl {
NoStore,
MaxAge(Duration),
Private,
NoCache,
}

impl std::fmt::Display for CacheControl {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
use CacheControl::*;
let s = match self {
NoStore => "no-store".into(),
MaxAge(duration) => format!("max-age={}", duration.whole_seconds()),
Private => "private".into(),
NoCache => "no-cache".into(),
};

write!(f, "{}", s)
}
}

/// Static files controller.
pub struct StaticFiles {
prefix: PathBuf,
root: PathBuf,
preloads: HashMap<PathBuf, Body>,
cache_control: CacheControl,
cache: Cache,
}

impl StaticFiles {
Expand All @@ -48,11 +93,21 @@ impl StaticFiles {
prefix: PathBuf::from("/").join(path),
root,
preloads: HashMap::new(),
cache_control: CacheControl::NoStore,
cache: Cache::Public,
};

Ok(statics)
}

/// Serve static files with the specified `Cache-Control: max-age` attribute.
pub fn cached(path: &str, duration: Duration) -> std::io::Result<Handler> {
Ok(Self::new(path)?
.cache_control(CacheControl::MaxAge(duration))
.cache(Cache::Public)
.handler())
}

/// Preload a static file into memory. This allows static files to load and serve files
/// which may not be available at runtime, e.g. by using [`include_bytes`].
///
Expand All @@ -72,6 +127,18 @@ impl StaticFiles {
self
}

/// Set the `Cache-Control` header.
pub fn cache_control(mut self, cache_control: CacheControl) -> Self {
self.cache_control = cache_control;
self
}

/// Set the `Cache` header.
pub fn cache(mut self, cache: Cache) -> Self {
self.cache = cache;
self
}

/// Set the prefix used in URLs.
///
/// For example, if the prefix `static` is set,
Expand Down Expand Up @@ -140,7 +207,9 @@ impl Controller for StaticFiles {
return Ok(Response::not_found());
}

let response = Response::new();
let response = Response::new()
.header("cache-control", self.cache_control.to_string())
.header("cache", self.cache.to_string());

Ok(response.body((path, file, metadata)))
}
Expand Down
4 changes: 2 additions & 2 deletions rwf/src/http/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ impl Body {
/// ```
/// # use rwf::http::Body;
/// let body = Body::html("<h1>Hello from Rwf!</h1>");
/// assert_eq!(body.mime_type(), "text/html");
/// assert_eq!(body.mime_type(), "text/html; charset=utf-8");
/// ```
pub fn mime_type(&self) -> &'static str {
use Body::*;
Expand Down Expand Up @@ -219,7 +219,7 @@ impl Body {
}
}
Text(_) => "text/plain",
Html(_) => "text/html",
Html(_) => "text/html; charset=utf-8",
Json(_) => "application/json",
Bytes(_) => "application/octet-stream",
}
Expand Down
21 changes: 14 additions & 7 deletions rwf/src/http/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,21 @@ impl Default for Request {
}
}

#[derive(Debug, Default, Clone)]
#[derive(Debug, Clone)]
struct Inner {
body: Vec<u8>,
cookies: Cookies,
peer: Option<SocketAddr>,
peer: SocketAddr,
}

impl Default for Inner {
fn default() -> Inner {
Inner {
body: Vec::default(),
cookies: Cookies::default(),
peer: "127.0.0.1:8000".parse().unwrap(), // Just used for testing.
}
}
}

impl Request {
Expand Down Expand Up @@ -92,7 +102,7 @@ impl Request {
session: cookies.get_session()?,
inner: Arc::new(Inner {
body,
peer: Some(peer),
peer,
cookies,
}),
received_at: OffsetDateTime::now_utc(),
Expand All @@ -105,10 +115,7 @@ impl Request {
/// This is the IP address of the TCP socket, and does
/// not have to be the actual client's IP address.
pub fn peer(&self) -> &SocketAddr {
self.inner
.peer
.as_ref()
.expect("peer is not set on the request")
&self.inner.peer
}

/// Set params on the request.
Expand Down
12 changes: 11 additions & 1 deletion rwf/src/http/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ impl Response {
let session = request.session();

if let Some(session) = session {
if !session.expired() {
if session.should_renew() {
let session = session
.clone()
.renew(get_config().general.session_duration());
Expand Down Expand Up @@ -543,6 +543,16 @@ impl Response {
.header("upgrade", protocol)
.code(101)
}

/// Response headers.
pub fn headers(&self) -> &Headers {
&self.headers
}

/// Mutable response headers.
pub fn headers_mut(&mut self) -> &mut Headers {
&mut self.headers
}
}

impl From<serde_json::Value> for Response {
Expand Down
Loading