Skip to main content

tablo_core/auth/
tenant_profile.rs

1//! The panel's tenant settings page: the [`TenantEditor`] trait that edits the tenant the request
2//! acts for, and the `{prefix}/tenant/profile` routes.
3
4use 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
27/// How a panel lets the signed-in user edit the tenant they act for on its settings page,
28/// installed with [`Auth::tenant_profile`](super::Auth::tenant_profile).
29///
30/// It mirrors a [`ProfileEditor`](super::ProfileEditor), for the request's
31/// [`Membership`]: [`may_edit`](Self::may_edit) says who may open the page,
32/// [`fill`](Self::fill) loads the form from the tenant, [`validate`](Self::validate) refuses a
33/// submission field by field, and [`save`](Self::save) writes it. `validate` and `save` run in one
34/// transaction the framework opens.
35///
36/// ```rust
37/// # use tablo_core::{Membership, PanelUser, TenantEditor};
38/// # use topcoat::context::Cx;
39/// # #[derive(Debug, Clone, toasty::Model)]
40/// # struct Team { #[key] id: uuid::Uuid, name: String }
41/// # struct Staff { owner: bool }
42/// # impl PanelUser for Staff {
43/// #     fn user_id(&self) -> String { String::new() }
44/// #     fn display_name(&self) -> &str { "" }
45/// #     fn can_access_panel(&self, _panel: &tablo_core::PanelId) -> bool { true }
46/// # }
47/// #[derive(tablo_core::FormInput)]
48/// struct TeamSettings {
49///     name: String,
50/// }
51///
52/// struct Teams;
53///
54/// impl TenantEditor for Teams {
55///     type Input = TeamSettings;
56///     type User = Staff;
57///
58///     fn may_edit(&self, _cx: &Cx, staff: &Staff, _team: &Membership) -> bool {
59///         staff.owner
60///     }
61///
62///     async fn fill(
63///         &self,
64///         _cx: &Cx,
65///         _staff: &Staff,
66///         team: &Membership,
67///     ) -> topcoat::Result<TeamSettings> {
68///         Ok(TeamSettings {
69///             name: team.name.clone(),
70///         })
71///     }
72///
73///     async fn save(
74///         &self,
75///         _cx: &Cx,
76///         _staff: &Staff,
77///         team: &Membership,
78///         settings: TeamSettings,
79///         ex: &mut dyn toasty::Executor,
80///     ) -> topcoat::Result<()> {
81///         Team::filter_by_id(team.tenant.get())
82///             .update()
83///             .name(settings.name)
84///             .exec(ex)
85///             .await?;
86///         Ok(())
87///     }
88/// }
89/// ```
90pub trait TenantEditor: Send + Sync + 'static {
91    /// What the settings page asks for: the app's own
92    /// [`#[derive(FormInput)]`](derive@crate::FormInput) struct.
93    type Input: FormInput;
94
95    /// The user who edits the tenant: the type the panel's
96    /// [`Authenticator`](super::Authenticator) loads, which mounting checks.
97    type User: PanelUser;
98
99    /// Whether `user` may edit `tenant`, one of their memberships. Defaults to every member. A
100    /// user who may not gets no link to the page, and the page answers them 403.
101    fn may_edit(&self, _cx: &Cx, _user: &Self::User, _tenant: &Membership) -> bool {
102        true
103    }
104
105    /// The form as the page first shows it, loaded for `tenant`. The page renders what
106    /// [`FormInput::write`] writes.
107    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    /// Refuse a submission [`save`](Self::save) should not receive: each error names an input
115    /// field's key and renders under its control. Defaults to none. A key no control renders is
116    /// a declaration error: the page would show no message.
117    ///
118    /// It runs inside the save's transaction `ex`, after the input parses and its controls' own
119    /// rules pass.
120    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    /// Write a validated `input` to `tenant` through the transaction `ex`, which commits when it
132    /// returns `Ok`.
133    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
143/// What a tenant settings submission came to.
144pub(crate) enum Outcome {
145    /// The committed change.
146    Saved,
147    /// The refused submission, its values, and why.
148    Refused {
149        values: FormValues,
150        errors: FieldErrors,
151    },
152}
153
154/// [`TenantEditor`] with its input and user types erased, as the panel keeps it.
155pub(crate) trait DynTenantEditor: Send + Sync {
156    /// The settings form.
157    fn schema(&self) -> Schema;
158    /// Whether `user` may edit `tenant`; `false` for a user of another type.
159    fn may_edit(&self, cx: &Cx, user: &dyn PanelUser, tenant: &Membership) -> bool;
160    /// The form's first values for `tenant`, or `None` for a user of another type.
161    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    /// Parses, checks, validates and saves one submission for `signed`'s user and `tenant`.
168    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
252/// A failed tenant read or write: a database failure becomes the opaque outage, logged; an
253/// editor's own error keeps its mapping.
254fn write_failure(error: topcoat::Error) -> topcoat::Error {
255    crate::error::driver_failure(error, crate::error::DATABASE_UNAVAILABLE)
256}
257
258/// The hidden field naming the tenant the form was filled from: a tab opened before another
259/// switched tenants must not save over the new one.
260const TENANT_FIELD: &str = "editing_tenant";
261
262/// The keys a tenant settings POST carries besides its input, which no input field may post.
263pub(crate) const RESERVED_KEYS: [&str; 2] = [crate::csrf::FIELD_NAME, TENANT_FIELD];
264
265/// Where the panel's tenant settings page lives: `{prefix}/tenant/profile`, or in the area that
266/// holds it.
267pub(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
274/// Whether the request's signed-in user may open the tenant settings page for the tenant they act
275/// for, which the gate refuses to someone acting as them.
276pub(crate) fn offered(cx: &Cx) -> bool {
277    !super::impersonation::acting(cx) && editing(cx).is_ok()
278}
279
280/// The signed-in user, the panel's editor and the membership the request acts under, or the
281/// answer to a request without them: 404 without an editor, 403 without a tenant the user may
282/// edit.
283fn 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
294/// `GET {prefix}/tenant/profile` — the settings form, filled from the tenant.
295pub(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
307/// `POST {prefix}/tenant/profile` — save the settings, then land back on the page.
308pub(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
337/// The settings page in the panel's shell: the editor's form for `tenant` with `values` and
338/// `errors`, saved to the page itself, cancelled to the panel's home.
339async 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
357/// The mistakes in a panel's [`Auth::tenant_profile`](super::Auth::tenant_profile): a settings
358/// page without auth, an editor whose user is not the authenticator's, and a form field the page
359/// cannot serve.
360pub(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}