1use std::{any::Any, future::Future};
5
6use topcoat::{
7 context::Cx,
8 router::{
9 Body,
10 error::{forbidden, not_found, see_other},
11 },
12 view::BoxView,
13};
14
15use super::{PanelUser, SignedIn, input, membership, signed, unauthenticated_error};
16use crate::{
17 BoxFuture,
18 auth::realm::{SettingsPage, current_realm, hosted, panel_prefix},
19 flash::set_notification,
20 form::{FieldErrors, FormInput, FormValues},
21 outcome::Notification,
22 schema::Schema,
23 tenancy::Membership,
24 topcoat_compat::async_page,
25};
26
27pub trait TenantEditor: Send + Sync + 'static {
91 type Input: FormInput;
94
95 type User: PanelUser;
98
99 fn may_edit(&self, _cx: &Cx, _user: &Self::User, _tenant: &Membership) -> bool {
102 true
103 }
104
105 fn fill(
108 &self,
109 cx: &Cx,
110 user: &Self::User,
111 tenant: &Membership,
112 ) -> impl Future<Output = topcoat::Result<Self::Input>> + Send;
113
114 fn validate(
121 &self,
122 _cx: &Cx,
123 _user: &Self::User,
124 _tenant: &Membership,
125 _input: &Self::Input,
126 _ex: &mut dyn toasty::Executor,
127 ) -> impl Future<Output = topcoat::Result<FieldErrors>> + Send {
128 async { Ok(FieldErrors::new()) }
129 }
130
131 fn save(
134 &self,
135 cx: &Cx,
136 user: &Self::User,
137 tenant: &Membership,
138 input: Self::Input,
139 ex: &mut dyn toasty::Executor,
140 ) -> impl Future<Output = topcoat::Result<()>> + Send;
141}
142
143pub(crate) enum Outcome {
145 Saved,
147 Refused {
149 values: FormValues,
150 errors: FieldErrors,
151 },
152}
153
154pub(crate) trait DynTenantEditor: Send + Sync {
156 fn schema(&self) -> Schema;
158 fn may_edit(&self, cx: &Cx, user: &dyn PanelUser, tenant: &Membership) -> bool;
160 fn values<'a>(
162 &'a self,
163 cx: &'a Cx,
164 user: &'a dyn PanelUser,
165 tenant: &'a Membership,
166 ) -> BoxFuture<'a, topcoat::Result<Option<FormValues>>>;
167 fn submit<'a>(
169 &'a self,
170 cx: &'a Cx,
171 signed: &'a SignedIn,
172 tenant: &'a Membership,
173 values: FormValues,
174 ) -> BoxFuture<'a, topcoat::Result<Outcome>>;
175}
176
177impl<E: TenantEditor> DynTenantEditor for E {
178 fn schema(&self) -> Schema {
179 E::Input::schema()
180 }
181
182 fn may_edit(&self, cx: &Cx, user: &dyn PanelUser, tenant: &Membership) -> bool {
183 let user: &dyn Any = user;
184 user.downcast_ref::<E::User>()
185 .is_some_and(|user| TenantEditor::may_edit(self, cx, user, tenant))
186 }
187
188 fn values<'a>(
189 &'a self,
190 cx: &'a Cx,
191 user: &'a dyn PanelUser,
192 tenant: &'a Membership,
193 ) -> BoxFuture<'a, topcoat::Result<Option<FormValues>>> {
194 Box::pin(async move {
195 let user: &dyn Any = user;
196 let Some(user) = user.downcast_ref::<E::User>() else {
197 return Ok(None);
198 };
199 let mut values = FormValues::new();
200 self.fill(cx, user, tenant)
201 .await
202 .map_err(write_failure)?
203 .write(&mut values);
204 Ok(Some(values))
205 })
206 }
207
208 fn submit<'a>(
209 &'a self,
210 cx: &'a Cx,
211 signed: &'a SignedIn,
212 tenant: &'a Membership,
213 mut values: FormValues,
214 ) -> BoxFuture<'a, topcoat::Result<Outcome>> {
215 Box::pin(async move {
216 let any: &dyn Any = &*signed.user;
217 let user = any
218 .downcast_ref::<E::User>()
219 .ok_or_else(|| topcoat::Error::from(forbidden()))?;
220 let schema = E::Input::schema();
221 let mut stored = FormValues::new();
222 self.fill(cx, user, tenant)
223 .await
224 .map_err(write_failure)?
225 .write(&mut stored);
226 input::keep_disabled(&schema, &mut values, &stored);
227 schema.keep_unedited(&mut values, &stored, &crate::time_zone(cx));
228 let input =
229 match input::parse::<E::Input>(cx, &values, &stored, "tenant settings").await? {
230 Ok(input) => input,
231 Err(errors) => return Ok(Outcome::Refused { values, errors }),
232 };
233 let mut db = crate::db::db(cx)?;
234 let mut tx = db.transaction().await.map_err(crate::error::unavailable)?;
235 let errors = self
236 .validate(cx, user, tenant, &input, &mut tx)
237 .await
238 .map_err(write_failure)?;
239 input::placed(&schema, &errors, "the tenant editor", "tenant settings")?;
240 if !errors.is_empty() {
241 return Ok(Outcome::Refused { values, errors });
242 }
243 self.save(cx, user, tenant, input, &mut tx)
244 .await
245 .map_err(write_failure)?;
246 tx.commit().await.map_err(crate::error::unavailable)?;
247 Ok(Outcome::Saved)
248 })
249 }
250}
251
252fn write_failure(error: topcoat::Error) -> topcoat::Error {
255 crate::error::driver_failure(error, crate::error::DATABASE_UNAVAILABLE)
256}
257
258const TENANT_FIELD: &str = "editing_tenant";
261
262pub(crate) const RESERVED_KEYS: [&str; 2] = [crate::csrf::FIELD_NAME, TENANT_FIELD];
264
265pub(crate) fn tenant_profile_url(cx: &Cx) -> String {
268 current_realm(cx).map_or_else(
269 || format!("{}/tenant/profile", panel_prefix(cx)),
270 |realm| realm.pages.tenant_profile.clone(),
271 )
272}
273
274pub(crate) fn offered(cx: &Cx) -> bool {
277 !super::impersonation::acting(cx) && editing(cx).is_ok()
278}
279
280fn editing(cx: &Cx) -> topcoat::Result<(&SignedIn, &dyn DynTenantEditor, &Membership)> {
284 let signed = signed(cx).ok_or_else(|| unauthenticated_error(cx))?;
285 let editor = current_realm(cx)
286 .and_then(|panel| panel.auth.tenant_editor())
287 .ok_or_else(not_found)?;
288 let tenant = membership(cx)
289 .filter(|tenant| editor.may_edit(cx, signed.user.as_ref(), tenant))
290 .ok_or_else(forbidden)?;
291 Ok((signed, editor, tenant))
292}
293
294pub(super) fn tenant_profile_page(cx: &Cx, _body: Body) -> BoxView<'_> {
296 async_page(async move {
297 let (signed, editor, tenant) = editing(cx)?;
298 let values = editor
299 .values(cx, signed.user.as_ref(), tenant)
300 .await?
301 .ok_or_else(forbidden)?;
302 crate::csrf::ensure_token(cx);
303 render(cx, editor, tenant, &values, &FieldErrors::new()).await
304 })
305}
306
307pub(super) fn tenant_profile_post(cx: &Cx, body: Body) -> BoxView<'_> {
309 async_page(async move {
310 let (signed, editor, tenant) = editing(cx)?;
311 let form = crate::auth::input::read_form(cx, body).await?;
312 crate::csrf::verify(cx, form.last(crate::csrf::FIELD_NAME))?;
313 if form.last(TENANT_FIELD) != Some(tenant.tenant.to_string().as_str()) {
314 set_notification(
315 cx,
316 Notification::warning(crate::t!(cx, "tablo-tenant-not-saved")).description(
317 crate::t!(cx, "tablo-tenant-switched", tenant = tenant.name.clone()),
318 ),
319 );
320 return Err(see_other(tenant_profile_url(cx)).into());
321 }
322 let input_schema = editor.schema();
323 let values = input_schema.read_input(cx, &form.pairs, &RESERVED_KEYS)?;
324 if let Outcome::Refused { values, errors } =
325 editor.submit(cx, signed, tenant, values).await?
326 {
327 return render(cx, editor, tenant, &values, &errors).await;
328 }
329 set_notification(
330 cx,
331 Notification::success(crate::t!(cx, "tablo-tenant-saved")),
332 );
333 Err(see_other(tenant_profile_url(cx)).into())
334 })
335}
336
337async fn render<'a>(
340 cx: &'a Cx,
341 editor: &dyn DynTenantEditor,
342 tenant: &Membership,
343 values: &FormValues,
344 errors: &FieldErrors,
345) -> topcoat::Result<BoxView<'a>> {
346 let schema = editor.schema();
347 let page = SettingsPage {
348 title: crate::t!(cx, "tablo-shell-tenant-settings"),
349 schema: &schema,
350 hidden: Some((TENANT_FIELD, tenant.tenant.to_string())),
351 values,
352 errors,
353 };
354 hosted(cx)?.settings_page(cx, page).await
355}
356
357pub(super) fn declaration_errors(auth: &super::AuthConfig) -> Vec<crate::DeclarationErrorKind> {
361 use super::input::FieldFault;
362 use crate::{DeclarationErrorKind, declaration::TenantProfileFault as Fault};
363
364 let Some(editor) = auth.tenant_editor.as_deref() else {
365 return Vec::new();
366 };
367 if auth.authenticator().is_none() {
368 return vec![DeclarationErrorKind::TenantProfile(Fault::AuthDisabled)];
369 }
370 let mut kinds = Vec::new();
371 let schema = editor.schema();
372 kinds.extend(schema.declaration_errors());
373 kinds.extend(schema.empty_choices());
374 kinds.extend(
375 input::field_faults(&schema, &RESERVED_KEYS).map(|(fault, name)| {
376 DeclarationErrorKind::TenantProfile(match fault {
377 FieldFault::Reserved => Fault::ReservedField(name),
378 FieldFault::File => Fault::FileField(name),
379 FieldFault::Relationship => Fault::RelationshipField(name),
380 })
381 }),
382 );
383 kinds
384}