Skip to main content

tablo_core/auth/
profile.rs

1//! The panel's profile page: the [`ProfileEditor`] trait that edits the signed-in account, the
2//! shipped [`Profile`] form, and the `{prefix}/profile` routes.
3
4use std::{
5    any::{Any, TypeId},
6    future::Future,
7};
8
9use topcoat::{
10    context::{Cx, try_context},
11    router::{
12        Body,
13        error::{forbidden, not_found, see_other, too_many_requests},
14        request::client_ip,
15    },
16    view::BoxView,
17};
18
19use super::{
20    PanelUser, SignedIn, email_change::Requested, input, registration::new_password_errors,
21    session::replace_sessions, signed, unauthenticated_error,
22};
23use crate::{
24    BoxFuture,
25    auth::realm::{SettingsPage, current_realm, hosted, panel_prefix},
26    flash::set_notification,
27    form::{FieldError, FieldErrors, FormInput, FormValues, parse_password, parse_scalar},
28    outcome::Notification,
29    schema::{Field, Schema},
30    topcoat_compat::async_page,
31};
32
33/// How a panel lets the signed-in user edit their own account on its profile page, installed
34/// with [`Auth::profile`](super::Auth::profile).
35///
36/// It mirrors a [`Registrar`](super::Registrar): [`Input`](Self::Input) is the form the page
37/// shows, [`fill`](Self::fill) seeds it from the account, [`validate`](Self::validate) refuses a
38/// submission field by field, and [`save`](Self::save) writes it. `validate` and `save` run in one
39/// transaction the framework opens.
40///
41/// [`PasswordAuth`](super::PasswordAuth) edits a [`PasswordAccount`](super::PasswordAccount)
42/// through a [`Profile`]; an app whose user table is not one, or whose page asks for more,
43/// implements it beside its [`Authenticator`](super::Authenticator), for the same user type:
44///
45/// ```rust
46/// # use tablo_core::{PanelUser, ProfileEditor, ProfileUpdate};
47/// # use topcoat::context::Cx;
48/// # #[derive(Debug, Clone, toasty::Model)]
49/// # struct Staff {
50/// #     #[key] #[auto] id: uuid::Uuid,
51/// #     name: String,
52/// # }
53/// # impl PanelUser for Staff {
54/// #     fn user_id(&self) -> String { self.id.to_string() }
55/// #     fn display_name(&self) -> &str { &self.name }
56/// #     fn can_access_panel(&self, _panel: &tablo_core::PanelId) -> bool { true }
57/// # }
58/// #[derive(tablo_core::FormInput)]
59/// struct Rename {
60///     name: String,
61/// }
62///
63/// struct StaffProfile;
64///
65/// impl ProfileEditor for StaffProfile {
66///     type Input = Rename;
67///     type User = Staff;
68///
69///     fn fill(&self, _cx: &Cx, staff: &Staff) -> Rename {
70///         Rename {
71///             name: staff.name.clone(),
72///         }
73///     }
74///
75///     async fn save(
76///         &self,
77///         _cx: &Cx,
78///         staff: &Staff,
79///         rename: Rename,
80///         ex: &mut dyn toasty::Executor,
81///     ) -> topcoat::Result<ProfileUpdate> {
82///         Staff::filter(Staff::fields().id().eq(staff.id))
83///             .update()
84///             .name(rename.name)
85///             .exec(ex)
86///             .await?;
87///         Ok(ProfileUpdate::Details)
88///     }
89/// }
90/// ```
91pub trait ProfileEditor: Send + Sync + 'static {
92    /// What the profile page asks for: [`Profile`], or the app's own
93    /// [`#[derive(FormInput)]`](derive@crate::FormInput) struct.
94    type Input: FormInput;
95
96    /// The account the page edits: the type the panel's [`Authenticator`](super::Authenticator)
97    /// loads, which mounting checks.
98    type User: PanelUser;
99
100    /// The form as the page first shows it, from the signed-in `user`. The page renders what
101    /// [`FormInput::write`] writes, so an input that never writes its passwords shows them
102    /// empty.
103    fn fill(&self, cx: &Cx, user: &Self::User) -> Self::Input;
104
105    /// Refuse a submission [`save`](Self::save) should not receive, such as a wrong current
106    /// password: each error names an input field's key and renders under its control. Defaults
107    /// to none. A key no control renders is a declaration error: the page would show no message.
108    ///
109    /// It runs inside the save's transaction `ex`, after the input parses and its controls' own
110    /// rules pass.
111    fn validate(
112        &self,
113        _cx: &Cx,
114        _user: &Self::User,
115        _input: &Self::Input,
116        _ex: &mut dyn toasty::Executor,
117    ) -> impl Future<Output = topcoat::Result<FieldErrors>> + Send {
118        async { Ok(FieldErrors::new()) }
119    }
120
121    /// Write a validated `input` to `user`'s account through the transaction `ex`, which commits
122    /// when it returns `Ok`, and say whether a credential changed.
123    fn save(
124        &self,
125        cx: &Cx,
126        user: &Self::User,
127        input: Self::Input,
128        ex: &mut dyn toasty::Executor,
129    ) -> impl Future<Output = topcoat::Result<ProfileUpdate>> + Send;
130}
131
132/// What a [`ProfileEditor::save`] changed, which decides what happens to the user's sessions.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134#[non_exhaustive]
135pub enum ProfileUpdate {
136    /// Nothing the user signs in with: every session stays signed in.
137    Details,
138    /// Something the user signs in with, such as a password: the user's sessions and reset links
139    /// end on every panel whose authenticator loads the same user type, in the transaction that
140    /// saves, and the browser that saved gets a new session under the tenant it acted for.
141    Credentials,
142}
143
144/// What a profile submission came to.
145pub(crate) enum Outcome {
146    /// The committed change, its sessions replaced when a credential changed; `email_pending`
147    /// when it asked a new address to confirm itself.
148    Saved { email_pending: bool },
149    /// The refused submission, its values, and why. The page renders a password control empty.
150    Refused {
151        values: FormValues,
152        errors: FieldErrors,
153    },
154}
155
156/// [`ProfileEditor`] with its input and user types erased, as the panel keeps it.
157pub(crate) trait DynProfileEditor: Send + Sync {
158    /// The profile form.
159    fn schema(&self) -> Schema;
160    /// The form's first values for `user`, or `None` for a user of another type.
161    fn values(&self, cx: &Cx, user: &dyn PanelUser) -> Option<FormValues>;
162    /// Parses, checks, validates and saves one submission for `signed`'s user, replacing their
163    /// sessions in the same transaction when a credential changed.
164    fn submit<'a>(
165        &'a self,
166        cx: &'a Cx,
167        signed: &'a SignedIn,
168        values: FormValues,
169    ) -> BoxFuture<'a, topcoat::Result<Outcome>>;
170}
171
172impl<E: ProfileEditor> DynProfileEditor for E {
173    fn schema(&self) -> Schema {
174        E::Input::schema()
175    }
176
177    fn values(&self, cx: &Cx, user: &dyn PanelUser) -> Option<FormValues> {
178        let user: &dyn Any = user;
179        let user = user.downcast_ref::<E::User>()?;
180        let mut values = FormValues::new();
181        self.fill(cx, user).write(&mut values);
182        Some(values)
183    }
184
185    fn submit<'a>(
186        &'a self,
187        cx: &'a Cx,
188        signed: &'a SignedIn,
189        mut values: FormValues,
190    ) -> BoxFuture<'a, topcoat::Result<Outcome>> {
191        Box::pin(async move {
192            let any: &dyn Any = &*signed.user;
193            let user = any
194                .downcast_ref::<E::User>()
195                .ok_or_else(|| topcoat::Error::from(forbidden()))?;
196            let schema = E::Input::schema();
197            let mut stored = FormValues::new();
198            self.fill(cx, user).write(&mut stored);
199            input::keep_disabled(&schema, &mut values, &stored);
200            schema.keep_unedited(&mut values, &stored, &crate::time_zone(cx));
201            let input = match input::parse::<E::Input>(cx, &values, &stored, "profile").await? {
202                Ok(input) => input,
203                Err(errors) => return Ok(Outcome::Refused { values, errors }),
204            };
205            let mut db = crate::db::db(cx)?;
206            let mut tx = db.transaction().await.map_err(crate::error::unavailable)?;
207            let errors = self
208                .validate(cx, user, &input, &mut tx)
209                .await
210                .map_err(write_failure)?;
211            input::placed(&schema, &errors, "the profile editor", "profile")?;
212            if !errors.is_empty() {
213                return Ok(Outcome::Refused { values, errors });
214            }
215            let update = self
216                .save(cx, user, input, &mut tx)
217                .await
218                .map_err(write_failure)?;
219            if update == ProfileUpdate::Credentials {
220                // The new credential and the end of the sessions the old one opened commit
221                // together, or neither does. The token only reaches the browser with the response.
222                let session = super::session::start(cx).await?;
223                replace_sessions(cx, &mut tx, signed, TypeId::of::<E::User>(), &session).await?;
224                let kind = super::hook::AuthEventKind::CredentialsChanged;
225                super::hook::run_own(cx, signed, kind, &mut tx).await?;
226            }
227            tx.commit().await.map_err(crate::error::unavailable)?;
228            let email_pending =
229                try_context::<Requested>(cx).is_some_and(|requested| requested.send(cx));
230            Ok(Outcome::Saved { email_pending })
231        })
232    }
233}
234
235/// A failed profile write: a database failure becomes the opaque outage, logged; an editor's own
236/// error keeps its mapping.
237fn write_failure(error: topcoat::Error) -> topcoat::Error {
238    crate::error::driver_failure(error, crate::error::DATABASE_UNAVAILABLE)
239}
240
241/// The profile form [`PasswordAuth`](super::PasswordAuth) edits a
242/// [`PasswordAccount`](super::PasswordAccount) through, and a custom [`ProfileEditor`] can take as
243/// its input: a name, an email address, an optional new password typed twice, and the current
244/// password.
245#[derive(Clone, PartialEq, Eq)]
246pub struct Profile {
247    /// The display name, posted as `name`.
248    pub name: String,
249    /// The email address the account signs in with, posted as `email`.
250    pub email: String,
251    /// The new password, posted as `password`; `None` when left blank, which keeps the current
252    /// one.
253    pub password: Option<String>,
254    /// The new password typed again, posted as `password_confirmation`.
255    pub password_confirmation: String,
256    /// The password the account signs in with today, posted as `current_password`; `None` when
257    /// left blank.
258    pub current_password: Option<String>,
259}
260
261impl Profile {
262    /// The refusals [`new_password_errors`] makes of a new password; none when the profile keeps
263    /// the current one.
264    pub fn password_errors(&self) -> FieldErrors {
265        match &self.password {
266            Some(password) => new_password_errors(password, &self.password_confirmation),
267            None => FieldErrors::new(),
268        }
269    }
270}
271
272/// Redacts the passwords, so a profile logged with `?` writes none to the log.
273impl std::fmt::Debug for Profile {
274    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
275        f.debug_struct("Profile")
276            .field("name", &self.name)
277            .field("email", &self.email)
278            .field("password", &self.password.as_ref().map(|_| "<redacted>"))
279            .field("password_confirmation", &"<redacted>")
280            .field(
281                "current_password",
282                &self.current_password.as_ref().map(|_| "<redacted>"),
283            )
284            .finish()
285    }
286}
287
288/// A field of [`Profile`], the key a refusal of a change posts under: a
289/// [`PasswordAccount`](super::PasswordAccount) names one through [`ProfileKeys`],
290/// `errors.add(|f| f.email, ..)`.
291#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
292pub enum ProfileField {
293    /// The display name, posted as `name`.
294    Name,
295    /// The email address, posted as `email`.
296    Email,
297    /// The new password, posted as `password`.
298    Password,
299    /// The new password typed again, posted as `password_confirmation`.
300    PasswordConfirmation,
301    /// The current password, posted as `current_password`.
302    CurrentPassword,
303}
304
305/// The fields of [`Profile`], each named like the field, which a refusal picks one from.
306#[derive(Debug, Clone, Copy)]
307pub struct ProfileKeys {
308    /// The display name.
309    pub name: ProfileField,
310    /// The email address.
311    pub email: ProfileField,
312    /// The new password.
313    pub password: ProfileField,
314    /// The new password typed again.
315    pub password_confirmation: ProfileField,
316    /// The current password.
317    pub current_password: ProfileField,
318}
319
320impl crate::FormFields for Profile {
321    type Field = ProfileField;
322    type Keys = ProfileKeys;
323
324    fn keys() -> ProfileKeys {
325        ProfileKeys {
326            name: ProfileField::Name,
327            email: ProfileField::Email,
328            password: ProfileField::Password,
329            password_confirmation: ProfileField::PasswordConfirmation,
330            current_password: ProfileField::CurrentPassword,
331        }
332    }
333}
334
335impl FormInput for Profile {
336    fn key(field: ProfileField) -> &'static str {
337        match field {
338            ProfileField::Name => NAME_FIELD,
339            ProfileField::Email => EMAIL_FIELD,
340            ProfileField::Password => PASSWORD_FIELD,
341            ProfileField::PasswordConfirmation => CONFIRMATION_FIELD,
342            ProfileField::CurrentPassword => CURRENT_PASSWORD_FIELD,
343        }
344    }
345
346    fn schema() -> Schema {
347        let required = crate::form::required_input;
348        Schema::new((
349            required(
350                Field::text_input::<String>(NAME_FIELD).label(crate::text!("tablo-auth-name")),
351            ),
352            required(
353                Field::text_input::<String>(EMAIL_FIELD)
354                    .email()
355                    .label(crate::text!("tablo-auth-email")),
356            ),
357            Field::text_input::<String>(PASSWORD_FIELD)
358                .password()
359                .label(crate::text!("tablo-auth-new-password"))
360                .help(crate::text!("tablo-profile-password-help")),
361            Field::text_input::<String>(CONFIRMATION_FIELD)
362                .password()
363                .label(crate::text!("tablo-auth-confirm-new-password")),
364            Field::text_input::<String>(CURRENT_PASSWORD_FIELD)
365                .current_password()
366                .label(crate::text!("tablo-auth-current-password"))
367                .help(crate::text!("tablo-profile-current-password-help")),
368        ))
369    }
370
371    fn parse(_cx: &Cx, values: &FormValues) -> Result<Self, Vec<FieldError>> {
372        let mut errors = Vec::new();
373        let mut keep = |read: Result<String, FieldError>| read.map_err(|error| errors.push(error));
374        let name = keep(parse_scalar::<String>(NAME_FIELD, values, None));
375        let email = keep(parse_scalar::<String>(EMAIL_FIELD, values, None));
376        // A blank password is no password; any other keeps every character it was typed with.
377        let mut optional = |key| {
378            keep(parse_password(key, values, Some(String::new())))
379                .ok()
380                .filter(|password| !password.trim().is_empty())
381        };
382        let password = optional(PASSWORD_FIELD);
383        let password_confirmation = optional(CONFIRMATION_FIELD).unwrap_or_default();
384        let current_password = optional(CURRENT_PASSWORD_FIELD);
385        match (name, email) {
386            (Ok(name), Ok(email)) if errors.is_empty() => Ok(Self {
387                name,
388                email,
389                password,
390                password_confirmation,
391                current_password,
392            }),
393            _ => Err(errors),
394        }
395    }
396
397    fn write(&self, out: &mut FormValues) {
398        out.insert(NAME_FIELD.to_string(), self.name.clone());
399        out.insert(EMAIL_FIELD.to_string(), self.email.clone());
400    }
401}
402
403/// The key [`Profile`]'s display name posts under.
404const NAME_FIELD: &str = "name";
405/// The key [`Profile`]'s email address posts under.
406const EMAIL_FIELD: &str = "email";
407/// The key [`Profile`]'s new password posts under.
408const PASSWORD_FIELD: &str = "password";
409/// The key [`Profile`]'s repeated new password posts under.
410const CONFIRMATION_FIELD: &str = "password_confirmation";
411/// The key [`Profile`]'s current password posts under.
412pub(crate) const CURRENT_PASSWORD_FIELD: &str = "current_password";
413
414/// The keys a profile POST carries besides its input, which no input field may post.
415pub(crate) const RESERVED_KEYS: [&str; 1] = [crate::csrf::FIELD_NAME];
416
417/// Where the panel's profile page lives: `{prefix}/profile`, or in the area that holds it.
418pub(crate) fn profile_url(cx: &Cx) -> String {
419    current_realm(cx).map_or_else(
420        || format!("{}/profile", panel_prefix(cx)),
421        |realm| realm.pages.profile.clone(),
422    )
423}
424
425/// Whether the request's panel installs a [`ProfileEditor`] and nobody acts as another user,
426/// whose profile the gate keeps from them.
427pub(crate) fn offered(cx: &Cx) -> bool {
428    !super::impersonation::acting(cx)
429        && current_realm(cx).is_some_and(|panel| panel.auth.profile_editor().is_some())
430}
431
432/// The signed-in user and the panel's editor, or the answer to a request without them.
433fn editing(cx: &Cx) -> topcoat::Result<(&SignedIn, &dyn DynProfileEditor)> {
434    let signed = signed(cx).ok_or_else(|| unauthenticated_error(cx))?;
435    let editor = signed.realm.auth.profile_editor().ok_or_else(not_found)?;
436    Ok((signed, editor))
437}
438
439/// `GET {prefix}/profile` — the profile form, filled from the signed-in account.
440pub(super) fn profile_page(cx: &Cx, _body: Body) -> BoxView<'_> {
441    async_page(async move {
442        let (signed, editor) = editing(cx)?;
443        let values = editor
444            .values(cx, signed.user.as_ref())
445            .ok_or_else(forbidden)?;
446        crate::csrf::ensure_token(cx);
447        render(cx, editor, &values, &FieldErrors::new()).await
448    })
449}
450
451/// `POST {prefix}/profile` — save the profile, then land back on the page.
452pub(super) fn profile_post(cx: &Cx, body: Body) -> BoxView<'_> {
453    async_page(async move {
454        let (signed, editor) = editing(cx)?;
455        let form = crate::auth::input::read_form(cx, body).await?;
456        crate::csrf::verify(cx, form.last(crate::csrf::FIELD_NAME))?;
457        let input_schema = editor.schema();
458        let values = input_schema.read_input(cx, &form.pairs, &RESERVED_KEYS)?;
459        // A stolen session must not try passwords against the current-password check at will.
460        // Counted per user alone, from any address: a lockout only holds back profile saves,
461        // never a sign-in.
462        let throttle = signed.realm.auth.throttle_profile();
463        if !throttle
464            .attempt(cx, "profile", &signed.user.user_id(), None)
465            .await?
466        {
467            tracing::warn!(
468                panel = %signed.realm.prefix,
469                client = ?client_ip(cx),
470                "profile save throttled"
471            );
472            return Err(too_many_requests(throttle.window_secs()).into());
473        }
474        // An email change the editor asks to confirm is mailed once the save commits.
475        let saving = cx.with(Requested::default());
476        let email_pending = match editor.submit(&saving, signed, values).await? {
477            Outcome::Refused { values, errors } => {
478                return render(cx, editor, &values, &errors).await;
479            }
480            Outcome::Saved { email_pending } => email_pending,
481        };
482        let saved = Notification::success(crate::t!(cx, "tablo-profile-saved"));
483        set_notification(
484            cx,
485            if email_pending {
486                saved.description(crate::t!(cx, "tablo-profile-email-pending"))
487            } else {
488                saved
489            },
490        );
491        Err(see_other(profile_url(cx)).into())
492    })
493}
494
495/// The profile page in the panel's shell: the editor's form with `values` and `errors`, saved to
496/// the page itself, cancelled to the panel's home.
497async fn render<'a>(
498    cx: &'a Cx,
499    editor: &dyn DynProfileEditor,
500    values: &FormValues,
501    errors: &FieldErrors,
502) -> topcoat::Result<BoxView<'a>> {
503    let schema = editor.schema();
504    let page = SettingsPage {
505        title: crate::t!(cx, "tablo-shell-profile"),
506        schema: &schema,
507        hidden: None,
508        values,
509        errors,
510    };
511    hosted(cx)?.settings_page(cx, page).await
512}
513
514/// The mistakes in a panel's [`Auth::profile`](super::Auth::profile): a profile without auth, an
515/// editor whose user is not the authenticator's, and a profile form field the page cannot serve.
516pub(super) fn declaration_errors(auth: &super::AuthConfig) -> Vec<crate::DeclarationErrorKind> {
517    use super::input::FieldFault;
518    use crate::{DeclarationErrorKind, declaration::ProfileFault};
519
520    let Some(editor) = auth.profile_editor.as_deref() else {
521        return Vec::new();
522    };
523    if auth.authenticator().is_none() {
524        return vec![DeclarationErrorKind::Profile(ProfileFault::AuthDisabled)];
525    }
526    let mut kinds = Vec::new();
527    let schema = editor.schema();
528    kinds.extend(schema.declaration_errors());
529    kinds.extend(schema.empty_choices());
530    kinds.extend(
531        input::field_faults(&schema, &RESERVED_KEYS).map(|(fault, name)| {
532            DeclarationErrorKind::Profile(match fault {
533                FieldFault::Reserved => ProfileFault::ReservedField(name),
534                FieldFault::File => ProfileFault::FileField(name),
535                FieldFault::Relationship => ProfileFault::RelationshipField(name),
536            })
537        }),
538    );
539    kinds
540}
541
542#[cfg(test)]
543mod tests;