1use 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
34pub trait ProfileEditor: Send + Sync + 'static {
92 type Input: FormInput;
95
96 type User: PanelUser;
99
100 fn fill(&self, cx: &Cx, user: &Self::User) -> Self::Input;
104
105 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134#[non_exhaustive]
135pub enum ProfileUpdate {
136 Details,
138 Credentials,
142}
143
144pub(crate) enum Outcome {
146 Saved { email_pending: bool },
149 Refused {
151 values: FormValues,
152 errors: FieldErrors,
153 },
154}
155
156pub(crate) trait DynProfileEditor: Send + Sync {
158 fn schema(&self) -> Schema;
160 fn values(&self, cx: &Cx, user: &dyn PanelUser) -> Option<FormValues>;
162 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 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 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
240fn write_failure(error: topcoat::Error) -> topcoat::Error {
243 crate::error::driver_failure(error, crate::error::DATABASE_UNAVAILABLE)
244}
245
246#[derive(Clone, PartialEq, Eq)]
251pub struct Profile {
252 pub name: String,
254 pub email: String,
256 pub password: Option<String>,
259 pub password_confirmation: String,
261 pub current_password: Option<String>,
264}
265
266impl Profile {
267 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
277impl 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 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
349const PASSWORD_FIELD: &str = "password";
351const CONFIRMATION_FIELD: &str = "password_confirmation";
353pub(crate) const CURRENT_PASSWORD_FIELD: &str = "current_password";
355
356pub(crate) const RESERVED_KEYS: [&str; 1] = [crate::csrf::FIELD_NAME];
358
359pub(crate) fn profile_url(cx: &Cx) -> String {
361 format!("{}/profile", panel_prefix(cx))
362}
363
364pub(crate) fn offered(cx: &Cx) -> bool {
366 current_realm(cx).is_some_and(|panel| panel.auth.profile_editor().is_some())
367}
368
369fn 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
376pub(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
388pub(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 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 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
429async 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
448pub(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;