Update 'cookie' to 0.18.

This commit is contained in:
Sergio Benitez 2023-09-28 23:50:29 -07:00
parent f41474dd61
commit 5d31ad4efb
18 changed files with 99 additions and 88 deletions

View File

@ -430,7 +430,7 @@ impl Arg {
fn unnamed(&self) -> &ArgExpr { fn unnamed(&self) -> &ArgExpr {
match self { match self {
Arg::Unnamed(expr) => expr, Arg::Unnamed(expr) => expr,
_ => panic!("Called Arg::unnamed() on an Arg::named!"), _ => panic!("Called Arg::unnamed() on an Arg::Named!"),
} }
} }

View File

@ -42,7 +42,7 @@ pear = "0.2.3"
pin-project-lite = "0.2" pin-project-lite = "0.2"
memchr = "2" memchr = "2"
stable-pattern = "0.1" stable-pattern = "0.1"
cookie = { version = "0.17.0", features = ["percent-encode"] } cookie = { version = "=0.18.0-rc.0", features = ["percent-encode"] }
state = "0.6" state = "0.6"
futures = { version = "0.3", default-features = false } futures = { version = "0.3", default-features = false }

View File

@ -28,19 +28,19 @@ pub use self::cookie::{Cookie, SameSite, Iter};
/// ///
/// #[get("/message")] /// #[get("/message")]
/// fn message(jar: &CookieJar<'_>) { /// fn message(jar: &CookieJar<'_>) {
/// jar.add(Cookie::new("message", "hello!")); /// jar.add(("message", "hello!"));
/// jar.add(Cookie::new("other", "bye!")); /// jar.add(Cookie::build(("session", "bye!")).expires(None));
/// ///
/// // `get()` does not reflect changes. /// // `get()` does not reflect changes.
/// assert!(jar.get("other").is_none()); /// assert!(jar.get("session").is_none());
/// # assert_eq!(jar.get("message").map(|c| c.value()), Some("hi")); /// assert_eq!(jar.get("message").map(|c| c.value()), Some("hi"));
/// ///
/// // `get_pending()` does. /// // `get_pending()` does.
/// let other_pending = jar.get_pending("other"); /// let session_pending = jar.get_pending("session");
/// let message_pending = jar.get_pending("message"); /// let message_pending = jar.get_pending("message");
/// assert_eq!(other_pending.as_ref().map(|c| c.value()), Some("bye!")); /// assert_eq!(session_pending.as_ref().map(|c| c.value()), Some("bye!"));
/// assert_eq!(message_pending.as_ref().map(|c| c.value()), Some("hello!")); /// assert_eq!(message_pending.as_ref().map(|c| c.value()), Some("hello!"));
/// # jar.remove(Cookie::named("message")); /// # jar.remove("message");
/// # assert_eq!(jar.get("message").map(|c| c.value()), Some("hi")); /// # assert_eq!(jar.get("message").map(|c| c.value()), Some("hi"));
/// # assert!(jar.get_pending("message").is_none()); /// # assert!(jar.get_pending("message").is_none());
/// } /// }
@ -48,7 +48,7 @@ pub use self::cookie::{Cookie, SameSite, Iter};
/// # use rocket::local::blocking::Client; /// # use rocket::local::blocking::Client;
/// # let client = Client::debug_with(routes![message]).unwrap(); /// # let client = Client::debug_with(routes![message]).unwrap();
/// # let response = client.get("/message") /// # let response = client.get("/message")
/// # .cookie(Cookie::new("message", "hi")) /// # .cookie(("message", "hi"))
/// # .dispatch(); /// # .dispatch();
/// # /// #
/// # assert!(response.status().class().is_success()); /// # assert!(response.status().class().is_success());
@ -202,7 +202,7 @@ impl<'a> CookieJar<'a> {
/// ///
/// ```rust /// ```rust
/// # #[macro_use] extern crate rocket; /// # #[macro_use] extern crate rocket;
/// use rocket::http::{Cookie, CookieJar}; /// use rocket::http::CookieJar;
/// ///
/// #[get("/")] /// #[get("/")]
/// fn handler(jar: &CookieJar<'_>) { /// fn handler(jar: &CookieJar<'_>) {
@ -226,7 +226,7 @@ impl<'a> CookieJar<'a> {
/// ///
/// ```rust /// ```rust
/// # #[macro_use] extern crate rocket; /// # #[macro_use] extern crate rocket;
/// use rocket::http::{Cookie, CookieJar}; /// use rocket::http::CookieJar;
/// ///
/// #[get("/")] /// #[get("/")]
/// fn handler(jar: &CookieJar<'_>) { /// fn handler(jar: &CookieJar<'_>) {
@ -252,7 +252,7 @@ impl<'a> CookieJar<'a> {
/// ///
/// ```rust /// ```rust
/// # #[macro_use] extern crate rocket; /// # #[macro_use] extern crate rocket;
/// use rocket::http::{Cookie, CookieJar}; /// use rocket::http::CookieJar;
/// ///
/// #[get("/")] /// #[get("/")]
/// fn handler(jar: &CookieJar<'_>) { /// fn handler(jar: &CookieJar<'_>) {
@ -297,17 +297,18 @@ impl<'a> CookieJar<'a> {
/// ///
/// #[get("/")] /// #[get("/")]
/// fn handler(jar: &CookieJar<'_>) { /// fn handler(jar: &CookieJar<'_>) {
/// jar.add(Cookie::new("first", "value")); /// jar.add(("first", "value"));
/// ///
/// let cookie = Cookie::build("other", "value_two") /// let cookie = Cookie::build(("other", "value_two"))
/// .path("/") /// .path("/")
/// .secure(true) /// .secure(true)
/// .same_site(SameSite::Lax); /// .same_site(SameSite::Lax);
/// ///
/// jar.add(cookie.finish()); /// jar.add(cookie);
/// } /// }
/// ``` /// ```
pub fn add(&self, mut cookie: Cookie<'static>) { pub fn add<C: Into<Cookie<'static>>>(&self, cookie: C) {
let mut cookie = cookie.into();
Self::set_defaults(self.config, &mut cookie); Self::set_defaults(self.config, &mut cookie);
self.ops.lock().push(Op::Add(cookie, false)); self.ops.lock().push(Op::Add(cookie, false));
} }
@ -334,30 +335,32 @@ impl<'a> CookieJar<'a> {
/// ///
/// ```rust /// ```rust
/// # #[macro_use] extern crate rocket; /// # #[macro_use] extern crate rocket;
/// use rocket::http::{Cookie, CookieJar}; /// use rocket::http::CookieJar;
/// ///
/// #[get("/")] /// #[get("/")]
/// fn handler(jar: &CookieJar<'_>) { /// fn handler(jar: &CookieJar<'_>) {
/// jar.add_private(Cookie::new("name", "value")); /// jar.add_private(("name", "value"));
/// } /// }
/// ``` /// ```
#[cfg(feature = "secrets")] #[cfg(feature = "secrets")]
#[cfg_attr(nightly, doc(cfg(feature = "secrets")))] #[cfg_attr(nightly, doc(cfg(feature = "secrets")))]
pub fn add_private(&self, mut cookie: Cookie<'static>) { pub fn add_private<C: Into<Cookie<'static>>>(&self, cookie: C) {
let mut cookie = cookie.into();
Self::set_private_defaults(self.config, &mut cookie); Self::set_private_defaults(self.config, &mut cookie);
self.ops.lock().push(Op::Add(cookie, true)); self.ops.lock().push(Op::Add(cookie, true));
} }
/// Removes `cookie` from this collection and generates a "removal" cookies /// Removes `cookie` from this collection and generates a "removal" cookies
/// to send to the client on response. For correctness, `cookie` must /// to send to the client on response. A "removal" cookie is a cookie that
/// contain the same `path` and `domain` as the cookie that was initially /// has the same name as the original cookie but has an empty value, a
/// set. Failure to provide the initial `path` and `domain` will result in /// max-age of 0, and an expiration date far in the past.
/// cookies that are not properly removed. For convenience, if a path is not ///
/// set on `cookie`, the `"/"` path will automatically be set. /// **Note: For correctness, `cookie` must contain the same `path` and
/// `domain` as the cookie that was initially set. Failure to provide the
/// initial `path` and `domain` will result in cookies that are not properly
/// removed. For convenience, if a path is not set on `cookie`, the `"/"`
/// path will automatically be set.**
/// ///
/// A "removal" cookie is a cookie that has the same name as the original
/// cookie but has an empty value, a max-age of 0, and an expiration date
/// far in the past.
/// ///
/// # Example /// # Example
/// ///
@ -367,10 +370,15 @@ impl<'a> CookieJar<'a> {
/// ///
/// #[get("/")] /// #[get("/")]
/// fn handler(jar: &CookieJar<'_>) { /// fn handler(jar: &CookieJar<'_>) {
/// jar.remove(Cookie::named("name")); /// // Rocket will set `path` to `/`.
/// jar.remove("name");
///
/// // Use a custom-built cookie to set a custom path.
/// jar.remove(Cookie::build("name").path("/login"));
/// } /// }
/// ``` /// ```
pub fn remove(&self, mut cookie: Cookie<'static>) { pub fn remove<C: Into<Cookie<'static>>>(&self, cookie: C) {
let mut cookie = cookie.into();
if cookie.path().is_none() { if cookie.path().is_none() {
cookie.set_path("/"); cookie.set_path("/");
} }
@ -388,16 +396,17 @@ impl<'a> CookieJar<'a> {
/// ///
/// ```rust /// ```rust
/// # #[macro_use] extern crate rocket; /// # #[macro_use] extern crate rocket;
/// use rocket::http::{Cookie, CookieJar}; /// use rocket::http::CookieJar;
/// ///
/// #[get("/")] /// #[get("/")]
/// fn handler(jar: &CookieJar<'_>) { /// fn handler(jar: &CookieJar<'_>) {
/// jar.remove_private(Cookie::named("name")); /// jar.remove_private("name");
/// } /// }
/// ``` /// ```
#[cfg(feature = "secrets")] #[cfg(feature = "secrets")]
#[cfg_attr(nightly, doc(cfg(feature = "secrets")))] #[cfg_attr(nightly, doc(cfg(feature = "secrets")))]
pub fn remove_private(&self, mut cookie: Cookie<'static>) { pub fn remove_private<C: Into<Cookie<'static>>>(&self, cookie: C) {
let mut cookie = cookie.into();
if cookie.path().is_none() { if cookie.path().is_none() {
cookie.set_path("/"); cookie.set_path("/");
} }
@ -415,7 +424,7 @@ impl<'a> CookieJar<'a> {
/// ///
/// ```rust /// ```rust
/// # #[macro_use] extern crate rocket; /// # #[macro_use] extern crate rocket;
/// use rocket::http::{Cookie, CookieJar}; /// use rocket::http::CookieJar;
/// ///
/// #[get("/")] /// #[get("/")]
/// fn handler(jar: &CookieJar<'_>) { /// fn handler(jar: &CookieJar<'_>) {

View File

@ -24,7 +24,7 @@ use super::{Client, LocalResponse};
/// let req = client.post("/") /// let req = client.post("/")
/// .header(ContentType::JSON) /// .header(ContentType::JSON)
/// .remote("127.0.0.1:8000".parse().unwrap()) /// .remote("127.0.0.1:8000".parse().unwrap())
/// .cookie(Cookie::new("name", "value")) /// .cookie(("name", "value"))
/// .body(r#"{ "value": 42 }"#); /// .body(r#"{ "value": 42 }"#);
/// ///
/// let response = req.dispatch().await; /// let response = req.dispatch().await;
@ -106,7 +106,7 @@ impl<'c> LocalRequest<'c> {
for cookie in response.cookies().iter() { for cookie in response.cookies().iter() {
if let Some(expires) = cookie.expires_datetime() { if let Some(expires) = cookie.expires_datetime() {
if expires <= current_time { if expires <= current_time {
jar.force_remove(cookie); jar.force_remove(cookie.name());
continue; continue;
} }
} }

View File

@ -22,7 +22,7 @@ use super::{Client, LocalResponse};
/// let req = client.post("/") /// let req = client.post("/")
/// .header(ContentType::JSON) /// .header(ContentType::JSON)
/// .remote("127.0.0.1:8000".parse().unwrap()) /// .remote("127.0.0.1:8000".parse().unwrap())
/// .cookie(Cookie::new("name", "value")) /// .cookie(("name", "value"))
/// .body(r#"{ "value": 42 }"#); /// .body(r#"{ "value": 42 }"#);
/// ///
/// let response = req.dispatch(); /// let response = req.dispatch();

View File

@ -131,13 +131,15 @@ macro_rules! pub_request_impl {
/// # Client::_test(|_, request, _| { /// # Client::_test(|_, request, _| {
/// let request: LocalRequest = request; /// let request: LocalRequest = request;
/// let req = request /// let req = request
/// .cookie(Cookie::new("username", "sb")) /// .cookie(("username", "sb"))
/// .cookie(Cookie::new("user_id", "12")); /// .cookie(("user_id", "12"));
/// # }); /// # });
/// ``` /// ```
#[inline] #[inline]
pub fn cookie(mut self, cookie: crate::http::Cookie<'_>) -> Self { pub fn cookie<'a, C>(mut self, cookie: C) -> Self
self._request_mut().cookies_mut().add_original(cookie.into_owned()); where C: Into<crate::http::Cookie<'a>>
{
self._request_mut().cookies_mut().add_original(cookie.into().into_owned());
self self
} }
@ -151,15 +153,17 @@ macro_rules! pub_request_impl {
/// ///
/// # Client::_test(|_, request, _| { /// # Client::_test(|_, request, _| {
/// let request: LocalRequest = request; /// let request: LocalRequest = request;
/// let cookies = vec![Cookie::new("a", "b"), Cookie::new("c", "d")]; /// let cookies = vec![("a", "b"), ("c", "d")];
/// let req = request.cookies(cookies); /// let req = request.cookies(cookies);
/// # }); /// # });
/// ``` /// ```
#[inline] #[inline]
pub fn cookies<'a, C>(mut self, cookies: C) -> Self pub fn cookies<'a, C, I>(mut self, cookies: I) -> Self
where C: IntoIterator<Item = crate::http::Cookie<'a>> where C: Into<crate::http::Cookie<'a>>,
I: IntoIterator<Item = C>
{ {
for cookie in cookies { for cookie in cookies {
let cookie: crate::http::Cookie<'_> = cookie.into();
self._request_mut().cookies_mut().add_original(cookie.into_owned()); self._request_mut().cookies_mut().add_original(cookie.into_owned());
} }
@ -180,14 +184,16 @@ macro_rules! pub_request_impl {
/// ///
/// # Client::_test(|_, request, _| { /// # Client::_test(|_, request, _| {
/// let request: LocalRequest = request; /// let request: LocalRequest = request;
/// let req = request.private_cookie(Cookie::new("user_id", "sb")); /// let req = request.private_cookie(("user_id", "sb"));
/// # }); /// # });
/// ``` /// ```
#[cfg(feature = "secrets")] #[cfg(feature = "secrets")]
#[cfg_attr(nightly, doc(cfg(feature = "secrets")))] #[cfg_attr(nightly, doc(cfg(feature = "secrets")))]
#[inline] #[inline]
pub fn private_cookie(mut self, cookie: crate::http::Cookie<'static>) -> Self { pub fn private_cookie<C>(mut self, cookie: C) -> Self
self._request_mut().cookies_mut().add_original_private(cookie); where C: Into<crate::http::Cookie<'static>>
{
self._request_mut().cookies_mut().add_original_private(cookie.into());
self self
} }

View File

@ -446,8 +446,8 @@ impl<'r> Request<'r> {
/// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap(); /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
/// # let request = c.get("/"); /// # let request = c.get("/");
/// # let req = request.inner(); /// # let req = request.inner();
/// req.cookies().add(Cookie::new("key", "val")); /// req.cookies().add(("key", "val"));
/// req.cookies().add(Cookie::new("ans", format!("life: {}", 38 + 4))); /// req.cookies().add(("ans", format!("life: {}", 38 + 4)));
/// ///
/// assert_eq!(req.cookies().get_pending("key").unwrap().value(), "val"); /// assert_eq!(req.cookies().get_pending("key").unwrap().value(), "val");
/// assert_eq!(req.cookies().get_pending("ans").unwrap().value(), "life: 42"); /// assert_eq!(req.cookies().get_pending("ans").unwrap().value(), "life: 42");

View File

@ -178,9 +178,9 @@ impl<R> Flash<R> {
let content = format!("{}{}{}{}", let content = format!("{}{}{}{}",
self.kind.len(), FLASH_COOKIE_DELIM, self.kind, self.message); self.kind.len(), FLASH_COOKIE_DELIM, self.kind, self.message);
Cookie::build(FLASH_COOKIE_NAME, content) Cookie::build((FLASH_COOKIE_NAME, content))
.max_age(Duration::minutes(5)) .max_age(Duration::minutes(5))
.finish() .build()
} }
} }
@ -211,7 +211,7 @@ impl<'r> FlashMessage<'r> {
fn clear_cookie_if_needed(&self) { fn clear_cookie_if_needed(&self) {
// Remove the cookie if it hasn't already been removed. // Remove the cookie if it hasn't already been removed.
if !self.consumed.swap(true, Ordering::Relaxed) { if !self.consumed.swap(true, Ordering::Relaxed) {
self.inner.remove(Cookie::named(FLASH_COOKIE_NAME)); self.inner.remove(FLASH_COOKIE_NAME);
} }
} }

View File

@ -1,17 +1,17 @@
#[macro_use] extern crate rocket; #[macro_use] extern crate rocket;
use rocket::request::Request; use rocket::request::Request;
use rocket::http::{Cookie, CookieJar}; use rocket::http::CookieJar;
#[catch(404)] #[catch(404)]
fn not_found(request: &Request) -> &'static str { fn not_found(request: &Request) -> &'static str {
request.cookies().add(Cookie::new("not_found", "404")); request.cookies().add(("not_found", "404"));
"404 - Not Found" "404 - Not Found"
} }
#[get("/")] #[get("/")]
fn index(cookies: &CookieJar<'_>) -> &'static str { fn index(cookies: &CookieJar<'_>) -> &'static str {
cookies.add(Cookie::new("index", "hi")); cookies.add(("index", "hi"));
"Hello, world!" "Hello, world!"
} }
@ -26,7 +26,7 @@ mod tests {
.mount("/", routes![index]) .mount("/", routes![index])
.register("/", catchers![not_found]) .register("/", catchers![not_found])
.attach(AdHoc::on_request("Add Cookie", |req, _| Box::pin(async move { .attach(AdHoc::on_request("Add Cookie", |req, _| Box::pin(async move {
req.cookies().add(Cookie::new("fairing", "woo")); req.cookies().add(("fairing", "woo"));
}))); })));
let client = Client::debug(rocket).unwrap(); let client = Client::debug(rocket).unwrap();

View File

@ -10,7 +10,7 @@ fn cookie_add_private(jar: &CookieJar<'_>) {
jar.add(cookie_a.clone()); jar.add(cookie_a.clone());
let mut cookie_b = Cookie::new("b", "v2"); let mut cookie_b = Cookie::new("b", "v2");
jar.add_private(cookie_b.clone()); jar.add_private(cookie_b.clone());
jar.add(Cookie::new("c", "v3")); jar.add(("c", "v3"));
// private: CookieJar::set_defaults(&mut cookie_a); // private: CookieJar::set_defaults(&mut cookie_a);
cookie_a.set_path("/"); cookie_a.set_path("/");
@ -89,9 +89,9 @@ mod cookies_private_tests {
let client = Client::debug(rocket()).unwrap(); let client = Client::debug(rocket()).unwrap();
let response = client let response = client
.get("/") .get("/")
.cookie(Cookie::new("a", "Cookie")) .cookie(("a", "Cookie"))
.private_cookie(Cookie::new("b", " tastes ")) .private_cookie(("b", " tastes "))
.cookie(Cookie::new("c", "good!")) .cookie(("c", "good!"))
.dispatch(); .dispatch();
assert_eq!(response.into_string().unwrap(), "Cookie tastes good!"); assert_eq!(response.into_string().unwrap(), "Cookie tastes good!");
@ -103,9 +103,9 @@ mod cookies_private_tests {
let client = Client::debug(rocket()).unwrap(); let client = Client::debug(rocket()).unwrap();
let response = client let response = client
.get("/oh-no") .get("/oh-no")
.cookie(Cookie::new("a", "Cookie")) .cookie(("a", "Cookie"))
.private_cookie(Cookie::new("b", " tastes ")) .private_cookie(("b", " tastes "))
.cookie(Cookie::new("c", "good!")) .cookie(("c", "good!"))
.dispatch(); .dispatch();
assert_ne!(response.into_string().unwrap(), "Cookie tastes good!"); assert_ne!(response.into_string().unwrap(), "Cookie tastes good!");

View File

@ -14,14 +14,14 @@ mod tests {
use super::*; use super::*;
use rocket::routes; use rocket::routes;
use rocket::local::blocking::Client; use rocket::local::blocking::Client;
use rocket::http::{Cookie, Status}; use rocket::http::Status;
#[test] #[test]
fn private_cookie_is_returned() { fn private_cookie_is_returned() {
let rocket = rocket::build().mount("/", routes![return_private_cookie]); let rocket = rocket::build().mount("/", routes![return_private_cookie]);
let client = Client::debug(rocket).unwrap(); let client = Client::debug(rocket).unwrap();
let req = client.get("/").private_cookie(Cookie::new("cookie_name", "cookie_value")); let req = client.get("/").private_cookie(("cookie_name", "cookie_value"));
let response = req.dispatch(); let response = req.dispatch();
assert_eq!(response.headers().get_one("Set-Cookie"), None); assert_eq!(response.headers().get_one("Set-Cookie"), None);
@ -33,7 +33,7 @@ mod tests {
let rocket = rocket::build().mount("/", routes![return_private_cookie]); let rocket = rocket::build().mount("/", routes![return_private_cookie]);
let client = Client::debug(rocket).unwrap(); let client = Client::debug(rocket).unwrap();
let req = client.get("/").cookie(Cookie::new("cookie_name", "cookie_value")); let req = client.get("/").cookie(("cookie_name", "cookie_value"));
let response = req.dispatch(); let response = req.dispatch();
assert_eq!(response.status(), Status::NotFound); assert_eq!(response.status(), Status::NotFound);

View File

@ -1,11 +1,11 @@
#[macro_use] extern crate rocket; #[macro_use] extern crate rocket;
use rocket::http::{Cookie, CookieJar}; use rocket::http::CookieJar;
#[post("/")] #[post("/")]
fn multi_add(jar_a: &CookieJar<'_>, jar_b: &CookieJar<'_>) { fn multi_add(jar_a: &CookieJar<'_>, jar_b: &CookieJar<'_>) {
jar_a.add(Cookie::new("a", "v1")); jar_a.add(("a", "v1"));
jar_b.add(Cookie::new("b", "v2")); jar_b.add(("b", "v2"));
} }
#[get("/")] #[get("/")]
@ -41,8 +41,8 @@ mod many_cookie_jars_tests {
fn test_multi_get() { fn test_multi_get() {
let client = Client::debug(rocket()).unwrap(); let client = Client::debug(rocket()).unwrap();
let response = client.get("/") let response = client.get("/")
.cookie(Cookie::new("a", "a_val")) .cookie(("a", "a_val"))
.cookie(Cookie::new("b", "hi!")) .cookie(("b", "hi!"))
.dispatch(); .dispatch();
assert_eq!(response.into_string().unwrap(), "a_valhi!"); assert_eq!(response.into_string().unwrap(), "a_valhi!");

View File

@ -4,8 +4,7 @@ use rocket::http::{CookieJar, Cookie};
#[rocket::get("/")] #[rocket::get("/")]
fn index(jar: &CookieJar<'_>) { fn index(jar: &CookieJar<'_>) {
let session_cookie = Cookie::build("key", "value").expires(None); jar.add_private(Cookie::build(("key", "value")).expires(None));
jar.add_private(session_cookie.finish());
} }
mod test_session_cookies { mod test_session_cookies {

View File

@ -1,10 +1,10 @@
#[macro_use] extern crate rocket; #[macro_use] extern crate rocket;
use rocket::http::{Cookie, CookieJar}; use rocket::http::CookieJar;
#[post("/")] #[post("/")]
fn add(jar: &CookieJar<'_>) { fn add(jar: &CookieJar<'_>) {
jar.add(Cookie::new("name", "value")); jar.add(("name", "value"));
} }
#[get("/")] #[get("/")]

View File

@ -12,17 +12,14 @@ pub use message_uri as uri;
#[post("/", data = "<message>")] #[post("/", data = "<message>")]
fn submit(cookies: &CookieJar<'_>, message: Form<&str>) -> Redirect { fn submit(cookies: &CookieJar<'_>, message: Form<&str>) -> Redirect {
cookies.add(Cookie::new("message", message.to_string())); cookies.add(("message", message.to_string()));
Redirect::to(uri!(index)) Redirect::to(uri!(index))
} }
#[get("/")] #[get("/")]
fn index(cookies: &CookieJar<'_>) -> Template { fn index(cookies: &CookieJar<'_>) -> Template {
let cookie = cookies.get("message"); let message = cookies.get("message").map(|c| c.value());
Template::render("message", context! { message })
Template::render("message", context! {
message: cookie.map(|c| c.value()),
})
} }
pub fn routes() -> Vec<rocket::Route> { pub fn routes() -> Vec<rocket::Route> {

View File

@ -60,7 +60,7 @@ fn login_page(flash: Option<FlashMessage<'_>>) -> Template {
#[post("/login", data = "<login>")] #[post("/login", data = "<login>")]
fn post_login(jar: &CookieJar<'_>, login: Form<Login<'_>>) -> Result<Redirect, Flash<Redirect>> { fn post_login(jar: &CookieJar<'_>, login: Form<Login<'_>>) -> Result<Redirect, Flash<Redirect>> {
if login.username == "Sergio" && login.password == "password" { if login.username == "Sergio" && login.password == "password" {
jar.add_private(Cookie::new("user_id", 1.to_string())); jar.add_private(("user_id", "1"));
Ok(Redirect::to(uri!(index))) Ok(Redirect::to(uri!(index)))
} else { } else {
Err(Flash::error(Redirect::to(uri!(login_page)), "Invalid username/password.")) Err(Flash::error(Redirect::to(uri!(login_page)), "Invalid username/password."))
@ -69,7 +69,7 @@ fn post_login(jar: &CookieJar<'_>, login: Form<Login<'_>>) -> Result<Redirect, F
#[post("/logout")] #[post("/logout")]
fn logout(jar: &CookieJar<'_>) -> Flash<Redirect> { fn logout(jar: &CookieJar<'_>) -> Flash<Redirect> {
jar.remove_private(Cookie::named("user_id")); jar.remove_private("user_id");
Flash::success(Redirect::to(uri!(login_page)), "Successfully logged out.") Flash::success(Redirect::to(uri!(login_page)), "Successfully logged out.")
} }

View File

@ -27,11 +27,11 @@ fn secure_cookies() {
#[get("/cookie")] #[get("/cookie")]
fn cookie(jar: &CookieJar<'_>) { fn cookie(jar: &CookieJar<'_>) {
jar.add(Cookie::new("k1", "v1")); jar.add(("k1", "v1"));
jar.add_private(Cookie::new("k2", "v2")); jar.add_private(("k2", "v2"));
jar.add(Cookie::build("k1u", "v1u").secure(false).finish()); jar.add(Cookie::build(("k1u", "v1u")).secure(false));
jar.add_private(Cookie::build("k2u", "v2u").secure(false).finish()); jar.add_private(Cookie::build(("k2u", "v2u")).secure(false));
} }
let client = Client::tracked(super::rocket().mount("/", routes![cookie])).unwrap(); let client = Client::tracked(super::rocket().mount("/", routes![cookie])).unwrap();

View File

@ -631,7 +631,7 @@ fn user_id(cookies: &CookieJar<'_>) -> Option<String> {
/// Remove the `user_id` cookie. /// Remove the `user_id` cookie.
#[post("/logout")] #[post("/logout")]
fn logout(cookies: &CookieJar<'_>) -> Flash<Redirect> { fn logout(cookies: &CookieJar<'_>) -> Flash<Redirect> {
cookies.remove_private(Cookie::named("user_id")); cookies.remove_private("user_id");
Flash::success(Redirect::to("/"), "Successfully logged out.") Flash::success(Redirect::to("/"), "Successfully logged out.")
} }
``` ```