use rocket::form::{Form, FromForm, Strict}; use rocket::response::status::BadRequest; use rocket::response::Redirect; use rocket::{get, post, uri, State}; use rocket_dyn_templates::Template; use serde::Serialize; use std::mem; use crate::states; #[derive(Serialize)] struct FormContext { id: u16, name: Option, email: Option, telefon: Option, message: Option, captcha: String, } #[get("/?&&&")] pub fn index( name: Option, email: Option, telefon: Option, message: Option, captcha_solutions: &State, ) -> Result> { let captcha = captcha::by_name(captcha::Difficulty::Easy, captcha::CaptchaName::Lucy); let captcha_base64 = match captcha.as_base64() { Some(s) => s, None => return Err(BadRequest(None)), }; let id = captcha_solutions.store_solution(&captcha.chars_as_string()); let form_context = FormContext { id, name, email, telefon, message, captcha: captcha_base64, }; Ok(Template::render("form", &form_context)) } #[derive(FromForm)] pub struct ContactForm { id: u16, name: String, email: String, telefon: String, message: String, captcha_answer: String, } #[post("/submit", data = "
")] pub fn submit( mut form: Form>, captcha_solutions: &State, ) -> Redirect { let path_prefix = uri!("/contact-form"); if !captcha_solutions.check_answer(form.id, &form.captcha_answer) { return Redirect::to(uri!( path_prefix, index( Some(mem::take(&mut form.name)), Some(mem::take(&mut form.email)), Some(mem::take(&mut form.telefon)), Some(mem::take(&mut form.message)), ) )); } Redirect::to(uri!(path_prefix, success())) } #[get("/success")] pub fn success() -> &'static str { "Ihre Anfrage wurde übermittelt! Wir melden uns bald bei Ihnen zurück." }