Created
April 2, 2017 22:11
-
-
Save Technius/24d6bbafd1155c7a923aee92a104592a to your computer and use it in GitHub Desktop.
iron-sessionstorage sub path cookie bug
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate iron; | |
extern crate mount; | |
extern crate router; | |
extern crate iron_sessionstorage; | |
use iron::prelude::*; | |
use iron_sessionstorage::SessionRequestExt; | |
use iron_sessionstorage::SessionStorage; | |
use iron_sessionstorage::backends::SignedCookieBackend; | |
struct MySession { | |
pub id: i32 | |
} | |
impl iron_sessionstorage::Value for MySession { | |
fn get_key() -> &'static str { "X-My-Session" } | |
fn into_raw(self) -> String { format!("{}", self.id) } | |
fn from_raw(s: String) -> Option<Self> { | |
s.parse::<i32>().map(|id| MySession { id: id }).ok() | |
} | |
} | |
fn main() { | |
let mut mount = mount::Mount::new(); | |
let mut router = router::Router::new(); | |
router.get("/login", |req: &mut Request| { | |
match try!(req.session().get::<MySession>()) { | |
Some(_) => Ok(Response::with("you're already logged in")), | |
None => { | |
req.session().set(MySession { id: 1 }).unwrap(); | |
Ok(Response::with("now logged in")) | |
} | |
} | |
}, "login"); | |
router.get("/logout", |req: &mut Request| { | |
match try!(req.session().get::<MySession>()) { | |
Some(_) => { | |
req.session().clear().unwrap(); | |
Ok(Response::with("now logged out")) | |
} | |
None => { | |
Ok(Response::with("not logged in")) | |
} | |
} | |
}, "logout"); | |
mount.mount("/path", router); | |
let mut chain = Chain::new(mount); | |
let secret = "changeme".as_bytes().to_vec(); | |
chain.link_around(SessionStorage::new(SignedCookieBackend::new(secret))); | |
iron::Iron::new(chain).http("localhost:8080").unwrap(); | |
// Try logging out twice -- you'll see the cookie hasn't been cleared! | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use iron::prelude::*; | |
use iron::middleware::AfterMiddleware; | |
use iron::headers::SetCookie; | |
pub struct DeleteCookieMiddleware; | |
impl AfterMiddleware for DeleteCookieMiddleware { | |
fn after(&self, _: &mut Request, mut res: Response) -> IronResult<Response> { | |
{ | |
let headers = &mut res.headers; | |
if let Some(sc) = headers.get_mut::<SetCookie>() { | |
let SetCookie(ref mut cookies) = *sc; | |
for c in cookies { | |
if c.starts_with("X-My-Session=; Max-Age=0;") { | |
c.push_str(";Path=/"); | |
} | |
} | |
} | |
} | |
Ok(res) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment