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_request_context},
11    router::{
12        Body,
13        error::{forbidden, not_found, see_other, too_many_requests},
14        request::client_ip,
15    },
16    session,
17    view::BoxView,
18};
19
20use super::{
21    PanelUser, SignedIn, email_change::Requested, input, registration::new_password_errors,
22    session::replace_sessions, signed, unauthenticated_error,
23};
24use crate::{
25    BoxFuture,
26    auth::realm::{SettingsPage, current_realm, hosted, panel_prefix},
27    flash::set_notification,
28    form::{FieldError, FieldErrors, FormInput, FormValues, parse_password, parse_scalar},
29    outcome::Notification,
30    schema::{Field, Schema},
31    topcoat_compat::async_page,
32};
33
34/// How a panel lets the signed-in user edit their own account on its profile page, installed
35/// with [`Auth::profile`](super::Auth::profile).
36///
37/// It mirrors a [`Registrar`](super::Registrar): [`Input`](Self::Input) is the form the page
38/// shows, [`fill`](Self::fill) seeds it from the account, [`validate`](Self::validate) refuses a
39/// submission field by field, and [`save`](Self::save) writes it. `validate` and `save` run in one
40/// transaction the framework opens.
41///
42/// The shipped [`PasswordAuth`](super::PasswordAuth) edits an [`AdminUser`](super::AdminUser)
43/// through a [`Profile`]; an app with its own user table implements it beside its
44/// [`Authenticator`](super::Authenticator), for the same user type:
45///
46/// ```rust
47/// # use tablo_core::{PanelUser, ProfileEditor, ProfileUpdate};
48/// # use topcoat::context::Cx;
49/// # #[derive(Debug, Clone, toasty::Model)]
50/// # struct Staff {
51/// #     #[key] #[auto] id: uuid::Uuid,
52/// #     name: String,
53/// # }
54/// # impl PanelUser for Staff {
55/// #     fn user_id(&self) -> String { self.id.to_string() }
56/// #     fn display_name(&self) -> &str { &self.name }
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            // A control the page renders disabled posts nothing the user may change: it keeps
200            // what `fill` wrote, whatever a crafted POST carries.
201            for key in schema.disabled_keys(true) {
202                match stored.get(key) {
203                    Some(value) => values.insert(key, value.clone()),
204                    None => values.remove(key),
205                };
206            }
207            schema.keep_unedited(&mut values, &stored, &crate::time_zone(cx));
208            let input = match input::parse::<E::Input>(cx, &values, &stored, "profile").await? {
209                Ok(input) => input,
210                Err(errors) => return Ok(Outcome::Refused { values, errors }),
211            };
212            let mut db = crate::db::db(cx)?;
213            let mut tx = db.transaction().await.map_err(crate::error::unavailable)?;
214            let errors = self
215                .validate(cx, user, &input, &mut tx)
216                .await
217                .map_err(write_failure)?;
218            input::placed(&schema, &errors, "the profile editor", "profile")?;
219            if !errors.is_empty() {
220                return Ok(Outcome::Refused { values, errors });
221            }
222            let update = self
223                .save(cx, user, input, &mut tx)
224                .await
225                .map_err(write_failure)?;
226            if update == ProfileUpdate::Credentials {
227                // The new credential and the end of the sessions the old one opened commit
228                // together, or neither does. The token only reaches the browser with the response.
229                let session = session::start(cx).await?;
230                replace_sessions(cx, &mut tx, signed, TypeId::of::<E::User>(), &session).await?;
231            }
232            tx.commit().await.map_err(crate::error::unavailable)?;
233            let email_pending =
234                try_request_context::<Requested>(cx).is_some_and(|requested| requested.mail(cx));
235            Ok(Outcome::Saved { email_pending })
236        })
237    }
238}
239
240/// A failed profile write: a database failure becomes the opaque outage, logged; an editor's own
241/// error keeps its mapping.
242fn write_failure(error: topcoat::Error) -> topcoat::Error {
243    crate::error::driver_failure(error, crate::error::DATABASE_UNAVAILABLE)
244}
245
246/// The profile form [`PasswordAuth`](super::PasswordAuth) edits an
247/// [`AdminUser`](super::AdminUser) through, and a custom [`ProfileEditor`] can take as its
248/// input: a name, an email address, an optional new password typed twice, and the current
249/// password.
250#[derive(Clone, PartialEq, Eq)]
251pub struct Profile {
252    /// The display name, posted as `name`.
253    pub name: String,
254    /// The email address the account signs in with, posted as `email`.
255    pub email: String,
256    /// The new password, posted as `password`; `None` when left blank, which keeps the current
257    /// one.
258    pub password: Option<String>,
259    /// The new password typed again, posted as `password_confirmation`.
260    pub password_confirmation: String,
261    /// The password the account signs in with today, posted as `current_password`; `None` when
262    /// left blank.
263    pub current_password: Option<String>,
264}
265
266impl Profile {
267    /// The refusals [`new_password_errors`] makes of a new password; none when the profile keeps
268    /// the current one.
269    pub fn password_errors(&self) -> FieldErrors {
270        match &self.password {
271            Some(password) => new_password_errors(password, &self.password_confirmation),
272            None => FieldErrors::new(),
273        }
274    }
275}
276
277/// Redacts the passwords, so a profile logged with `?` writes none to the log.
278impl std::fmt::Debug for Profile {
279    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
280        f.debug_struct("Profile")
281            .field("name", &self.name)
282            .field("email", &self.email)
283            .field("password", &self.password.as_ref().map(|_| "<redacted>"))
284            .field("password_confirmation", &"<redacted>")
285            .field(
286                "current_password",
287                &self.current_password.as_ref().map(|_| "<redacted>"),
288            )
289            .finish()
290    }
291}
292
293impl FormInput for Profile {
294    fn schema() -> Schema {
295        let required = crate::form::required_input;
296        Schema::new((
297            required(Field::text_input::<String>("name").label(crate::text!("tablo-auth-name"))),
298            required(
299                Field::text_input::<String>("email")
300                    .email()
301                    .label(crate::text!("tablo-auth-email")),
302            ),
303            Field::text_input::<String>(PASSWORD_FIELD)
304                .password()
305                .label(crate::text!("tablo-auth-new-password"))
306                .help(crate::text!("tablo-profile-password-help")),
307            Field::text_input::<String>(CONFIRMATION_FIELD)
308                .password()
309                .label(crate::text!("tablo-auth-confirm-new-password")),
310            Field::text_input::<String>(CURRENT_PASSWORD_FIELD)
311                .current_password()
312                .label(crate::text!("tablo-auth-current-password"))
313                .help(crate::text!("tablo-profile-current-password-help")),
314        ))
315    }
316
317    fn parse(_cx: &Cx, values: &FormValues) -> Result<Self, Vec<FieldError>> {
318        let mut errors = Vec::new();
319        let mut keep = |read: Result<String, FieldError>| read.map_err(|error| errors.push(error));
320        let name = keep(parse_scalar::<String>("name", values, None));
321        let email = keep(parse_scalar::<String>("email", values, None));
322        // A blank password is no password; any other keeps every character it was typed with.
323        let mut optional = |key| {
324            keep(parse_password(key, values, Some(String::new())))
325                .ok()
326                .filter(|password| !password.trim().is_empty())
327        };
328        let password = optional(PASSWORD_FIELD);
329        let password_confirmation = optional(CONFIRMATION_FIELD).unwrap_or_default();
330        let current_password = optional(CURRENT_PASSWORD_FIELD);
331        match (name, email) {
332            (Ok(name), Ok(email)) if errors.is_empty() => Ok(Self {
333                name,
334                email,
335                password,
336                password_confirmation,
337                current_password,
338            }),
339            _ => Err(errors),
340        }
341    }
342
343    fn write(&self, out: &mut FormValues) {
344        out.insert("name".to_string(), self.name.clone());
345        out.insert("email".to_string(), self.email.clone());
346    }
347}
348
349/// The key [`Profile`]'s new password posts under.
350const PASSWORD_FIELD: &str = "password";
351/// The key [`Profile`]'s repeated new password posts under.
352const CONFIRMATION_FIELD: &str = "password_confirmation";
353/// The key [`Profile`]'s current password posts under.
354pub(crate) const CURRENT_PASSWORD_FIELD: &str = "current_password";
355
356/// The keys a profile POST carries besides its input, which no input field may post.
357pub(crate) const RESERVED_KEYS: [&str; 1] = [crate::csrf::FIELD_NAME];
358
359/// Where the panel's profile page lives: `{prefix}/profile`.
360pub(crate) fn profile_url(cx: &Cx) -> String {
361    format!("{}/profile", panel_prefix(cx))
362}
363
364/// Whether the request's panel installs a [`ProfileEditor`].
365pub(crate) fn offered(cx: &Cx) -> bool {
366    current_realm(cx).is_some_and(|panel| panel.auth.profile_editor().is_some())
367}
368
369/// The signed-in user and the panel's editor, or the answer to a request without them.
370fn editing(cx: &Cx) -> topcoat::Result<(&SignedIn, &dyn DynProfileEditor)> {
371    let signed = signed(cx).ok_or_else(|| unauthenticated_error(cx))?;
372    let editor = signed.realm.auth.profile_editor().ok_or_else(not_found)?;
373    Ok((signed, editor))
374}
375
376/// `GET {prefix}/profile` — the profile form, filled from the signed-in account.
377pub(super) fn profile_page(cx: &Cx, _body: Body) -> BoxView<'_> {
378    async_page(async move {
379        let (signed, editor) = editing(cx)?;
380        let values = editor
381            .values(cx, signed.user.as_ref())
382            .ok_or_else(forbidden)?;
383        crate::csrf::ensure_token(cx);
384        render(cx, editor, &values, &FieldErrors::new()).await
385    })
386}
387
388/// `POST {prefix}/profile` — save the profile, then land back on the page.
389pub(super) fn profile_post(cx: &Cx, body: Body) -> BoxView<'_> {
390    async_page(async move {
391        let (signed, editor) = editing(cx)?;
392        let form = crate::auth::input::read_form(cx, body).await?;
393        crate::csrf::verify(cx, form.last(crate::csrf::FIELD_NAME))?;
394        let input_schema = editor.schema();
395        let values = input_schema.read_input(cx, &form.pairs, &RESERVED_KEYS)?;
396        // A stolen session must not try passwords against the current-password check at will.
397        // Counted per user alone, from any address: a lockout only holds back profile saves,
398        // never a sign-in.
399        let throttle = signed.realm.auth.throttle_profile();
400        if !throttle.attempt(&signed.user.user_id(), None) {
401            tracing::warn!(
402                panel = %signed.realm.prefix,
403                client = ?client_ip(cx),
404                "profile save throttled"
405            );
406            return Err(too_many_requests(throttle.window_secs()).into());
407        }
408        // An email change the editor asks to confirm is mailed once the save commits.
409        let saving = cx.with(Requested::default());
410        let email_pending = match editor.submit(&saving, signed, values).await? {
411            Outcome::Refused { values, errors } => {
412                return render(cx, editor, &values, &errors).await;
413            }
414            Outcome::Saved { email_pending } => email_pending,
415        };
416        let saved = Notification::success(crate::t!(cx, "tablo-profile-saved"));
417        set_notification(
418            cx,
419            if email_pending {
420                saved.description(crate::t!(cx, "tablo-profile-email-pending"))
421            } else {
422                saved
423            },
424        );
425        Err(see_other(profile_url(cx)).into())
426    })
427}
428
429/// The profile page in the panel's shell: the editor's form with `values` and `errors`, saved to
430/// the page itself, cancelled to the panel's home.
431async fn render<'a>(
432    cx: &'a Cx,
433    editor: &dyn DynProfileEditor,
434    values: &FormValues,
435    errors: &FieldErrors,
436) -> topcoat::Result<BoxView<'a>> {
437    let schema = editor.schema();
438    let page = SettingsPage {
439        title: crate::t!(cx, "tablo-shell-profile"),
440        schema: &schema,
441        hidden: None,
442        values,
443        errors,
444    };
445    hosted(cx)?.settings_page(cx, page).await
446}
447
448/// The mistakes in a panel's [`Auth::profile`](super::Auth::profile): a profile without auth, an
449/// editor whose user is not the authenticator's, and a profile form field the page cannot serve.
450pub(super) fn declaration_errors(auth: &super::AuthConfig) -> Vec<crate::DeclarationErrorKind> {
451    use super::input::FieldFault;
452    use crate::{DeclarationErrorKind, declaration::ProfileFault};
453
454    let Some(editor) = auth.profile_editor.as_deref() else {
455        return Vec::new();
456    };
457    if auth.authenticator().is_none() {
458        return vec![DeclarationErrorKind::Profile(ProfileFault::AuthDisabled)];
459    }
460    let mut kinds = Vec::new();
461    let schema = editor.schema();
462    kinds.extend(schema.declaration_errors());
463    kinds.extend(schema.empty_choices());
464    kinds.extend(
465        input::field_faults(&schema, &RESERVED_KEYS).map(|(fault, name)| {
466            DeclarationErrorKind::Profile(match fault {
467                FieldFault::Reserved => ProfileFault::ReservedField(name),
468                FieldFault::File => ProfileFault::FileField(name),
469                FieldFault::Relationship => ProfileFault::RelationshipField(name),
470            })
471        }),
472    );
473    kinds
474}
475
476#[cfg(test)]
477mod tests;