tablo_core/auth/panel_user.rs
1//! [`PanelUser`] and the [`Authenticator`] that loads one.
2
3use std::{any::Any, future::Future};
4
5use topcoat::context::Cx;
6
7use crate::tenancy::{Membership, TenantId};
8
9/// A signed-in user, as the panel knows it (ADR-0013).
10///
11/// Implement it for the app's own user type and return that type from an
12/// [`Authenticator`]; the shipped [`AdminUser`](super::AdminUser) implements it too. App code
13/// reads the user back with its own type through [`user`](super::user).
14///
15/// ```rust
16/// # struct Staff {
17/// # id: uuid::Uuid,
18/// # name: String,
19/// # active: bool,
20/// # memberships: Vec<tablo_core::Membership>,
21/// # }
22/// # use tablo_core::{Membership, PanelUser};
23/// impl PanelUser for Staff {
24/// fn user_id(&self) -> String {
25/// self.id.to_string()
26/// }
27/// fn display_name(&self) -> &str {
28/// &self.name
29/// }
30/// fn can_access_panel(&self, _panel: &tablo_core::PanelId) -> bool {
31/// self.active
32/// }
33/// fn tenants(&self) -> &[Membership] {
34/// &self.memberships
35/// }
36/// }
37/// ```
38pub trait PanelUser: Any + Send + Sync {
39 /// The stable key the session stores and
40 /// [`Authenticator::find_by_id`] receives. Any string fits.
41 fn user_id(&self) -> String;
42
43 /// The name the user menu shows.
44 fn display_name(&self) -> &str;
45
46 /// The muted line under the name in the user menu, such as an email or a role. Defaults to
47 /// none.
48 fn subtitle(&self) -> Option<&str> {
49 None
50 }
51
52 /// The address the account stores, which mail meant for the account goes to: a reset link,
53 /// a verification link, a sign-in code. Defaults to none: the account gets no mail.
54 fn email(&self) -> Option<&str> {
55 None
56 }
57
58 /// Whether the user may enter `panel`. A user who may not answers 403, indistinguishable from
59 /// bad credentials at login. Every user type answers it: a sign-up on one panel writes an
60 /// account every panel over the same user type looks up.
61 ///
62 /// `panel` is a [`PanelId`](crate::PanelId): it equals the prefix the panel was declared with
63 /// in any spelling, so `"admin"` and `"/admin"` both name `Panel::new("admin")`, and it offers
64 /// no string to match a part of. One user type can serve several panels, each with its own
65 /// rule. Name each panel and refuse the rest, so that a panel added or renamed later admits
66 /// nobody until it has a rule:
67 ///
68 /// ```rust
69 /// # struct Staff { active: bool, is_staff: bool }
70 /// # impl Staff {
71 /// fn can_access_panel(&self, panel: &tablo_core::PanelId) -> bool {
72 /// if panel == "admin" {
73 /// self.active && self.is_staff
74 /// } else if panel == "portal" {
75 /// self.active
76 /// } else {
77 /// false
78 /// }
79 /// }
80 /// # }
81 /// # let staff = Staff { active: true, is_staff: false };
82 /// # assert!(!staff.can_access_panel(&tablo_core::PanelId::new("/admin")));
83 /// # assert!(staff.can_access_panel(&tablo_core::PanelId::new("/portal/")));
84 /// # assert!(!staff.can_access_panel(&tablo_core::PanelId::new("/portal-old")));
85 /// ```
86 ///
87 /// Every check of a panel asks it with that panel's id: the gate on each request, the
88 /// login, the sign-up, a mailed link and a two-factor challenge. The link that cancels an
89 /// email change does not ask: it only restores the old address and ends sessions.
90 fn can_access_panel(&self, panel: &crate::PanelId) -> bool;
91
92 /// The tenants the user may act for, in the order the tenant switcher
93 /// lists them. A session acts for the [`default_tenant`](Self::default_tenant)
94 /// until the user selects another. Defaults to none: the user has no tenant.
95 ///
96 /// A panel acts for tenants when it offers a tenant registration or settings page, or mounts
97 /// a tenant-scoped resource. Any other acts for no tenant:
98 /// [`tenant_id`](crate::tenant_id) answers `None` there, and the panel offers no tenant
99 /// menu and no route to switch.
100 ///
101 /// With two or more, on a panel that acts for tenants, a tenant menu sits atop the sidebar. It
102 /// posts to `{prefix}/tenant`, which stores the choice on the session and returns to the
103 /// panel's home page. A tenant the user is not a member of answers 403, and a stored choice
104 /// applies only while the membership lasts. One browser acts for one tenant at a time, in
105 /// every tab.
106 fn tenants(&self) -> &[Membership] {
107 &[]
108 }
109
110 /// The tenant a session acts for until the user selects another, while it is one of
111 /// [`tenants`](Self::tenants), such as one the user picks on their profile page and the app
112 /// stores. Defaults to none: the first of `tenants`.
113 fn default_tenant(&self) -> Option<TenantId> {
114 None
115 }
116
117 /// The time zone the user reads and enters wall-clock times in: a timestamp's control, its
118 /// [`DateColumn`](crate::DateColumn) day and its [`DateFilter`](crate::DateFilter) days.
119 /// Defaults to none: the panel's [`time_zone`](crate::Panel::time_zone).
120 fn time_zone(&self) -> Option<jiff::tz::TimeZone> {
121 None
122 }
123
124 /// The locale the user reads the panel and their mails in, such as `fr`. Defaults to none: the
125 /// browser's best match among the panel's [`locales`](crate::Panel::locales), else its
126 /// default. A locale matches the closest the panel offers, as `fr-CA` reads `fr`; one with no
127 /// match counts as none. A locale the user picks from the shell's language menu outranks this
128 /// one for their pages, while their mails still read this one, unless the authenticator
129 /// stores the pick through [`Authenticator::store_locale`] for this method to read.
130 ///
131 /// A user who stores their locale as text parses it:
132 ///
133 /// ```rust,ignore
134 /// fn locale(&self) -> Option<Locale> {
135 /// self.locale.as_deref()?.parse().ok()
136 /// }
137 /// ```
138 fn locale(&self) -> Option<topcoat::l10n::Locale> {
139 None
140 }
141}
142
143/// How a panel loads its users (ADR-0013).
144///
145/// [`PasswordAuth`](crate::PasswordAuth) implements it over a
146/// [`PasswordAccount`](crate::PasswordAccount): the shipped [`AdminUser`](super::AdminUser) by
147/// default, or the app's own model. An app whose users sign in some other way implements it and
148/// passes the value to [`Panel::auth`](crate::Panel::auth) via
149/// [`Auth::custom`](crate::Auth::custom). Sessions are the framework's, so an implementation only
150/// maps credentials to a user and a stored id back to one. An app that signs its users in itself
151/// implements [`ExternalAuth`](crate::ExternalAuth) instead.
152///
153/// Every *credential* failure must return `Ok(None)`, never a distinguishable
154/// error: the login response is one generic message for all of them. An
155/// infrastructure failure is not a credential verdict, so an implementation
156/// that cannot reach its store returns the driver's error instead — the login
157/// handler maps it to the opaque outage page, which keeps a database outage
158/// from rendering as a rejected password. An implementation's own error keeps
159/// its own mapping.
160pub trait Authenticator: Send + Sync + 'static {
161 /// The app's user type.
162 type User: PanelUser;
163
164 /// Verify `login`/`password`, returning the user on success.
165 ///
166 /// Implementations must run comparable work for unknown accounts so
167 /// timing does not leak account existence; [`verify_password`](super::verify_password) does,
168 /// given `None` for an unknown account.
169 fn verify(
170 &self,
171 cx: &Cx,
172 login: &str,
173 password: &str,
174 ) -> impl Future<Output = topcoat::Result<Option<Self::User>>> + Send;
175
176 /// Load the session's user by [`PanelUser::user_id`], with everything the request
177 /// reads from it — its [`tenants`](PanelUser::tenants) included.
178 ///
179 /// It runs on every request, which is what makes deactivation, revocation
180 /// and a removed membership take effect immediately; return `None` when
181 /// the user no longer authenticates.
182 fn find_by_id(
183 &self,
184 cx: &Cx,
185 id: &str,
186 ) -> impl Future<Output = topcoat::Result<Option<Self::User>>> + Send;
187
188 /// Whether `password` is `user`'s current password: what a page asks before a change a stolen
189 /// session must not make, such as turning two-factor sign-in on.
190 ///
191 /// It defaults to [`verify`](Self::verify) with the user's [`email`](PanelUser::email) as the
192 /// login, and answers `false` for a user without one: override it when users sign in with
193 /// something else.
194 fn confirm_password(
195 &self,
196 cx: &Cx,
197 user: &Self::User,
198 password: &str,
199 ) -> impl Future<Output = topcoat::Result<bool>> + Send {
200 async move {
201 let Some(login) = user.email() else {
202 return Ok(false);
203 };
204 let verified = self.verify(cx, login, password).await?;
205 Ok(verified.is_some_and(|found| found.user_id() == user.user_id()))
206 }
207 }
208
209 /// Stores `locale` as `user`'s after they pick it from the shell's language menu, so their
210 /// [`locale`](PanelUser::locale) reads it on the next request, in another browser, and in the
211 /// mail a job sends them. It runs only when the pick differs from that locale, and never
212 /// while someone [impersonates](crate::Auth::impersonation) the user.
213 ///
214 /// It defaults to storing nothing: the pick then lives in the browser's cookie alone. A
215 /// failure is logged, and the page still switches to the locale picked.
216 fn store_locale(
217 &self,
218 cx: &Cx,
219 user: &Self::User,
220 locale: &topcoat::l10n::Locale,
221 ) -> impl Future<Output = topcoat::Result<()>> + Send {
222 let _ = (cx, user, locale);
223 async { Ok(()) }
224 }
225
226 /// The [`user_id`](PanelUser::user_id) of the user whose sign-in details a panel's edit form
227 /// changed from `before` to `after`, two records of the resource's model, or `None` when the
228 /// model is not this authenticator's or the edit left the details alone.
229 ///
230 /// The panel then ends that user's sessions, pending sign-ins, reset links and pending email
231 /// change in the edit's transaction, on every panel whose authenticator loads its type.
232 /// [`PasswordAuth`](super::PasswordAuth) answers for its account's email and password hash; it
233 /// defaults to `None`.
234 fn changed_credentials(&self, before: &dyn Any, after: &dyn Any) -> Option<String> {
235 let _ = (before, after);
236 None
237 }
238}