steid

@jamesgill /

1//! Creating an organisation — `/orgs/new`.
2//!
3//! A static route, so it beats `/{handle}`; `orgs` and `organizations` are reserved in
4//! [`OrgName`](crate::domain::OrgName) as well, so the two agree rather than relying on
5//! routing order alone.
6//!
7//! Signed in only. An organisation is a handle at the root like a person's, and the
8//! actor who creates one becomes its owner.
9
10use serde::Deserialize;
11use topcoat::{
12 Result,
13 context::Cx,
14 router::{
15 StatusCode,
16 content::Form,
17 error::{not_found, redirect},
18 page,
19 },
20 view::{attributes, component, view},
21};
22
23use crate::{
24 application::{
25 Error, NewOrganisation, create_organization, home_handle, home_is_set, is_personal_handle,
26 set_home,
27 },
28 components::{
29 button::button,
30 flash::{FlashKind, flash},
31 input::input,
32 label::label,
33 },
34 domain::{DomainError, OrgName},
35};
36
37use super::{
38 context::{
39 current_actor, identity, instance_settings, location, memberships, orgs, server_error,
40 users,
41 },
42 csrf::{csrf_field, csrf_verified},
43 format::optional,
44 layout::narrow,
45};
46
47#[derive(Debug, Deserialize)]
48struct CreateForm {
49 /// The hidden field every form carries; see [`csrf`](super::csrf).
50 ///
51 /// `default` so that a submission with no token at all is refused by
52 /// `csrf_verified` — a 403 saying what happened — rather than failing
53 /// deserialization into a bare 400 that says nothing.
54 #[serde(default)]
55 csrf_token: String,
56 handle: String,
57 display_name: String,
58 /// The "make this the home page" box. Absent from the submission when unticked,
59 /// which is how an HTML checkbox travels.
60 #[serde(default)]
61 home: Option<String>,
62}
63
64/// Whether the instance has a home page yet.
65///
66/// Drives the checkbox's default: an instance nobody has chosen for offers to be
67/// pointed at the new organisation, and one that already has a home does not
68/// volunteer to move its own front door.
69pub(super) async fn home_chosen(cx: &Cx) -> Result<bool> {
70 home_is_set(&instance_settings(cx))
71 .await
72 .map_err(server_error)
73}
74
75/// Sends anyone who is not signed in to the sign-in page.
76///
77/// A GET guard, so `redirect`'s 307 is right — see the note on
78/// [`location`](super::context::location) for why a POST may not use it.
79async fn signed_in(cx: &Cx) -> Result<()> {
80 if identity(cx).await?.is_none() {
81 return Err(redirect("/auth/login").into());
82 }
83
84 Ok(())
85}
86
87#[page("/orgs/new")]
88async fn new_org_page(cx: &Cx) -> Result {
89 signed_in(cx).await?;
90
91 let offer_home = !home_chosen(cx).await?;
92
93 view! {
94 new_org_form(handle: "", display_name: "", home: offer_home, error: "")
95 }
96}
97
98/// Creates the organisation, and optionally points the root at it.
99///
100/// Success is a 303 to the new organisation's page — see
101/// [`location`](super::context::location) for why it is spelled this way rather than
102/// with `redirect()`, which is a 307 and would re-POST the form to its target.
103///
104/// **Home is set after the organisation exists, and a failure to set it does not undo
105/// the organisation.** The two are separate facts: an organisation that exists but is
106/// not the front door is a normal state a person can fix from its settings page, where
107/// rolling the creation back would throw away a handle they have already been told
108/// they hold.
109#[page(POST "/orgs/new")]
110async fn create(cx: &Cx, Form(submitted): Form<CreateForm>) -> Result {
111 // No sign-in guard of its own: `csrf_verified` already refuses a request with no
112 // session, uniformly, which is every anonymous POST to this route.
113 csrf_verified(cx, &submitted.csrf_token).await?;
114
115 let wants_home = submitted.home.is_some();
116 let actor = current_actor(cx).await?;
117
118 let outcome = create_organization(
119 &actor,
120 &NewOrganisation {
121 handle: submitted.handle.clone(),
122 display_name: optional(&submitted.display_name),
123 },
124 &orgs(cx),
125 &memberships(cx),
126 )
127 .await;
128
129 let message = match outcome {
130 Ok(org) => {
131 if wants_home {
132 set_home(
133 &actor,
134 &org.id,
135 &orgs(cx),
136 &memberships(cx),
137 &users(cx),
138 &instance_settings(cx),
139 )
140 .await
141 .map_err(|error| server_error(std::io::Error::other(error.to_string())))?;
142 }
143
144 return view! {
145 (StatusCode::SEE_OTHER)
146 (location(&format!("/{}", org.name))?)
147 };
148 }
149 Err(Error::Domain(DomainError::Validation { field, reason })) => {
150 format!("That {field} is no good: {reason}.")
151 }
152 Err(Error::Domain(DomainError::AlreadyExists { .. })) => {
153 format!(
154 "The handle {} is already taken on this instance.",
155 submitted.handle.trim()
156 )
157 }
158 // Unreachable: the CSRF check above has already refused anyone without a
159 // session, and that is the only way the use case says no.
160 Err(Error::Domain(DomainError::Forbidden)) => return Err(not_found().into()),
161 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
162 };
163
164 view! {
165 new_org_form(
166 handle: submitted.handle.as_str(),
167 display_name: submitted.display_name.as_str(),
168 home: wants_home,
169 error: message.as_str(),
170 )
171 }
172}
173
174/// The create form.
175///
176/// Values arrive as parameters rather than being read back from storage, so a rejected
177/// submission re-renders exactly what was typed.
178#[component]
179async fn new_org_form(handle: &str, display_name: &str, home: bool, error: &str) -> Result {
180 view! {
181 narrow(
182 <h1 class="text-xl font-semibold tracking-tight">"New organisation"</h1>
183 <p class="mt-1 text-sm text-muted-foreground">
184 "An organisation owns repositories the way a person does, and lives at "
185 "a handle of its own."
186 </p>
187
188 if !error.is_empty() {
189 <div class="mt-6">
190 flash(kind: FlashKind::Error, (error))
191 </div>
192 }
193
194 <form method="post" action="/orgs/new" class="mt-6 space-y-5">
195 csrf_field()
196 <div class="space-y-2">
197 label(attrs: attributes! { for="handle" }, "Handle")
198 input(attrs: attributes! {
199 id="handle"
200 name="handle"
201 type="text"
202 value=(handle)
203 placeholder="acme"
204 required=(true)
205 maxlength=(OrgName::MAX_LEN.to_string())
206 autofocus=(true)
207 })
208 <p class="text-xs text-muted-foreground">
209 "Letters, digits and hyphens. Lowercased. This is the URL: "
210 <code class="font-mono">"/acme"</code> "."
211 </p>
212 </div>
213
214 <div class="space-y-2">
215 label(attrs: attributes! { for="display_name" }, "Display name")
216 input(attrs: attributes! {
217 id="display_name"
218 name="display_name"
219 type="text"
220 value=(display_name)
221 placeholder="Acme Inc"
222 })
223 <p class="text-xs text-muted-foreground">
224 "Optional. Shown instead of the handle."
225 </p>
226 </div>
227
228 <div class="space-y-2">
229 <div class="flex items-start gap-2">
230 <input
231 id="home"
232 name="home"
233 type="checkbox"
234 value="on"
235 checked=(home)
236 class="mt-0.5"
237 />
238 label(attrs: attributes! { for="home" }, "Make this the home page")
239 </div>
240 <p class="text-xs text-muted-foreground">
241 "The root of this instance then lands on this organisation, for "
242 "everyone. One at a time."
243 </p>
244 </div>
245
246 <div class="flex items-center gap-3">
247 button(attrs: attributes! { type="submit" }, "Create organisation")
248 <a href="/" class="text-sm text-muted-foreground hover:text-foreground">
249 "Cancel"
250 </a>
251 </div>
252 </form>
253 )
254 }
255}
256
257/// Whether the organisation behind a handle has settings pages of its own.
258///
259/// A personal organisation does not: its profile is edited at the person's existing
260/// `/{handle}/settings`, and giving it a second set would be two forms writing one row.
261/// See [`is_personal_org`].
262pub(super) async fn is_personal(cx: &Cx, handle: &OrgName) -> Result<bool> {
263 is_personal_handle(handle, &orgs(cx), &users(cx))
264 .await
265 .map_err(server_error)
266}
267
268/// The handle the root URL lands on, or `None` when nobody has chosen and there is no
269/// sole owner to fall back to.
270pub(super) async fn home(cx: &Cx) -> Result<Option<OrgName>> {
271 home_handle(&instance_settings(cx), &users(cx), &orgs(cx))
272 .await
273 .map_err(server_error)
274}