forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

lang.rs41 lines, 1.2 KiBHistoryRawDownload
1use serde::Deserialize;
2use topcoat::{
3 Result,
4 context::Cx,
5 cookie::{Cookies, cookies},
6 router::{
7 content::Form,
8 error::{SeeOther, bad_request, see_other},
9 route,
10 },
11};
12
13use crate::i18n::{Lang, lang_cookie};
14
15#[derive(Deserialize)]
16struct LangForm {
17 lang: String,
18 /// Where to return to. Only a relative path on this site is accepted.
19 #[serde(default)]
20 back: String,
21}
22
23/// Accepts "/..." paths on this site. Rejects "//host" and "/\host", which browsers read as
24/// other hosts, and anything with control characters.
25pub(super) fn safe_back(back: &str) -> &str {
26 let ok = back.starts_with('/')
27 && !back.starts_with("//")
28 && !back.starts_with("/\\")
29 && !back.chars().any(|c| c.is_control());
30 if ok { back } else { "/" }
31}
32
33/// POST /lang: stores the chosen language in a cookie and returns to the page it was
34/// chosen on.
35#[route(POST)]
36async fn set_lang(cx: &Cx, Form(form): Form<LangForm>) -> Result<SeeOther> {
37 let lang = Lang::from_code(form.lang.trim())
38 .ok_or_else(|| bad_request("unsupported language"))?;
39 cookies(cx).add(lang_cookie(lang));
40 Ok(see_other(safe_back(&form.back)))
41}