use rocket::form::{Form, Strict}; use rocket::response::status::BadRequest; use rocket::response::Redirect; use rocket::{get, post, uri, State}; use rocket_dyn_templates::{context, Template}; use std::mem; use crate::captcha_solutions; use crate::config; use crate::context; use crate::forms; use crate::mailer; #[get("/?&&&&")] pub fn index( was_validated: Option, name: Option<&str>, email: Option<&str>, telefon: Option<&str>, message: Option<&str>, config: &State, 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 = context::FormContext::new( &config.path_prefix, was_validated, id, name, email, telefon, message, &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(true), 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(true), Some(&name), Some(&email), Some(&telefon), Some(&message) )) .to_string(), ) } } Redirect::to(path_prefix + &uri!(success()).to_string()) } #[get("/success")] pub fn success() -> Template { Template::render("success", context! {}) }