1mod pages;
6
7use std::{any::TypeId, future::Future, marker::PhantomData, time::Duration};
8
9use topcoat::{
10 context::Cx,
11 router::{Body, RouteFuture, error::see_other, response::IntoResponse},
12};
13
14use self::pages::{ForgotAlert, forgot_response, invalid_link, reset_response};
15use super::{
16 LoginThrottle, PanelUser,
17 hook::{AuthEvent, AuthEventKind},
18 infrastructure_failure,
19 login::login_url,
20 mail::{AuthLetterKind, TOKEN_FIELD, after_response, token_from_query},
21 registration::new_password_errors,
22 session::{credential_panels, end_credentials},
23 token::{self, REVOCATION, TokenPurpose, run_serializable},
24};
25use crate::{
26 BoxFuture,
27 auth::realm::{Realm, current_realm, hosted, panel_prefix},
28 flash::set_notification,
29 form::FieldErrors,
30 outcome::Notification,
31};
32
33pub const RESET_LIFETIME: Duration = Duration::from_hours(1);
35
36pub trait PasswordResetter: Send + Sync + 'static {
92 type User: PanelUser;
95
96 fn find_by_email(
99 &self,
100 cx: &Cx,
101 email: &str,
102 ) -> impl Future<Output = topcoat::Result<Option<Self::User>>> + Send;
103
104 fn reset_password(
111 &self,
112 cx: &Cx,
113 user_id: &str,
114 password: &str,
115 ex: &mut dyn toasty::Executor,
116 ) -> impl Future<Output = topcoat::Result<()>> + Send;
117}
118
119pub(crate) struct Recipient {
121 address: String,
122 user_id: String,
123 locale: Option<topcoat::l10n::Locale>,
125}
126
127pub(crate) trait DynPasswordResetter: Send + Sync {
129 fn recipient<'a>(
132 &'a self,
133 cx: &'a Cx,
134 panel: &'a crate::PanelId,
135 email: &'a str,
136 ) -> BoxFuture<'a, topcoat::Result<Option<Recipient>>>;
137 fn reset_password<'a>(
138 &'a self,
139 cx: &'a Cx,
140 user_id: &'a str,
141 password: &'a str,
142 ex: &'a mut dyn toasty::Executor,
143 ) -> BoxFuture<'a, topcoat::Result<()>>;
144 fn user_type(&self) -> TypeId;
147}
148
149impl<R: PasswordResetter> DynPasswordResetter for R {
150 fn recipient<'a>(
151 &'a self,
152 cx: &'a Cx,
153 panel: &'a crate::PanelId,
154 email: &'a str,
155 ) -> BoxFuture<'a, topcoat::Result<Option<Recipient>>> {
156 Box::pin(async move {
157 let user = self.find_by_email(cx, email).await?;
158 let Some(user) = user.filter(|user| user.can_access_panel(panel)) else {
159 return Ok(None);
160 };
161 let Some(email) = user.email() else {
162 tracing::warn!(
164 user = std::any::type_name::<R::User>(),
165 "a password reset found an account whose `PanelUser::email` is `None`"
166 );
167 return Ok(None);
168 };
169 Ok(Some(Recipient {
170 address: email.to_string(),
171 user_id: user.user_id(),
172 locale: user.locale(),
173 }))
174 })
175 }
176
177 fn reset_password<'a>(
178 &'a self,
179 cx: &'a Cx,
180 user_id: &'a str,
181 password: &'a str,
182 ex: &'a mut dyn toasty::Executor,
183 ) -> BoxFuture<'a, topcoat::Result<()>> {
184 Box::pin(PasswordResetter::reset_password(
185 self, cx, user_id, password, ex,
186 ))
187 }
188
189 fn user_type(&self) -> TypeId {
190 TypeId::of::<R::User>()
191 }
192}
193
194pub struct PasswordReset<U> {
218 resetter: Box<dyn DynPasswordResetter>,
219 pub(in crate::auth) throttle: LoginThrottle,
220 user: PhantomData<fn() -> U>,
221}
222
223impl<U: PanelUser> PasswordReset<U> {
224 #[must_use]
226 pub fn new(resetter: impl PasswordResetter<User = U>) -> Self {
227 Self {
228 resetter: Box::new(resetter),
229 throttle: LoginThrottle::new(3, Duration::from_mins(15)),
230 user: PhantomData,
231 }
232 }
233
234 #[must_use]
238 pub fn throttle(mut self, throttle: LoginThrottle) -> Self {
239 self.throttle = throttle;
240 self
241 }
242
243 pub(crate) fn erase(self) -> PasswordReset<()> {
245 PasswordReset {
246 resetter: self.resetter,
247 throttle: self.throttle,
248 user: PhantomData,
249 }
250 }
251}
252
253impl PasswordReset<()> {
254 pub(crate) fn resetter(&self) -> &dyn DynPasswordResetter {
255 &*self.resetter
256 }
257}
258
259impl<U> std::fmt::Debug for PasswordReset<U> {
260 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
261 f.debug_struct("PasswordReset")
262 .field("throttle", &self.throttle)
263 .finish_non_exhaustive()
264 }
265}
266
267const EMAIL_FIELD: &str = "email";
269const PASSWORD_FIELD: &str = "password";
272const CONFIRMATION_FIELD: &str = "password_confirmation";
273
274pub(crate) fn forgot_url(cx: &Cx) -> String {
276 format!("{}/forgot-password", panel_prefix(cx))
277}
278
279pub(crate) fn reset_url(cx: &Cx) -> String {
281 format!("{}/reset-password", panel_prefix(cx))
282}
283
284pub(crate) fn offered(cx: &Cx) -> bool {
286 current_realm(cx).is_some_and(|panel| panel.auth.reset().is_some())
287}
288
289pub(super) fn forgot_page(cx: &Cx, _body: Body) -> RouteFuture<'_> {
291 Box::pin(async move { forgot_response(cx, "", &FieldErrors::new(), None).await })
292}
293
294pub(super) fn forgot_post(cx: &Cx, body: Body) -> RouteFuture<'_> {
297 Box::pin(async move {
298 let panel = current_realm(cx).ok_or_else(topcoat::router::error::not_found)?;
299 let reset = panel
300 .auth
301 .reset()
302 .ok_or_else(topcoat::router::error::not_found)?;
303 let form = crate::auth::input::read_form(cx, body).await?;
304 crate::csrf::verify(cx, form.last(crate::csrf::FIELD_NAME))?;
305 let email = form.last(EMAIL_FIELD).map_or("", str::trim);
306 if email.is_empty() {
307 let mut errors = FieldErrors::new();
308 errors.add_field(EMAIL_FIELD, crate::text!("tablo-reset-enter-email"));
309 return forgot_response(cx, email, &errors, None).await;
310 }
311 if !reset
312 .throttle
313 .attempt(cx, "password-reset", email, None)
314 .await?
315 {
316 tracing::warn!(panel = %panel.prefix, "password reset request throttled");
317 return forgot_response(cx, email, &FieldErrors::new(), Some(ForgotAlert::Throttled))
318 .await;
319 }
320 let recipient = match reset.resetter().recipient(cx, &panel.id, email).await {
321 Ok(recipient) => recipient,
322 Err(error) => {
323 let error = infrastructure_failure(error);
324 if crate::error::TabloError::is_infrastructure(&error) {
325 return forgot_response(
326 cx,
327 email,
328 &FieldErrors::new(),
329 Some(ForgotAlert::Unavailable),
330 )
331 .await;
332 }
333 return Err(error);
334 }
335 };
336 if let Some(recipient) = recipient {
337 after_response(cx, "password reset link", move |cx, panel| async move {
338 mail_link(&cx, &panel, &recipient).await
339 });
340 }
341 set_notification(
342 cx,
343 Notification::success(crate::t!(cx, "tablo-reset-sent"))
344 .description(crate::t!(cx, "tablo-reset-sent-description")),
345 );
346 see_other(login_url(cx)).into_response(cx)
347 })
348}
349
350async fn mail_link(cx: &Cx, panel: &Realm, recipient: &Recipient) -> topcoat::Result<()> {
353 let Recipient {
354 address,
355 user_id,
356 locale,
357 } = recipient;
358 let cx = &crate::i18n::addressed_to(cx, locale.as_ref());
359 let mail = panel
360 .auth
361 .auth_mail()
362 .ok_or_else(topcoat::router::error::not_found)?;
363 let brand = hosted(cx)?.brand_name(cx);
364 let minutes = RESET_LIFETIME.as_secs() / 60;
365 token::issue_mailed(
366 cx,
367 mail,
368 TokenPurpose::PasswordReset,
369 user_id,
370 None,
371 RESET_LIFETIME,
372 |token| {
373 mail.letter(
374 AuthLetterKind::PasswordReset,
375 address,
376 crate::t!(cx, "tablo-reset-mail-subject", brand = brand.clone()),
377 crate::t!(
378 cx,
379 "tablo-reset-mail-body",
380 brand = brand.clone(),
381 minutes = minutes,
382 link = mail.link(&reset_url(cx), token)
383 ),
384 Some(RESET_LIFETIME),
385 )
386 },
387 )
388 .await
389}
390
391async fn live_token(
393 cx: &Cx,
394 ex: &mut dyn toasty::Executor,
395 encoded: &str,
396) -> topcoat::Result<Option<token::AuthToken>> {
397 token::live(cx, ex, TokenPurpose::PasswordReset, encoded).await
398}
399
400pub(super) fn reset_page(cx: &Cx, _body: Body) -> RouteFuture<'_> {
403 Box::pin(async move {
404 let token = token_from_query(cx);
405 let mut db = crate::db::db(cx)?;
406 let live = live_token(cx, &mut db, &token).await?;
407 if live.is_none() {
408 return invalid_link(cx).await;
409 }
410 reset_response(cx, &token, &FieldErrors::new()).await
411 })
412}
413
414pub(super) fn reset_post(cx: &Cx, body: Body) -> RouteFuture<'_> {
417 Box::pin(async move {
418 let panel = current_realm(cx).ok_or_else(topcoat::router::error::not_found)?;
419 let reset = panel
420 .auth
421 .reset()
422 .ok_or_else(topcoat::router::error::not_found)?;
423 let form = crate::auth::input::read_form(cx, body).await?;
424 crate::csrf::verify(cx, form.last(crate::csrf::FIELD_NAME))?;
425 let token = form.last(TOKEN_FIELD).unwrap_or_default().to_string();
426 let password = form.last(PASSWORD_FIELD).unwrap_or_default();
427 let confirmation = form.last(CONFIRMATION_FIELD).unwrap_or_default();
428 let mut db = crate::db::db(cx)?;
429 let Some(row) = live_token(cx, &mut db, &token).await? else {
430 return invalid_link(cx).await;
431 };
432 if !may_enter(cx, panel, &row.user_id).await? {
435 return invalid_link(cx).await;
436 }
437 let errors = new_password_errors(password, confirmation);
438 if !errors.is_empty() {
439 return reset_response(cx, &token, &errors).await;
440 }
441 let reset_done = run_serializable!(cx, |tx| async {
442 if live_token(cx, tx, &token).await?.is_none() {
444 return Ok(false);
445 }
446 reset
447 .resetter()
448 .reset_password(cx, &row.user_id, password, tx)
449 .await
450 .map_err(infrastructure_failure)?;
451 let user_type = reset.resetter().user_type();
452 let panels = credential_panels(cx, user_type, panel);
453 end_credentials(tx, &row.user_id, &panels, REVOCATION).await?;
454 let event =
455 AuthEvent::unsigned(AuthEventKind::PasswordReset, &panel.id, Some(&row.user_id));
456 super::hook::run(cx, &panel.auth_hooks, &event, tx).await?;
457 Ok(true)
458 })?;
459 if !reset_done {
460 return invalid_link(cx).await;
461 }
462 set_notification(
463 cx,
464 Notification::success(crate::t!(cx, "tablo-reset-done"))
465 .description(crate::t!(cx, "tablo-reset-done-description")),
466 );
467 see_other(login_url(cx)).into_response(cx)
468 })
469}
470
471async fn may_enter(cx: &Cx, panel: &Realm, user_id: &str) -> topcoat::Result<bool> {
474 let Some(authenticator) = panel.auth.authenticator() else {
475 return Ok(false);
476 };
477 let user = authenticator
478 .find_by_id(cx, user_id)
479 .await
480 .map_err(infrastructure_failure)?;
481 Ok(user.is_some_and(|user| user.can_access_panel(&panel.id)))
482}
483
484pub(super) fn declaration_errors(auth: &super::AuthConfig) -> Vec<crate::DeclarationErrorKind> {
488 use crate::{DeclarationErrorKind, declaration::ResetFault};
489
490 if auth.reset.is_some() && auth.authenticator().is_none() {
491 return vec![DeclarationErrorKind::PasswordReset(
492 ResetFault::AuthDisabled,
493 )];
494 }
495 Vec::new()
496}