1use 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
33pub 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 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 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
235fn write_failure(error: topcoat::Error) -> topcoat::Error {
238 crate::error::driver_failure(error, crate::error::DATABASE_UNAVAILABLE)
239}
240
241#[derive(Clone, PartialEq, Eq)]
246pub struct Profile {
247 pub name: String,
249 pub email: String,
251 pub password: Option<String>,
254 pub password_confirmation: String,
256 pub current_password: Option<String>,
259}
260
261impl Profile {
262 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
272impl 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
292pub enum ProfileField {
293 Name,
295 Email,
297 Password,
299 PasswordConfirmation,
301 CurrentPassword,
303}
304
305#[derive(Debug, Clone, Copy)]
307pub struct ProfileKeys {
308 pub name: ProfileField,
310 pub email: ProfileField,
312 pub password: ProfileField,
314 pub password_confirmation: ProfileField,
316 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 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
403const NAME_FIELD: &str = "name";
405const EMAIL_FIELD: &str = "email";
407const PASSWORD_FIELD: &str = "password";
409const CONFIRMATION_FIELD: &str = "password_confirmation";
411pub(crate) const CURRENT_PASSWORD_FIELD: &str = "current_password";
413
414pub(crate) const RESERVED_KEYS: [&str; 1] = [crate::csrf::FIELD_NAME];
416
417pub(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
425pub(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
432fn 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
439pub(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
451pub(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 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 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
495async 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
514pub(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;