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)]
2021-03-06 03:34:40 +00:00
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate serde_derive;
2020-10-16 23:08:58 +00:00
2022-07-13 04:37:42 +00:00
use rocket::form::Form;
use rocket::request::FlashMessage;
2021-03-06 03:34:40 +00:00
use rocket::response::{Flash, Redirect};
2020-10-16 23:56:13 +00:00
use rocket_csrf::CsrfToken;
2022-07-13 04:37:42 +00:00
use rocket_dyn_templates::Template;
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,
}
2022-07-13 04:37:42 +00:00
#[launch]
fn rocket() -> _ {
rocket::build()
2021-03-06 02:34:27 +00:00
.attach(rocket_csrf::Fairing::default())
2020-10-16 23:08:58 +00:00
.attach(Template::fairing())
2020-10-16 23:25:10 +00:00
.mount("/", routes![index, new, create])
2020-10-16 23:08:58 +00:00
}
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-18 07:29:55 +00:00
authenticity_token: csrf_token.authenticity_token().to_string(),
2022-07-13 04:37:42 +00:00
flash: flash.map(|flash| flash.message().to_string()),
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) {
2021-03-06 03:34:40 +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
}