From 63e89b04b42f4b5e98d13c2905ee3b5aa329406d Mon Sep 17 00:00:00 2001 From: Sergio Benitez Date: Wed, 8 Mar 2017 14:25:58 -0800 Subject: [PATCH] Rename Session::add to Session::set. Also set a default expiration of 3 hours for session cookies. --- examples/session/src/main.rs | 2 +- lib/Cargo.toml | 2 +- lib/src/http/session.rs | 11 ++++++++++- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/examples/session/src/main.rs b/examples/session/src/main.rs index a94f98e2..7bb21eb2 100644 --- a/examples/session/src/main.rs +++ b/examples/session/src/main.rs @@ -40,7 +40,7 @@ impl<'a, 'r> FromRequest<'a, 'r> for User { #[post("/login", data = "")] fn login(mut session: Session, login: Form) -> Flash { if login.get().username == "Sergio" && login.get().password == "password" { - session.add(Cookie::new("user_id", 1.to_string())); + session.set(Cookie::new("user_id", 1.to_string())); Flash::success(Redirect::to("/"), "Successfully logged in.") } else { Flash::error(Redirect::to("/login"), "Invalid username/password.") diff --git a/lib/Cargo.toml b/lib/Cargo.toml index e2a85b2f..f58204ff 100644 --- a/lib/Cargo.toml +++ b/lib/Cargo.toml @@ -30,7 +30,7 @@ memchr = "1" base64 = "0.4" [dependencies.cookie] -version = "^0.7" +version = "0.7.2" features = ["percent-encode", "secure"] [dev-dependencies] diff --git a/lib/src/http/session.rs b/lib/src/http/session.rs index efcb7920..09f837ce 100644 --- a/lib/src/http/session.rs +++ b/lib/src/http/session.rs @@ -1,5 +1,6 @@ use std::cell::{RefCell, RefMut}; +use time::{self, Duration}; use cookie::{Cookie, CookieJar, Delta}; pub use cookie::Key; @@ -42,12 +43,20 @@ impl<'a> Session<'a> { self.cookies.borrow_mut().private(&self.key).get(name) } - pub fn add(&mut self, mut cookie: Cookie<'static>) { + pub fn set(&mut self, mut cookie: Cookie<'static>) { cookie.set_http_only(true); + if cookie.path().is_none() { cookie.set_path("/"); } + // TODO: Should this be configurable? + if cookie.max_age().is_none() && cookie.expires().is_none() { + let session_lifetime = Duration::hours(3); + cookie.set_max_age(session_lifetime); + cookie.set_expires(time::now() + session_lifetime); + } + self.cookies.get_mut().private(&self.key).add(cookie) }