use serde::Deserialize; use topcoat::{ Result, context::Cx, cookie::{Cookies, cookies}, router::{ content::Form, error::{SeeOther, bad_request, see_other}, route, }, }; use crate::i18n::{Lang, lang_cookie}; #[derive(Deserialize)] struct LangForm { lang: String, /// Where to return to. Only a relative path on this site is accepted. #[serde(default)] back: String, } /// Accepts "/..." paths on this site. Rejects "//host" and "/\host", which browsers read as /// other hosts, and anything with control characters. pub(super) fn safe_back(back: &str) -> &str { let ok = back.starts_with('/') && !back.starts_with("//") && !back.starts_with("/\\") && !back.chars().any(|c| c.is_control()); if ok { back } else { "/" } } /// POST /lang: stores the chosen language in a cookie and returns to the page it was /// chosen on. #[route(POST)] async fn set_lang(cx: &Cx, Form(form): Form) -> Result { let lang = Lang::from_code(form.lang.trim()) .ok_or_else(|| bad_request("unsupported language"))?; cookies(cx).add(lang_cookie(lang)); Ok(see_other(safe_back(&form.back))) }