forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiB7aca449Tahinli2 minutes ago336 commits

theme_cookie.rs95 lines, 2.6 KiBHistoryRawDownload
1use serde::Deserialize;
2use topcoat::Result;
3use topcoat::context::{Cx, context};
4use topcoat::router::content::Form;
5use topcoat::router::error::{SeeOther, see_other};
6use topcoat::router::route;
7
8use forge_core::AuditAction;
9use forge_core::Store;
10use forge_core::store::ui_prefs::THEMES;
11
12use crate::audit::{self, Actor, Target};
13use crate::auth::{current_user, require_csrf};
14use crate::state::AppState;
15use crate::theme::set_theme_cookie;
16
17#[derive(Deserialize)]
18struct ThemeForm {
19 #[serde(default)]
20 csrf: String,
21 #[serde(default)]
22 theme: String,
23 #[serde(default)]
24 back: String,
25}
26
27pub fn safe_back(back: &str) -> &str {
28 let local = back.starts_with('/')
29 && !back.starts_with("//")
30 && !back.contains('\\')
31 && !back.chars().any(char::is_control);
32 if local { back } else { "/" }
33}
34
35#[route(POST "/-/theme")]
36async fn set_theme(cx: &Cx, Form(form): Form<ThemeForm>) -> Result<SeeOther> {
37 let back = safe_back(&form.back);
38 if current_user(cx).await?.is_none() {
39 if !THEMES.contains(&form.theme.as_str()) {
40 return Err(forge_core::Error::Invalid("theme".into()).into());
41 }
42 set_theme_cookie(cx, &form.theme);
43 return Ok(see_other(back));
44 }
45 let viewer = require_csrf(cx, &form.csrf).await?;
46 if !THEMES.contains(&form.theme.as_str()) {
47 return Err(forge_core::Error::Invalid("theme".into()).into());
48 }
49 let store: &Store = &context::<AppState>(cx).store;
50 store
51 .set_ui_prefs(&viewer.0.id, &form.theme, &viewer.0.language)
52 .await?;
53 audit::record(
54 store,
55 Some(cx),
56 Actor::User(&viewer.0),
57 AuditAction::UiPrefsChanged,
58 Target {
59 kind: "user",
60 id: &viewer.0.id,
61 name: &viewer.0.username,
62 },
63 serde_json::json!({ "theme": form.theme, "language": viewer.0.language }),
64 )
65 .await;
66 Ok(see_other(back))
67}
68
69#[cfg(test)]
70mod tests {
71 use super::safe_back;
72
73 #[test]
74 fn local_paths_are_kept() {
75 assert_eq!(safe_back("/explore?q=rust"), "/explore?q=rust");
76 assert_eq!(safe_back("/"), "/");
77 assert_eq!(safe_back("/acme/app/issues/3"), "/acme/app/issues/3");
78 }
79
80 #[test]
81 fn anything_else_falls_back_to_the_root() {
82 for back in [
83 "",
84 "//evil.com",
85 "https://evil.com",
86 "/\\evil",
87 "\\\\evil.com",
88 "evil.com/x",
89 "/ok\r\nSet-Cookie: x=1",
90 "/ok\nx",
91 ] {
92 assert_eq!(safe_back(back), "/", "{back:?}");
93 }
94 }
95}