use rocket::form::{Form, 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::captcha_solutions; use crate::config; use crate::forms; use crate::mailer; #[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)) } #[post("/submit", data = "
")] pub fn submit( mut form: Form>, config: &State, captcha_solutions: &State, mailer: &State, ) -> Redirect { let path_prefix = config.path_prefix.clone(); let name = mem::take(&mut form.name); let email = mem::take(&mut form.email); let telefon = mem::take(&mut form.telefon); let message = mem::take(&mut form.message); if !captcha_solutions.check_answer(form.id, &form.captcha_answer) { return Redirect::to( path_prefix + &uri!(index(Some(name), Some(email), Some(telefon), Some(message))).to_string(), ); } match mailer.send(&name, &email, &telefon, &message) { Ok(_) => (), Err(_) => { return Redirect::to( path_prefix + &uri!(index(Some(name), Some(email), Some(telefon), Some(message))) .to_string(), ) } } Redirect::to(path_prefix + &uri!(success()).to_string()) } #[get("/success")] pub fn success() -> &'static str { "Ihre Anfrage wurde übermittelt! Wir melden uns bald bei Ihnen zurück." }