-
Notifications
You must be signed in to change notification settings - Fork 157
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
Handling Sessions with an 'Environment' #246
Closed
Closed
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
d8983be
feat(server): add some shared data across all requests
Ryman 47b0136
feat(cookies): allow reading the cookies from a Request
Ryman 2304e8c
feat(response): allow Plugins for Response
Ryman 1239748
feat(cookies): allow setting cookies on Response
Ryman 13f1ad4
refactor(cookies): collapse to a single trait and add some docs
Ryman 7a60286
fix(cookies): add explicit implementations for Cookies trait
Ryman 5b4e23b
chore(tests): update compile-fail tests
Ryman 23bb400
test(server): add a compile-fail test to ensure reasonable error message
Ryman ebc6aa9
refactor(*): Request is now accessible through a Response instance
Ryman 47a728d
feat(session): add Session plugin based on the Cookie store
Ryman 4fb224d
chore(cfail): update cfail test
Ryman edea3ab
feat(macros): allow hinting the server data type in middleware macro
Ryman 5aa0833
doc(response): explain why Response owns Request now
Ryman File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
#[macro_use] extern crate nickel; | ||
extern crate cookie; | ||
|
||
use nickel::{Nickel, HttpRouter, Cookies, QueryString}; | ||
use nickel::cookies; | ||
use cookie::Cookie; | ||
|
||
struct Data { | ||
secret_key: cookies::SecretKey | ||
} | ||
|
||
impl AsRef<cookies::SecretKey> for Data { | ||
fn as_ref(&self) -> &cookies::SecretKey { | ||
&self.secret_key | ||
} | ||
} | ||
|
||
fn main() { | ||
let data = Data { secret_key: cookies::SecretKey([0; 32]) }; | ||
let mut server = Nickel::with_data(data); | ||
|
||
// Try curl -b MyCookie=bar localhost:6767 | ||
server.get("/", middleware! { |mut res| | ||
let cookie = res.cookies().find("MyCookie"); | ||
format!("MyCookie={:?}", cookie.map(|c| c.value)) | ||
}); | ||
|
||
// Note: Don't use get for login in real applications ;) | ||
// Try http://localhost:6767/login?name=foo | ||
server.get("/login", middleware! { |mut res| | ||
let cookie = { | ||
let name = res.request.query().get("name") | ||
.unwrap_or("default_name"); | ||
Cookie::new("MyCookie".to_owned(), name.to_owned()) | ||
}; | ||
|
||
let jar = res.cookies_mut() | ||
// long life cookies! | ||
.permanent(); | ||
jar.add(cookie); | ||
|
||
"Cookie set!" | ||
}); | ||
|
||
server.listen("127.0.0.1:6767"); | ||
} |
This file contains 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
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
#[macro_use] extern crate nickel; | ||
extern crate rustc_serialize; | ||
extern crate time; | ||
|
||
use std::io::Write; | ||
use nickel::*; | ||
use nickel::status::StatusCode; | ||
use time::Duration; | ||
|
||
#[derive(RustcDecodable, RustcEncodable)] | ||
struct User { | ||
name: String, | ||
password: String, | ||
} | ||
|
||
struct ServerData; | ||
static SECRET_KEY: &'static cookies::SecretKey = &cookies::SecretKey([0; 32]); | ||
impl AsRef<cookies::SecretKey> for ServerData { | ||
fn as_ref(&self) -> &cookies::SecretKey { SECRET_KEY } | ||
} | ||
impl SessionStore for ServerData { | ||
type Store = Option<String>; | ||
|
||
fn timeout() -> Duration { | ||
Duration::seconds(5) | ||
} | ||
} | ||
|
||
|
||
fn main() { | ||
let mut server = Nickel::with_data(ServerData); | ||
|
||
/* Anyone should be able to reach thist route. */ | ||
server.get("/", middleware! { |mut res| | ||
format!("You are logged in as: {:?}\n", res.session()) | ||
}); | ||
|
||
server.post("/login", middleware!{|mut res| | ||
if let Ok(u) = res.request.json_as::<User>() { | ||
if u.name == "foo" && u.password == "bar" { | ||
*res.session_mut() = Some(u.name); | ||
return res.send("Successfully logged in.") | ||
} | ||
} | ||
(StatusCode::BadRequest, "Access denied.") | ||
}); | ||
|
||
server.get("/secret", middleware! { |mut res| <ServerData> | ||
match *res.session() { | ||
Some(ref user) if user == "foo" => (StatusCode::Ok, "Some hidden information!"), | ||
_ => (StatusCode::Forbidden, "Access denied.") | ||
} | ||
}); | ||
|
||
fn custom_403<'a>(err: &mut NickelError<ServerData>) -> Action { | ||
if let Some(ref mut res) = err.response_mut() { | ||
if res.status() == StatusCode::Forbidden { | ||
let _ = res.write_all(b"Access denied!\n"); | ||
return Halt(()) | ||
} | ||
} | ||
|
||
Continue(()) | ||
} | ||
|
||
// issue #20178 | ||
let custom_handler: fn(&mut NickelError<ServerData>) -> Action = custom_403; | ||
|
||
server.handle_error(custom_handler); | ||
|
||
server.listen("127.0.0.1:6767"); | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I may not see the forest for the tree here. How do I fully test this example? Of course I can send the right json to the running server using something like curl or postman and I get the "successfully logged in" text. But I'd like to test out the entire example (session cookie). So I thought, ok, let's just render a small
<form>
for the/
route that can be used for the login. But that's not gonna work as non ajax submitted forms aren't send as JSON so I would have to change other parts of the example, too.So I wonder, did you actually test the entire example to see if the session cookie is created by the browser after successful login? If so, how did you test that out?
@Ryman
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
See nickel-org/nickel-auth#1, it has a test shell script. (but yes we should have a test written in rust!)