rocket_csrf/examples/minimal/src/main.rs

60 lines
1.4 KiB
Rust
Raw Normal View History

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