1
0
Fork 0
mirror of https://github.com/kotovalexarian/rocket_csrf.git synced 2025-04-21 17:22:23 -04:00

Improve example

This commit is contained in:
Alex Kotov 2020-10-17 04:25:10 +05:00
parent 735cc43d99
commit aa2fc038b0
Signed by: kotovalexarian
GPG key ID: 553C0EBBEB5D5F08
2 changed files with 22 additions and 7 deletions

View file

@ -3,13 +3,14 @@
#[macro_use] extern crate rocket;
#[macro_use] extern crate serde_derive;
use rocket::response::Redirect;
use rocket::request::Form;
use rocket::response::{Flash, Redirect};
use rocket::request::{FlashMessage, Form};
use rocket_contrib::templates::Template;
#[derive(Serialize)]
struct TemplateContext {
csrf_token: String,
flash: Option<String>,
}
#[derive(FromForm)]
@ -22,24 +23,36 @@ fn main() {
rocket::ignite()
.attach(rocket_csrf::Fairing::new())
.attach(Template::fairing())
.mount("/", routes![new, create])
.mount("/", routes![index, new, create])
.launch();
}
#[get("/")]
fn index() -> Redirect {
Redirect::to(uri!(new))
}
#[get("/comments/new")]
fn new(csrf: rocket_csrf::Guard) -> Template {
fn new(csrf: rocket_csrf::Guard, flash: Option<FlashMessage>) -> Template {
let template_context = TemplateContext {
csrf_token: csrf.0,
flash: flash.map(|msg| format!("{}! {}", msg.name(), msg.msg())),
};
Template::render("comments/new", &template_context)
}
#[post("/comments", data = "<form>")]
fn create(csrf: rocket_csrf::Guard, form: Form<Comment>) -> Redirect {
fn create(csrf: rocket_csrf::Guard, form: Form<Comment>) -> Flash<Redirect> {
if let Err(_) = csrf.verify(&form.authenticity_token) {
return Redirect::to(uri!(new));
return Flash::error(
Redirect::to(uri!(new)),
"invalid authenticity token",
);
}
Redirect::to(uri!(new))
Flash::success(
Redirect::to(uri!(new)),
format!("created comment: {:#?}", form.text),
)
}

View file

@ -1,3 +1,5 @@
{{ flash }}
<form method="post" action="/comments">
<input type="hidden" name="authenticity_token" value="{{ csrf_token }}"/>
<input type="text" name="text"/>