Skip to main content

tablo_core/auth/
account.rs

1//! [`PasswordAccount`], the user model the stock password sign-in reads, and [`PasswordAuth`],
2//! the sign-in, profile, password reset and email verification over one.
3
4use std::{any::Any, future::Future, marker::PhantomData};
5
6use derive_where::derive_where;
7use jiff::Timestamp;
8use topcoat::{context::Cx, l10n::Locale};
9
10use super::{
11    AdminUser, Authenticator, EmailChange, PanelUser, Profile, ProfileEditor, ProfileField,
12    ProfileUpdate, hash_password, infrastructure_failure, profile::CURRENT_PASSWORD_FIELD,
13    request_email_change, verify_password,
14};
15use crate::{
16    EmailVerifier, FieldErrors, FormInput, Lens, PasswordResetter,
17    toasty_compat::{
18        RowUpdate,
19        pk::{canonical_key, pk_eq_expr, pk_filter, pk_text},
20    },
21};
22
23/// A user model [`PasswordAuth`] signs in by email and password, and whose own account it edits,
24/// resets and verifies.
25///
26/// The app names four fields of its model through [`lens!`](crate::lens!), and says what the
27/// panel signs in: the model itself, or a value loaded beside it, such as the user with their
28/// tenants. [`AdminUser`] is one.
29///
30/// ```rust
31/// # use jiff::Timestamp;
32/// # use topcoat::context::Cx;
33/// use tablo_core::{Lens, Membership, PanelUser, PasswordAccount, lens};
34///
35/// #[derive(Debug, Clone, toasty::Model)]
36/// struct User {
37///     #[key]
38///     #[auto]
39///     id: uuid::Uuid,
40///     name: String,
41///     #[unique]
42///     email: String,
43///     password: String,
44///     email_verified_at: Option<Timestamp>,
45/// }
46///
47/// /// The user and the tenants they belong to.
48/// struct SignedIn {
49///     user: User,
50///     tenants: Vec<Membership>,
51/// }
52///
53/// impl PanelUser for SignedIn {
54///     fn user_id(&self) -> String {
55///         self.user.id.to_string()
56///     }
57///     fn display_name(&self) -> &str {
58///         &self.user.name
59///     }
60///     fn email(&self) -> Option<&str> {
61///         Some(&self.user.email)
62///     }
63///     fn can_access_panel(&self, _panel: &tablo_core::PanelId) -> bool {
64///         true
65///     }
66///     fn tenants(&self) -> &[Membership] {
67///         &self.tenants
68///     }
69/// }
70///
71/// impl PasswordAccount for User {
72///     type User = SignedIn;
73///
74///     fn name() -> Lens<Self, String> {
75///         lens!(User.name)
76///     }
77///     fn email() -> Lens<Self, String> {
78///         lens!(User.email)
79///     }
80///     fn password_hash() -> Lens<Self, String> {
81///         lens!(User.password)
82///     }
83///     fn email_verified_at() -> Lens<Self, Option<Timestamp>> {
84///         lens!(User.email_verified_at)
85///     }
86///     fn account(user: &SignedIn) -> &User {
87///         &user.user
88///     }
89///     async fn sign_in(
90///         self,
91///         _cx: &Cx,
92///         _ex: &mut dyn toasty::Executor,
93///     ) -> topcoat::Result<Option<SignedIn>> {
94///         // Load the user's memberships through `_ex` here.
95///         Ok(Some(SignedIn {
96///             user: self,
97///             tenants: Vec::new(),
98///         }))
99///     }
100/// }
101/// ```
102///
103/// [`PasswordAuth`] stores an email trimmed and lowercased, as
104/// [`normalize_email`](super::normalize_email) spells it, and looks it up the same way, so a
105/// resource or a sign-up that writes the email stores it so too. The model's primary key is one
106/// field, and the `User`'s [`PanelUser::user_id`] spells it as its `Display` does, such as
107/// `self.id.to_string()`: a sign-in whose id spells another key is refused as a declaration
108/// error.
109///
110/// A panel's edit form over the model that changes an account's email or password hash ends its
111/// sessions, pending sign-ins, reset links and pending email change on every panel that signs in
112/// `Self::User`, as it does an [`AdminUser`]'s; a custom action calls
113/// [`revoke_sessions_for_user`](super::revoke_sessions_for_user) itself.
114pub trait PasswordAccount:
115    toasty::schema::Model<
116        UpdateQuery: From<toasty::stmt::Query<toasty::stmt::List<Self>>>
117                         + toasty::stmt::IntoStatement<Returning = ()>,
118    > + toasty::stmt::IntoExpr<Self>
119    + Send
120    + Sync
121    + 'static
122{
123    /// What the panel signs in: `Self`, or a value holding it.
124    type User: PanelUser;
125
126    /// The display name, which the profile page edits.
127    fn name() -> Lens<Self, String>;
128
129    /// The address the account signs in with, unique across the table.
130    fn email() -> Lens<Self, String>;
131
132    /// The password's Argon2id hash in PHC string format, as
133    /// [`hash_password`](super::hash_password) writes it.
134    fn password_hash() -> Lens<Self, String>;
135
136    /// When the account proved it reads its email; `None` until it does, and again after the
137    /// email changes. Every email change writes it; only a panel with
138    /// [`Auth::email_verification`](crate::Auth::email_verification) reads it.
139    fn email_verified_at() -> Lens<Self, Option<Timestamp>>;
140
141    /// The account `user` signs in as.
142    fn account(user: &Self::User) -> &Self;
143
144    /// The account as the panel signs it in, loaded through `ex`, or `None` when it no longer
145    /// signs in, such as a deactivated account: its login fails as a wrong password does, its
146    /// sessions end at their next request, and it gets no reset link.
147    ///
148    /// It runs on every request of a signed-in session, so a removed membership or a deactivation
149    /// takes effect at once. It reads through `ex`, the connection the caller already holds.
150    fn sign_in(
151        self,
152        cx: &Cx,
153        ex: &mut dyn toasty::Executor,
154    ) -> impl Future<Output = topcoat::Result<Option<Self::User>>> + Send;
155
156    /// Refuses a profile change the app does not allow `user`, such as a new email on an account
157    /// whose sign-in details are locked. Defaults to none. It runs before the current password is
158    /// checked, and the page renders each error under its field's control. `profile.email` is as
159    /// typed: compare it through [`normalize_email`](super::normalize_email), as the stored email
160    /// is spelled.
161    fn profile_errors(user: &Self::User, profile: &Profile) -> FieldErrors<Profile> {
162        let _ = (user, profile);
163        FieldErrors::new()
164    }
165
166    /// Stores `locale` as `user`'s, as [`Authenticator::store_locale`] describes. Defaults to
167    /// storing nothing.
168    fn store_locale(
169        cx: &Cx,
170        user: &Self::User,
171        locale: &Locale,
172    ) -> impl Future<Output = topcoat::Result<()>> + Send {
173        let _ = (cx, user, locale);
174        async { Ok(()) }
175    }
176}
177
178/// The stock sign-in by email and password, over a [`PasswordAccount`]: the authenticator, and
179/// the [`ProfileEditor`], [`PasswordResetter`] and [`EmailVerifier`] for its users.
180///
181/// `PasswordAuth` reads the shipped [`AdminUser`]; `PasswordAuth::<User>::default()` reads
182/// the app's own `User` model.
183///
184/// ```rust
185/// use tablo_core::{Auth, PasswordAuth};
186///
187/// let auth = Auth::custom(PasswordAuth::new()).profile(PasswordAuth::new());
188/// # let _ = auth;
189/// ```
190///
191/// An unknown email costs the same work as a wrong password, and every failure shows the same
192/// message. It looks an email up trimmed and lowercased, so `Ada@Example.com` and
193/// `ada@example.com` are one account. A row stored with capitals cannot sign in or reset its
194/// password: list the accounts that differ only in case with `SELECT LOWER(TRIM(email)) FROM
195/// users GROUP BY 1 HAVING COUNT(*) > 1`, merge or delete them, then run `UPDATE users SET email
196/// = LOWER(TRIM(email))`. SQLite's `LOWER` folds ASCII letters only, so lowercase any other
197/// capital by hand.
198///
199/// As the profile editor it edits the name, the email and the password through a [`Profile`].
200/// Changing the email or the password asks for the current password, and refuses a new password
201/// [`new_password_errors`](super::new_password_errors) refuses and, once the current password
202/// verifies, an email another account holds. A changed password is a
203/// [`ProfileUpdate::Credentials`]. A new email goes through [`request_email_change`]: on a panel
204/// with [`Auth::email_verification`](crate::Auth::email_verification) it waits for its link,
205/// elsewhere it is stored at once, as a credential change.
206#[derive_where(Debug, Clone, Copy, Default)]
207pub struct PasswordAuth<A = AdminUser> {
208    #[derive_where(skip)]
209    account: PhantomData<fn() -> A>,
210}
211
212impl PasswordAuth {
213    /// The stock sign-in over the shipped [`AdminUser`].
214    #[must_use]
215    pub const fn new() -> Self {
216        Self {
217            account: PhantomData,
218        }
219    }
220}
221
222impl<A: PasswordAccount> Authenticator for PasswordAuth<A> {
223    type User = A::User;
224
225    async fn verify(
226        &self,
227        cx: &Cx,
228        login: &str,
229        password: &str,
230    ) -> topcoat::Result<Option<A::User>> {
231        let mut db = crate::db::db(cx)?;
232        let account = by_email::<A>(&mut db, login).await?;
233        let hash = account
234            .as_ref()
235            .map(|account| A::password_hash().read(account).clone());
236        if !verify_password(password, hash.as_deref()).await {
237            return Ok(None);
238        }
239        match account {
240            Some(account) => signed_in(account, cx, &mut db).await,
241            None => Ok(None),
242        }
243    }
244
245    async fn find_by_id(&self, cx: &Cx, id: &str) -> topcoat::Result<Option<A::User>> {
246        let Some(filter) = pk_eq_expr::<A>(id) else {
247            return Ok(None);
248        };
249        let mut db = crate::db::db(cx)?;
250        let account = toasty::stmt::Query::<toasty::stmt::List<A>>::all()
251            .filter(filter)
252            .first()
253            .exec(&mut db)
254            .await
255            .map_err(infrastructure_failure)?;
256        match account {
257            Some(account) => signed_in(account, cx, &mut db).await,
258            None => Ok(None),
259        }
260    }
261
262    /// Checks `password` against the account's own hash, whatever [`PanelUser::email`] answers.
263    async fn confirm_password(
264        &self,
265        _cx: &Cx,
266        user: &A::User,
267        password: &str,
268    ) -> topcoat::Result<bool> {
269        let hash = A::password_hash().read(A::account(user));
270        Ok(verify_password(password, Some(hash)).await)
271    }
272
273    async fn store_locale(&self, cx: &Cx, user: &A::User, locale: &Locale) -> topcoat::Result<()> {
274        A::store_locale(cx, user, locale).await
275    }
276
277    /// The account's key when an edit changed its email or its password hash.
278    fn changed_credentials(&self, before: &dyn Any, after: &dyn Any) -> Option<String> {
279        let (before, after) = (before.downcast_ref::<A>()?, after.downcast_ref::<A>()?);
280        let changed = A::email().read(before) != A::email().read(after)
281            || A::password_hash().read(before) != A::password_hash().read(after);
282        changed.then(|| pk_text(before))
283    }
284}
285
286impl<A: PasswordAccount> ProfileEditor for PasswordAuth<A> {
287    type Input = Profile;
288    type User = A::User;
289
290    fn fill(&self, _cx: &Cx, user: &A::User) -> Profile {
291        let account = A::account(user);
292        Profile {
293            name: A::name().read(account).clone(),
294            email: A::email().read(account).clone(),
295            password: None,
296            password_confirmation: String::new(),
297            current_password: None,
298        }
299    }
300
301    async fn validate(
302        &self,
303        _cx: &Cx,
304        user: &A::User,
305        profile: &Profile,
306        ex: &mut dyn toasty::Executor,
307    ) -> topcoat::Result<FieldErrors> {
308        let account = A::account(user);
309        let mut errors = A::profile_errors(user, profile).keyed(Profile::key);
310        errors.extend(profile.password_errors());
311        let email = normalize_email(&profile.email);
312        let new_email = email != *A::email().read(account);
313        if new_email || profile.password.is_some() {
314            let hash = A::password_hash().read(account);
315            match &profile.current_password {
316                None => errors.add_field(
317                    CURRENT_PASSWORD_FIELD,
318                    crate::text!("tablo-profile-current-password-needed"),
319                ),
320                Some(current) if !verify_password(current, Some(hash)).await => {
321                    errors.add_field(
322                        CURRENT_PASSWORD_FIELD,
323                        crate::text!("tablo-profile-current-password-wrong"),
324                    );
325                }
326                Some(_) => {}
327            }
328        }
329        let email_key = Profile::key(ProfileField::Email);
330        // Only the account's owner learns whether another account holds an email: a stolen
331        // session without the password must not probe addresses.
332        if new_email
333            && !errors.contains_key(CURRENT_PASSWORD_FIELD)
334            && !errors.contains_key(email_key)
335            && by_email::<A>(ex, &email)
336                .await?
337                .is_some_and(|other| pk_text(&other) != pk_text(account))
338        {
339            errors.add_field(email_key, email_taken());
340        }
341        Ok(errors)
342    }
343
344    async fn save(
345        &self,
346        cx: &Cx,
347        user: &A::User,
348        profile: Profile,
349        ex: &mut dyn toasty::Executor,
350    ) -> topcoat::Result<ProfileUpdate> {
351        let account = A::account(user);
352        let email = normalize_email(&profile.email);
353        let stored = email != *A::email().read(account)
354            && request_email_change(cx, &mut *ex, user, &email).await? == EmailChange::Immediate;
355        let mut update = RowUpdate::new::<A>(pk_filter(account));
356        update.set(A::name().path(), profile.name);
357        if stored {
358            update.set(A::email().path(), email);
359            update.set(A::email_verified_at().path(), None);
360        }
361        if let Some(password) = &profile.password {
362            update.set(A::password_hash().path(), hash_password(password).await?);
363        }
364        update.exec(ex).await?;
365        Ok(if stored || profile.password.is_some() {
366            ProfileUpdate::Credentials
367        } else {
368            ProfileUpdate::Details
369        })
370    }
371}
372
373impl<A: PasswordAccount> PasswordResetter for PasswordAuth<A> {
374    type User = A::User;
375
376    async fn find_by_email(&self, cx: &Cx, email: &str) -> topcoat::Result<Option<A::User>> {
377        let mut db = crate::db::db(cx)?;
378        match by_email::<A>(&mut db, email).await? {
379            Some(account) => signed_in(account, cx, &mut db).await,
380            None => Ok(None),
381        }
382    }
383
384    async fn reset_password(
385        &self,
386        _cx: &Cx,
387        user_id: &str,
388        password: &str,
389        ex: &mut dyn toasty::Executor,
390    ) -> topcoat::Result<()> {
391        let mut update = RowUpdate::new::<A>(by_user_id::<A>(user_id)?);
392        update.set(A::password_hash().path(), hash_password(password).await?);
393        update.exec(ex).await?;
394        Ok(())
395    }
396}
397
398impl<A: PasswordAccount> EmailVerifier for PasswordAuth<A> {
399    type User = A::User;
400
401    fn is_verified(&self, user: &A::User) -> bool {
402        A::email_verified_at().read(A::account(user)).is_some()
403    }
404
405    async fn store_verified_email(
406        &self,
407        _cx: &Cx,
408        user_id: &str,
409        email: &str,
410        ex: &mut dyn toasty::Executor,
411    ) -> topcoat::Result<()> {
412        let mut update = RowUpdate::new::<A>(by_user_id::<A>(user_id)?);
413        update.set(A::email().path(), normalize_email(email));
414        update.set(A::email_verified_at().path(), Some(Timestamp::now()));
415        update.exec(ex).await?;
416        Ok(())
417    }
418}
419
420/// The account whose email, as [`normalize_email`] spells it, is `email`.
421async fn by_email<A: PasswordAccount>(
422    ex: &mut dyn toasty::Executor,
423    email: &str,
424) -> topcoat::Result<Option<A>> {
425    toasty::stmt::Query::<toasty::stmt::List<A>>::all()
426        .filter(A::email().path().clone().eq(normalize_email(email)))
427        .first()
428        .exec(ex)
429        .await
430        .map_err(infrastructure_failure)
431}
432
433/// The filter selecting the account `user_id` names; not found when it spells no key.
434fn by_user_id<A: PasswordAccount>(user_id: &str) -> topcoat::Result<toasty::stmt::Expr<bool>> {
435    pk_eq_expr::<A>(user_id).ok_or_else(|| topcoat::router::error::not_found().into())
436}
437
438/// `account` as the panel signs it in, refusing a user whose id spells another key than the
439/// account's, or a key no later request can parse: the session would store an id no later request
440/// finds.
441async fn signed_in<A: PasswordAccount>(
442    account: A,
443    cx: &Cx,
444    ex: &mut dyn toasty::Executor,
445) -> topcoat::Result<Option<A::User>> {
446    let key = pk_text(&account);
447    let user = account.sign_in(cx, ex).await?;
448    if let Some(user) = &user
449        && canonical_key::<A>(&user.user_id()).as_deref() != Some(key.as_str())
450    {
451        return Err(crate::error::declaration(format!(
452            "`PanelUser::user_id` answers '{}' for the account whose key is '{key}': a \
453             `PasswordAccount` has a single primitive key, and its user spells it as its \
454             `Display` does",
455            user.user_id()
456        )));
457    }
458    Ok(user)
459}
460
461/// `email` as a [`PasswordAccount`] stores it: trimmed and lowercased.
462///
463/// ```rust
464/// assert_eq!(
465///     tablo_core::auth::normalize_email(" Ada@Example.COM "),
466///     "ada@example.com"
467/// );
468/// ```
469#[must_use]
470pub fn normalize_email(email: &str) -> String {
471    email.trim().to_lowercase()
472}
473
474/// The refusal of an email another account holds.
475pub(super) fn email_taken() -> crate::Text {
476    crate::text!(
477        "tablo-field-taken",
478        label = crate::text!("tablo-auth-email")
479    )
480}