forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

setup.rs153 lines, 5.6 KiBHistoryRawDownload
1//! First-run setup. While no user exists, `GET /setup` shows the form that creates the first
2//! administrator. Once a user exists, both the page and its POST are a 404, so the route does not
3//! reveal that the instance was set up.
4
5use im_core::model::{AuditAction, amr};
6use im_core::names::{normalize_email, parse_display_name, parse_email};
7use im_core::password::{check_policy, hash_password_async};
8use im_core::store::sessions::SignInState;
9use serde::Deserialize;
10use serde_json::Value;
11use topcoat::Result;
12use topcoat::context::{Cx, app_context};
13use topcoat::router::content::Form;
14use topcoat::router::error::{forbidden, not_found, see_other};
15use topcoat::router::page;
16use topcoat::view::{View, view};
17
18use crate::audit::{Actor, record};
19use crate::auth::{after_sign_in, check_pre_csrf, clear_pre_csrf, pre_csrf_token, start_session};
20use crate::i18n::Lang;
21use crate::i18n::account::{Txt, policy_problem, text};
22use crate::state::AppState;
23use crate::views::{alert, field, page_lang, shell};
24
25/// The fields of the setup form. Every field defaults to empty, so a missing one is a failed check
26/// (403 for the token, a message for the rest), not a 400.
27#[derive(Deserialize, Default)]
28struct SetupForm {
29 #[serde(default)]
30 precsrf: String,
31 #[serde(default)]
32 name: String,
33 #[serde(default)]
34 email: String,
35 #[serde(default)]
36 password: String,
37 #[serde(default)]
38 password_again: String,
39}
40
41/// `GET /setup`.
42#[page("/setup")]
43async fn setup_form(cx: &Cx) -> Result<impl View> {
44 if app_context::<AppState>(cx).store.user_count().await? > 0 {
45 return Err(not_found().into());
46 }
47 let csrf = pre_csrf_token(cx);
48 let lang = page_lang(cx, None);
49 Ok(setup_view(
50 cx,
51 lang,
52 csrf,
53 String::new(),
54 String::new(),
55 None,
56 ))
57}
58
59/// `POST /setup`. Creates the first administrator, signs them in and sends them on.
60#[page(POST "/setup")]
61async fn setup_submit(cx: &Cx, Form(form): Form<SetupForm>) -> Result<impl View> {
62 let state = app_context::<AppState>(cx);
63 if state.store.user_count().await? > 0 {
64 return Err(not_found().into());
65 }
66 if !check_pre_csrf(cx, &form.precsrf) {
67 return Err(forbidden().into());
68 }
69 let csrf = pre_csrf_token(cx);
70 let lang = page_lang(cx, None);
71 let typed_email = form.email.clone();
72
73 // A refused name is not shown back: it may hold control characters, which must not reach HTML.
74 let name = match parse_display_name(&form.name) {
75 Ok(name) => name,
76 Err(_) => {
77 let problem = text(lang, Txt::ErrNameInvalid).to_owned();
78 return Ok(setup_view(
79 cx,
80 lang,
81 csrf,
82 String::new(),
83 typed_email,
84 Some(problem),
85 ));
86 }
87 };
88 let problem = match parse_email(&normalize_email(&form.email)) {
89 Err(_) => Some(text(lang, Txt::ErrEmailInvalid).to_owned()),
90 Ok(email) => match check_policy(&form.password, &email, &name) {
91 Err(violation) => Some(policy_problem(lang, violation)),
92 Ok(()) if form.password != form.password_again => {
93 Some(text(lang, Txt::ErrPasswordsDiffer).to_owned())
94 }
95 Ok(()) => None,
96 },
97 };
98 if let Some(problem) = problem {
99 return Ok(setup_view(cx, lang, csrf, name, typed_email, Some(problem)));
100 }
101
102 let email = parse_email(&normalize_email(&form.email))?;
103 let hash = hash_password_async(form.password.clone()).await?;
104 let user = match state.store.create_first_admin(&email, &name, &hash).await {
105 Ok(user) => user,
106 // Another setup finished first; the page no longer exists for this request either.
107 Err(im_core::Error::Conflict(_)) => return Err(not_found().into()),
108 Err(error) => return Err(error.into()),
109 };
110 if !start_session(cx, &user, amr::PASSWORD, SignInState::of(&user)).await? {
111 clear_pre_csrf(cx);
112 return Err(see_other("/login").into());
113 }
114 clear_pre_csrf(cx);
115 record(
116 cx,
117 Actor::User(&user.id),
118 AuditAction::SetupDone,
119 Some(("user", &user.id)),
120 Value::Null,
121 )
122 .await;
123 Err(see_other(after_sign_in(state, &user, "/")).into())
124}
125
126/// The setup page. The typed name and email come back; passwords never do.
127fn setup_view(
128 cx: &Cx,
129 lang: Lang,
130 csrf: String,
131 name: String,
132 email: String,
133 problem: Option<String>,
134) -> impl View {
135 view! { cx => shell(title: text(lang, Txt::SetupTitle), lang: lang, viewer: None,
136 <section class="card narrow stack">
137 <h1>(text(lang, Txt::SetupTitle))</h1>
138 <p class="muted">(text(lang, Txt::SetupIntro))</p>
139 if let Some(problem) = problem {
140 alert(message: problem)
141 }
142 <form method="post" action="/setup" class="stack">
143 <input type="hidden" name="precsrf" value=(csrf)>
144 field(label: text(lang, Txt::Name), name: "name", kind: "text", autocomplete: "name", value: name)
145 field(label: text(lang, Txt::Email), name: "email", kind: "email", autocomplete: "username", value: email)
146 field(label: text(lang, Txt::Password), name: "password", kind: "password", autocomplete: "new-password", value: String::new())
147 field(label: text(lang, Txt::NewPasswordAgain), name: "password_again", kind: "password", autocomplete: "new-password", value: String::new())
148 <p class="hint">(text(lang, Txt::PasswordHint))</p>
149 <button type="submit" class="button primary">(text(lang, Txt::CreateAdmin))</button>
150 </form>
151 </section>
152 ) }
153}