2016-09-12 01:57:04 +00:00
|
|
|
use std::convert::AsRef;
|
2016-10-04 00:09:13 +00:00
|
|
|
|
2017-03-07 09:19:06 +00:00
|
|
|
use time::Duration;
|
2017-01-27 07:08:15 +00:00
|
|
|
|
2019-06-13 01:48:02 +00:00
|
|
|
use crate::outcome::IntoOutcome;
|
2019-08-04 23:19:44 +00:00
|
|
|
use crate::response::{Responder, ResultFuture};
|
2019-06-13 01:48:02 +00:00
|
|
|
use crate::request::{self, Request, FromRequest};
|
|
|
|
use crate::http::{Status, Cookie};
|
2018-04-15 02:53:36 +00:00
|
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
2016-09-12 01:57:04 +00:00
|
|
|
|
2016-11-03 14:09:01 +00:00
|
|
|
// The name of the actual flash cookie.
|
2018-07-18 16:45:20 +00:00
|
|
|
const FLASH_COOKIE_NAME: &str = "_flash";
|
2016-09-22 11:12:07 +00:00
|
|
|
|
2020-05-17 00:55:11 +00:00
|
|
|
// Character to use as a delimiter after the cookie's name's length.
|
|
|
|
const FLASH_COOKIE_DELIM: char = ':';
|
|
|
|
|
2016-11-03 14:09:01 +00:00
|
|
|
/// Sets a "flash" cookie that will be removed when it is accessed. The
|
2018-10-06 13:25:17 +00:00
|
|
|
/// analogous request type is [`FlashMessage`].
|
2016-11-02 17:48:43 +00:00
|
|
|
///
|
|
|
|
/// This type makes it easy to send messages across requests. It is typically
|
|
|
|
/// used for "status" messages after redirects. For instance, if a user attempts
|
|
|
|
/// to visit a page he/she does not have access to, you may want to redirect the
|
|
|
|
/// user to a safe place and show a message indicating what happened on the
|
|
|
|
/// redirected page. The message should only persist for a single request. This
|
|
|
|
/// can be accomplished with this type.
|
|
|
|
///
|
|
|
|
/// # Usage
|
|
|
|
///
|
|
|
|
/// Each `Flash` message consists of a `name` and some `msg` contents. A generic
|
|
|
|
/// constructor ([new](#method.new)) can be used to construct a message with any
|
|
|
|
/// name, while the [warning](#method.warning), [success](#method.success), and
|
|
|
|
/// [error](#method.error) constructors create messages with the corresponding
|
|
|
|
/// names.
|
|
|
|
///
|
2018-10-06 13:25:17 +00:00
|
|
|
/// Messages can be retrieved on the request side via the [`FlashMessage`] type
|
|
|
|
/// and the [name](#method.name) and [msg](#method.msg) methods.
|
2016-11-02 17:48:43 +00:00
|
|
|
///
|
2016-11-03 14:09:01 +00:00
|
|
|
/// # Response
|
2016-11-02 17:48:43 +00:00
|
|
|
///
|
|
|
|
/// The `Responder` implementation for `Flash` sets the message cookie and then
|
|
|
|
/// uses the passed in responder `res` to complete the response. In other words,
|
2018-07-12 03:44:09 +00:00
|
|
|
/// it simply sets a cookie and delegates the rest of the response handling to
|
2016-11-02 17:48:43 +00:00
|
|
|
/// the wrapped responder.
|
2016-11-03 14:09:01 +00:00
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// The following complete Rocket application illustrates the use of a `Flash`
|
|
|
|
/// message on both the request and response sides.
|
|
|
|
///
|
|
|
|
/// ```rust
|
2019-08-20 23:53:00 +00:00
|
|
|
/// # #![feature(proc_macro_hygiene)]
|
2018-06-28 15:55:15 +00:00
|
|
|
/// # #[macro_use] extern crate rocket;
|
2016-11-03 14:09:01 +00:00
|
|
|
/// use rocket::response::{Flash, Redirect};
|
|
|
|
/// use rocket::request::FlashMessage;
|
2017-03-31 07:18:58 +00:00
|
|
|
/// use rocket::http::RawStr;
|
2016-11-03 14:09:01 +00:00
|
|
|
///
|
|
|
|
/// #[post("/login/<name>")]
|
2017-03-31 07:18:58 +00:00
|
|
|
/// fn login(name: &RawStr) -> Result<&'static str, Flash<Redirect>> {
|
2016-11-03 14:09:01 +00:00
|
|
|
/// if name == "special_user" {
|
|
|
|
/// Ok("Hello, special user!")
|
|
|
|
/// } else {
|
|
|
|
/// Err(Flash::error(Redirect::to("/"), "Invalid username."))
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// #[get("/")]
|
|
|
|
/// fn index(flash: Option<FlashMessage>) -> String {
|
|
|
|
/// flash.map(|msg| format!("{}: {}", msg.name(), msg.msg()))
|
|
|
|
/// .unwrap_or_else(|| "Welcome!".to_string())
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// # if false { // We don't actually want to launch the server in an example.
|
2017-03-16 05:10:09 +00:00
|
|
|
/// rocket::ignite().mount("/", routes![login, index]).launch();
|
2016-11-03 14:09:01 +00:00
|
|
|
/// # }
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// On the response side (in `login`), a `Flash` error message is set if some
|
|
|
|
/// fictional authentication failed, and the user is redirected to `"/"`. On the
|
|
|
|
/// request side (in `index`), the handler emits the flash message if there is
|
|
|
|
/// one and otherwise emits a standard welcome message. Note that if the user
|
|
|
|
/// were to refresh the index page after viewing a flash message, the user would
|
|
|
|
/// receive the standard welcome message.
|
|
|
|
#[derive(Debug)]
|
2016-09-12 01:57:04 +00:00
|
|
|
pub struct Flash<R> {
|
|
|
|
name: String,
|
|
|
|
message: String,
|
2018-04-15 02:53:36 +00:00
|
|
|
consumed: AtomicBool,
|
|
|
|
inner: R,
|
2016-09-12 01:57:04 +00:00
|
|
|
}
|
|
|
|
|
2018-10-06 13:25:17 +00:00
|
|
|
/// Type alias to retrieve [`Flash`] messages from a request.
|
2018-04-15 02:53:36 +00:00
|
|
|
///
|
|
|
|
/// # Flash Cookie
|
|
|
|
///
|
|
|
|
/// A `FlashMessage` holds the parsed contents of the flash cookie. As long as
|
|
|
|
/// there is a flash cookie present (set by the `Flash` `Responder`), a
|
2018-07-12 03:44:09 +00:00
|
|
|
/// `FlashMessage` request guard will succeed.
|
2018-04-15 02:53:36 +00:00
|
|
|
///
|
|
|
|
/// The flash cookie is cleared if either the [`name()`] or [`msg()`] method is
|
|
|
|
/// called. If neither method is called, the flash cookie is not cleared.
|
|
|
|
///
|
2018-10-06 13:25:17 +00:00
|
|
|
/// [`name()`]: Flash::name()
|
|
|
|
/// [`msg()`]: Flash::msg()
|
2019-06-13 01:48:02 +00:00
|
|
|
pub type FlashMessage<'a, 'r> = crate::response::Flash<&'a Request<'r>>;
|
2018-04-15 02:53:36 +00:00
|
|
|
|
2016-12-15 08:47:31 +00:00
|
|
|
impl<'r, R: Responder<'r>> Flash<R> {
|
2016-11-02 17:48:43 +00:00
|
|
|
/// Constructs a new `Flash` message with the given `name`, `msg`, and
|
|
|
|
/// underlying `responder`.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// Construct a "suggestion" message with contents "Try this out!" that
|
|
|
|
/// redirects to "/".
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use rocket::response::{Redirect, Flash};
|
|
|
|
///
|
2017-02-02 10:16:21 +00:00
|
|
|
/// # #[allow(unused_variables)]
|
2016-11-02 17:48:43 +00:00
|
|
|
/// let msg = Flash::new(Redirect::to("/"), "suggestion", "Try this out!");
|
|
|
|
/// ```
|
2016-09-12 01:57:04 +00:00
|
|
|
pub fn new<N: AsRef<str>, M: AsRef<str>>(res: R, name: N, msg: M) -> Flash<R> {
|
|
|
|
Flash {
|
|
|
|
name: name.as_ref().to_string(),
|
|
|
|
message: msg.as_ref().to_string(),
|
2018-04-15 02:53:36 +00:00
|
|
|
consumed: AtomicBool::default(),
|
|
|
|
inner: res,
|
2016-09-12 01:57:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-11-02 17:48:43 +00:00
|
|
|
/// Constructs a "success" `Flash` message with the given `responder` and
|
|
|
|
/// `msg`.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// Construct a "success" message with contents "It worked!" that redirects
|
|
|
|
/// to "/".
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use rocket::response::{Redirect, Flash};
|
|
|
|
///
|
2017-02-02 10:16:21 +00:00
|
|
|
/// # #[allow(unused_variables)]
|
2016-11-02 17:48:43 +00:00
|
|
|
/// let msg = Flash::success(Redirect::to("/"), "It worked!");
|
|
|
|
/// ```
|
2016-09-12 01:57:04 +00:00
|
|
|
pub fn success<S: AsRef<str>>(responder: R, msg: S) -> Flash<R> {
|
|
|
|
Flash::new(responder, "success", msg)
|
|
|
|
}
|
|
|
|
|
2016-11-02 17:48:43 +00:00
|
|
|
/// Constructs a "warning" `Flash` message with the given `responder` and
|
|
|
|
/// `msg`.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// Construct a "warning" message with contents "Watch out!" that redirects
|
|
|
|
/// to "/".
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use rocket::response::{Redirect, Flash};
|
|
|
|
///
|
2017-02-02 10:16:21 +00:00
|
|
|
/// # #[allow(unused_variables)]
|
2016-11-02 17:48:43 +00:00
|
|
|
/// let msg = Flash::warning(Redirect::to("/"), "Watch out!");
|
|
|
|
/// ```
|
|
|
|
pub fn warning<S: AsRef<str>>(responder: R, msg: S) -> Flash<R> {
|
|
|
|
Flash::new(responder, "warning", msg)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Constructs an "error" `Flash` message with the given `responder` and
|
|
|
|
/// `msg`.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// Construct an "error" message with contents "Whoops!" that redirects
|
|
|
|
/// to "/".
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use rocket::response::{Redirect, Flash};
|
|
|
|
///
|
2017-02-02 10:16:21 +00:00
|
|
|
/// # #[allow(unused_variables)]
|
2016-11-02 17:48:43 +00:00
|
|
|
/// let msg = Flash::error(Redirect::to("/"), "Whoops!");
|
|
|
|
/// ```
|
2016-09-12 01:57:04 +00:00
|
|
|
pub fn error<S: AsRef<str>>(responder: R, msg: S) -> Flash<R> {
|
|
|
|
Flash::new(responder, "error", msg)
|
|
|
|
}
|
|
|
|
|
2017-01-27 07:08:15 +00:00
|
|
|
fn cookie(&self) -> Cookie<'static> {
|
2020-05-17 00:55:11 +00:00
|
|
|
let content = format!("{}{}{}{}",
|
|
|
|
self.name.len(), FLASH_COOKIE_DELIM, self.name, self.message);
|
|
|
|
|
2017-01-27 07:08:15 +00:00
|
|
|
Cookie::build(FLASH_COOKIE_NAME, content)
|
|
|
|
.max_age(Duration::minutes(5))
|
|
|
|
.path("/")
|
|
|
|
.finish()
|
2016-09-12 01:57:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-11-03 14:09:01 +00:00
|
|
|
/// Sets the message cookie and then uses the wrapped responder to complete the
|
2018-07-12 03:44:09 +00:00
|
|
|
/// response. In other words, simply sets a cookie and delegates the rest of the
|
2016-11-03 14:09:01 +00:00
|
|
|
/// response handling to the wrapped responder. As a result, the `Outcome` of
|
|
|
|
/// the response is the `Outcome` of the wrapped `Responder`.
|
2019-07-24 15:21:52 +00:00
|
|
|
impl<'r, R: Responder<'r> + Send + 'r> Responder<'r> for Flash<R> {
|
|
|
|
fn respond_to(self, req: &'r Request<'_>) -> ResultFuture<'r> {
|
2016-09-12 01:57:04 +00:00
|
|
|
trace_!("Flash: setting message: {}:{}", self.name, self.message);
|
2018-04-15 02:53:36 +00:00
|
|
|
req.cookies().add(self.cookie());
|
|
|
|
self.inner.respond_to(req)
|
2016-09-12 01:57:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-15 02:53:36 +00:00
|
|
|
impl<'a, 'r> Flash<&'a Request<'r>> {
|
|
|
|
/// Constructs a new message with the given name and message for the given
|
|
|
|
/// request.
|
2018-04-16 03:18:32 +00:00
|
|
|
fn named(name: &str, msg: &str, req: &'a Request<'r>) -> Flash<&'a Request<'r>> {
|
2016-09-12 01:57:04 +00:00
|
|
|
Flash {
|
|
|
|
name: name.to_string(),
|
|
|
|
message: msg.to_string(),
|
2018-04-15 02:53:36 +00:00
|
|
|
consumed: AtomicBool::new(false),
|
2018-04-16 03:18:32 +00:00
|
|
|
inner: req,
|
2018-04-15 02:53:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Clears the request cookie if it hasn't already been cleared.
|
|
|
|
fn clear_cookie_if_needed(&self) {
|
|
|
|
// Remove the cookie if it hasn't already been removed.
|
|
|
|
if !self.consumed.swap(true, Ordering::Relaxed) {
|
|
|
|
let cookie = Cookie::build(FLASH_COOKIE_NAME, "").path("/").finish();
|
|
|
|
self.inner.cookies().remove(cookie);
|
2016-09-12 01:57:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-11-02 17:48:43 +00:00
|
|
|
/// Returns the `name` of this message.
|
2016-09-12 01:57:04 +00:00
|
|
|
pub fn name(&self) -> &str {
|
2018-04-15 02:53:36 +00:00
|
|
|
self.clear_cookie_if_needed();
|
|
|
|
&self.name
|
2016-09-12 01:57:04 +00:00
|
|
|
}
|
|
|
|
|
2016-11-02 17:48:43 +00:00
|
|
|
/// Returns the `msg` contents of this message.
|
2016-09-12 01:57:04 +00:00
|
|
|
pub fn msg(&self) -> &str {
|
2018-04-15 02:53:36 +00:00
|
|
|
self.clear_cookie_if_needed();
|
|
|
|
&self.message
|
2016-09-12 01:57:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-15 02:53:36 +00:00
|
|
|
/// Retrieves a flash message from a flash cookie. If there is no flash cookie,
|
|
|
|
/// or if the flash cookie is malformed, an empty `Err` is returned.
|
2016-11-03 14:09:01 +00:00
|
|
|
///
|
|
|
|
/// The suggested use is through an `Option` and the `FlashMessage` type alias
|
|
|
|
/// in `request`: `Option<FlashMessage>`.
|
2018-04-15 02:53:36 +00:00
|
|
|
impl<'a, 'r> FromRequest<'a, 'r> for Flash<&'a Request<'r>> {
|
2016-09-12 01:57:04 +00:00
|
|
|
type Error = ();
|
|
|
|
|
2018-04-16 03:18:32 +00:00
|
|
|
fn from_request(req: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
2018-07-12 03:44:09 +00:00
|
|
|
trace_!("Flash: attempting to retrieve message.");
|
2018-04-16 03:18:32 +00:00
|
|
|
req.cookies().get(FLASH_COOKIE_NAME).ok_or(()).and_then(|cookie| {
|
2016-09-12 01:57:04 +00:00
|
|
|
trace_!("Flash: retrieving message: {:?}", cookie);
|
|
|
|
|
2017-02-09 07:53:29 +00:00
|
|
|
// Parse the flash message.
|
2017-01-27 07:08:15 +00:00
|
|
|
let content = cookie.value();
|
2020-05-17 00:55:11 +00:00
|
|
|
let (len_str, kv) = match content.find(FLASH_COOKIE_DELIM) {
|
|
|
|
Some(i) => (&content[..i], &content[(i + 1)..]),
|
|
|
|
None => return Err(()),
|
2016-09-12 01:57:04 +00:00
|
|
|
};
|
|
|
|
|
2018-04-16 03:18:32 +00:00
|
|
|
match len_str.parse::<usize>() {
|
|
|
|
Ok(i) if i <= kv.len() => Ok(Flash::named(&kv[..i], &kv[i..], req)),
|
|
|
|
_ => Err(())
|
|
|
|
}
|
2018-04-15 02:53:36 +00:00
|
|
|
}).into_outcome(Status::BadRequest)
|
2016-09-12 01:57:04 +00:00
|
|
|
}
|
|
|
|
}
|