Rename Session::add to Session::set.

Also set a default expiration of 3 hours for session cookies.
This commit is contained in:
Sergio Benitez 2017-03-08 14:25:58 -08:00
parent 4f8894f645
commit 63e89b04b4
3 changed files with 12 additions and 3 deletions

View File

@ -40,7 +40,7 @@ impl<'a, 'r> FromRequest<'a, 'r> for User {
#[post("/login", data = "<login>")]
fn login(mut session: Session, login: Form<Login>) -> Flash<Redirect> {
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.")

View File

@ -30,7 +30,7 @@ memchr = "1"
base64 = "0.4"
[dependencies.cookie]
version = "^0.7"
version = "0.7.2"
features = ["percent-encode", "secure"]
[dev-dependencies]

View File

@ -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)
}