65 lines
2.3 KiB
Rust
65 lines
2.3 KiB
Rust
use rouille::{input, Request, Response};
|
|
|
|
// The CookieRequest and CookieResponse traits are currently only used
|
|
// to add, retrieve and reset the `back_url` cookie. That cookie is
|
|
// used to set the URL of the in-UI back button when visiting a page
|
|
// which can be arrived at via several paths.
|
|
//
|
|
// An example of this is the Scuttlebutt Settings menu (/settings/scuttlebutt),
|
|
// which can be accessed via the Settings menu (/settings) or the Scuttlebutt
|
|
// Status page (/status/scuttlebutt). We need to be able to set the path of
|
|
// the back button to point to the correct page (ie. the one from which we've
|
|
// come).
|
|
//
|
|
// The `back_url` cookie is also used on the Profile page
|
|
// (/scuttlebutt/profile).
|
|
|
|
/// Cookie trait for `Request`.
|
|
pub trait CookieRequest {
|
|
/// Retrieve a cookie value from a `Request`.
|
|
fn retrieve_cookie(&self, cookie_name: &str) -> Option<&str>;
|
|
}
|
|
|
|
impl CookieRequest for Request {
|
|
fn retrieve_cookie(&self, cookie_name: &str) -> Option<&str> {
|
|
// check for cookie using given name
|
|
let cookie_val = input::cookies(self)
|
|
.find(|&(n, _)| n == cookie_name)
|
|
// return the value of the cookie (key is already known)
|
|
.map(|key_val| key_val.1);
|
|
|
|
cookie_val
|
|
}
|
|
}
|
|
|
|
/// Cookie trait for `Response`.
|
|
pub trait CookieResponse {
|
|
/// Add a cookie containing the given data to a `Response`. Data should be
|
|
/// in the form of `cookie_name=cookie_val`.
|
|
fn add_cookie(self, cookie_name_val: &str) -> Response;
|
|
/// Reset a cookie value for a `Response`.
|
|
fn reset_cookie(self, cookie_name: &str) -> Response;
|
|
}
|
|
|
|
impl CookieResponse for Response {
|
|
fn add_cookie(self, cookie_name_val: &str) -> Response {
|
|
// set the cookie header
|
|
// max-age is currently set to 3600 seconds (1 hour)
|
|
self.with_additional_header(
|
|
"Set-Cookie",
|
|
format!("{}; Max-Age=3600; SameSite=Lax; Path=/", cookie_name_val),
|
|
)
|
|
}
|
|
|
|
fn reset_cookie(self, cookie_name: &str) -> Response {
|
|
// set a blank cookie to clear the cookie from the previous request
|
|
self.with_additional_header(
|
|
"Set-Cookie",
|
|
format!(
|
|
"{}=; Max-Age=0; SameSite=Lax; Path=/; Expires=Fri, 21 Aug 1987 12:00:00 UTC",
|
|
cookie_name
|
|
),
|
|
)
|
|
}
|
|
}
|