1use std::{
6 sync::{Arc, Mutex},
7 time::Duration,
8};
9
10use topcoat::{
11 context::{Cx, try_context},
12 router::{
13 Body, RouteFuture,
14 error::see_other,
15 response::{IntoResponse, Response},
16 },
17 view::{ViewExt, attributes, view},
18};
19
20use super::{
21 PanelUser, SignedIn,
22 hook::{AuthEvent, AuthEventKind},
23 infrastructure_failure,
24 login::login_url,
25 mail::{
26 AuthLetter, AuthLetterKind, TOKEN_FIELD, after_response, private, send, token_from_query,
27 },
28 page::{AuthPage, render},
29 panel_root,
30 session::{Activity, credential_panels, end_credentials, resolve, start_once},
31 token::{self, AuthToken, CREDENTIALS, REVOCATION, TokenPurpose, run_serializable},
32 verification::VERIFICATION_LIFETIME,
33};
34use crate::{
35 auth::realm::{Realm, current_realm, hosted, panel_prefix},
36 flash::set_notification,
37 outcome::Notification,
38};
39
40const CANCEL_LIFETIME: Duration = Duration::from_hours(24 * 7);
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45#[must_use]
46pub enum EmailChange {
47 Pending,
50 Immediate,
52}
53
54pub async fn request_email_change(
104 cx: &Cx,
105 ex: &mut dyn toasty::Executor,
106 user: &dyn PanelUser,
107 email: &str,
108) -> topcoat::Result<EmailChange> {
109 if super::signed(cx).is_some_and(|signed| signed.impersonator.is_some()) {
111 return Err(topcoat::router::error::forbidden().into());
112 }
113 if !current_realm(cx).is_some_and(|panel| panel.auth.verification().is_some()) {
114 return Ok(EmailChange::Immediate);
115 }
116 let mail = current_realm(cx)
117 .and_then(|panel| panel.auth.auth_mail())
118 .ok_or_else(topcoat::router::error::not_found)?;
119 let user_id = user.user_id();
120 let confirm = token::issue(
121 cx,
122 &mut *ex,
123 TokenPurpose::EmailChange,
124 &user_id,
125 Some(email.to_string()),
126 VERIFICATION_LIFETIME,
127 )
128 .await?;
129 let brand = hosted(cx)?.brand_name(cx);
130 let mut letters = vec![mail.letter(
131 AuthLetterKind::EmailChange,
132 email,
133 crate::t!(cx, "tablo-email-change-mail-subject", brand = brand.clone()),
134 crate::t!(
135 cx,
136 "tablo-email-change-mail-body",
137 new = email,
138 brand = brand.clone(),
139 link = mail.link(&confirm_url(cx), &confirm)
140 ),
141 Some(VERIFICATION_LIFETIME),
142 )?];
143 if let Some(old) = user.email() {
145 let cancel = token::issue(
146 cx,
147 &mut *ex,
148 TokenPurpose::EmailChangeCancel,
149 &user_id,
150 Some(old.to_string()),
151 CANCEL_LIFETIME,
152 )
153 .await?;
154 letters.push(mail.letter(
155 AuthLetterKind::EmailChangeCancel,
156 old,
157 crate::t!(
158 cx,
159 "tablo-email-change-notice-subject",
160 brand = brand.clone()
161 ),
162 crate::t!(
163 cx,
164 "tablo-email-change-notice-body",
165 brand = brand,
166 new = email,
167 old = old,
168 link = mail.link(&cancel_url(cx), &cancel)
169 ),
170 Some(CANCEL_LIFETIME),
171 )?);
172 }
173 let mut pending = Vec::new();
174 for letter in letters {
175 pending.extend(mail.hand(cx, &mut *ex, letter).await?);
176 }
177 match try_context::<Requested>(cx) {
178 Some(requested) => requested.push(pending),
180 None => send_after_response(cx, pending),
181 }
182 Ok(EmailChange::Pending)
183}
184
185#[derive(Clone, Default)]
188pub(super) struct Requested(Arc<Mutex<Option<Vec<AuthLetter>>>>);
189
190impl Requested {
191 fn push(&self, letters: Vec<AuthLetter>) {
192 self.0
193 .lock()
194 .unwrap_or_else(|poison| poison.into_inner())
195 .get_or_insert_default()
196 .extend(letters);
197 }
198
199 pub(super) fn send(&self, cx: &Cx) -> bool {
202 let letters = self
203 .0
204 .lock()
205 .unwrap_or_else(|poison| poison.into_inner())
206 .take();
207 let any = letters.is_some();
208 send_after_response(cx, letters.unwrap_or_default());
209 any
210 }
211}
212
213fn send_after_response(cx: &Cx, letters: Vec<AuthLetter>) {
215 if letters.is_empty() {
216 return;
217 }
218 after_response(cx, "email change links", move |cx, _| async move {
219 for letter in letters {
220 send(&cx, letter).await?;
221 }
222 Ok(())
223 });
224}
225
226pub(crate) fn confirm_url(cx: &Cx) -> String {
228 format!("{}/email-change/confirm", panel_prefix(cx))
229}
230
231pub(crate) fn cancel_url(cx: &Cx) -> String {
233 format!("{}/email-change/cancel", panel_prefix(cx))
234}
235
236struct Opened {
239 row: AuthToken,
240 account: Arc<dyn PanelUser>,
241 signed: Option<SignedIn>,
242}
243
244async fn opened(
247 cx: &Cx,
248 panel: &Arc<Realm>,
249 purpose: TokenPurpose,
250 encoded: &str,
251) -> topcoat::Result<Option<Opened>> {
252 let Some(authenticator) = panel.auth.authenticator() else {
253 return Ok(None);
254 };
255 let mut db = crate::db::db(cx)?;
256 let Some(row) = token::live(cx, &mut db, purpose, encoded).await? else {
257 return Ok(None);
258 };
259 let account = authenticator
260 .find_by_id(cx, &row.user_id)
261 .await
262 .map_err(infrastructure_failure)?
263 .filter(|account| {
266 purpose == TokenPurpose::EmailChangeCancel || account.can_access_panel(&panel.id)
267 });
268 let Some(account) = account else {
269 return Ok(None);
270 };
271 let signed = resolve(cx, panel, authenticator, Activity::Counts)
273 .await?
274 .filter(|signed| signed.user.user_id() == row.user_id && signed.impersonator.is_none());
275 Ok(Some(Opened {
276 row,
277 account,
278 signed,
279 }))
280}
281
282async fn link_page(
285 cx: &Cx,
286 title: String,
287 description: String,
288 button: String,
289) -> topcoat::Result<Response> {
290 let csrf = crate::csrf::ensure_token(cx);
291 let action = topcoat::router::request::uri(cx).path().to_string();
292 let token = token_from_query(cx);
293 let form = view! {
294 <form method="post" action=(action) data-email-change="">
295 (crate::csrf::field(cx, &csrf))
296 <input type="hidden" name=(TOKEN_FIELD) value=(token)>
297 tablo_ui::button(
298 variant: tablo_ui::ButtonVariant::Primary,
299 attrs: attributes! { type="submit" class="w-full" },
300 (button)
301 )
302 </form>
303 }
304 .boxed();
305 let page = render(
306 cx,
307 AuthPage {
308 title,
309 description,
310 status: None,
311 form,
312 switch: None,
313 note: None,
314 },
315 )
316 .await?;
317 private(page.single().await?.into_response(cx)?)
318}
319
320async fn link(
323 cx: &Cx,
324 purpose: TokenPurpose,
325 encoded: &str,
326) -> topcoat::Result<Result<(Arc<Realm>, Opened), Response>> {
327 let panel = current_realm(cx).ok_or_else(topcoat::router::error::not_found)?;
328 if panel.auth.verification().is_none() {
329 return Err(topcoat::router::error::not_found().into());
330 }
331 match opened(cx, panel, purpose, encoded).await? {
332 Some(opened) => Ok(Ok((Arc::clone(panel), opened))),
333 None => Ok(Err(super::verification::invalid_link(cx).await?)),
334 }
335}
336
337async fn posted_token(cx: &Cx, body: Body) -> topcoat::Result<String> {
339 let form = crate::auth::input::read_form(cx, body).await?;
340 crate::csrf::verify(cx, form.last(crate::csrf::FIELD_NAME))?;
341 Ok(form.last(TOKEN_FIELD).unwrap_or_default().to_string())
342}
343
344pub(super) fn confirm_page(cx: &Cx, _body: Body) -> RouteFuture<'_> {
346 Box::pin(async move {
347 let (_, opened) = match link(cx, TokenPurpose::EmailChange, &token_from_query(cx)).await? {
348 Ok(link) => link,
349 Err(invalid) => return Ok(invalid),
350 };
351 let email = opened.row.email.unwrap_or_default();
352 link_page(
353 cx,
354 crate::t!(cx, "tablo-email-change-confirm-title"),
355 crate::t!(cx, "tablo-email-change-confirm-description", email = email),
356 crate::t!(cx, "tablo-confirm"),
357 )
358 .await
359 })
360}
361
362pub(super) fn confirm_post(cx: &Cx, body: Body) -> RouteFuture<'_> {
366 Box::pin(async move {
367 let encoded = posted_token(cx, body).await?;
368 let (panel, Opened { row, signed, .. }) =
369 match link(cx, TokenPurpose::EmailChange, &encoded).await? {
370 Ok(link) => link,
371 Err(invalid) => return Ok(invalid),
372 };
373 let verifier = panel
374 .auth
375 .verification()
376 .ok_or_else(topcoat::router::error::not_found)?
377 .verifier();
378 let email = row.email.clone().unwrap_or_default();
379 let user_type = verifier.user_type();
380 let mut started = None;
381 let landing = run_serializable!(cx, |tx| async {
382 if token::live(cx, tx, TokenPurpose::EmailChange, &encoded)
384 .await?
385 .is_none()
386 {
387 return Ok(None);
388 }
389 token::spend(tx, &row).await?;
390 verifier
391 .store_verified_email(cx, &row.user_id, &email, tx)
392 .await
393 .map_err(infrastructure_failure)?;
394 let kind = AuthEventKind::EmailChanged;
395 let event = match &signed {
396 Some(signed) => {
397 AuthEvent::own(kind, &panel.id, signed.acting_tenant(cx), &*signed.user)
398 }
399 None => AuthEvent::unsigned(kind, &panel.id, Some(&row.user_id)),
400 };
401 super::hook::run(cx, &panel.auth_hooks, &event, tx).await?;
402 Ok(Some(match &signed {
403 Some(signed) => {
404 let session = start_once(cx, &mut started).await?;
405 super::session::replace_sessions(cx, tx, signed, user_type, &session).await?;
406 panel_root(cx)
407 }
408 None => {
409 let panels = credential_panels(cx, user_type, &panel);
410 end_credentials(tx, &row.user_id, &panels, CREDENTIALS).await?;
411 login_url(cx)
412 }
413 }))
414 })?;
415 let Some(landing) = landing else {
416 return super::verification::invalid_link(cx).await;
417 };
418 set_notification(
419 cx,
420 Notification::success(crate::t!(cx, "tablo-email-change-done")).description(crate::t!(
421 cx,
422 "tablo-email-change-done-description",
423 email = email
424 )),
425 );
426 private(see_other(landing).into_response(cx)?)
427 })
428}
429
430pub(super) fn cancel_page(cx: &Cx, _body: Body) -> RouteFuture<'_> {
432 Box::pin(async move {
433 let (_, opened) =
434 match link(cx, TokenPurpose::EmailChangeCancel, &token_from_query(cx)).await? {
435 Ok(link) => link,
436 Err(invalid) => return Ok(invalid),
437 };
438 let email = opened.row.email.unwrap_or_default();
439 link_page(
440 cx,
441 crate::t!(cx, "tablo-email-change-keep-title"),
442 crate::t!(cx, "tablo-email-change-keep-description", email = email),
443 crate::t!(cx, "tablo-email-change-keep"),
444 )
445 .await
446 })
447}
448
449pub(super) fn cancel_post(cx: &Cx, body: Body) -> RouteFuture<'_> {
453 Box::pin(async move {
454 let encoded = posted_token(cx, body).await?;
455 let (panel, Opened { row, account, .. }) =
456 match link(cx, TokenPurpose::EmailChangeCancel, &encoded).await? {
457 Ok(link) => link,
458 Err(invalid) => return Ok(invalid),
459 };
460 let verifier = panel
461 .auth
462 .verification()
463 .ok_or_else(topcoat::router::error::not_found)?
464 .verifier();
465 let old = row.email.clone().unwrap_or_default();
466 let cancelled = run_serializable!(cx, |tx| async {
467 if token::live(cx, tx, TokenPurpose::EmailChangeCancel, &encoded)
468 .await?
469 .is_none()
470 {
471 return Ok(false);
472 }
473 token::spend(tx, &row).await?;
474 if account.email() != Some(old.as_str()) {
475 verifier
477 .store_verified_email(cx, &row.user_id, &old, tx)
478 .await
479 .map_err(infrastructure_failure)?;
480 }
481 let panels = credential_panels(cx, verifier.user_type(), &panel);
482 end_credentials(tx, &row.user_id, &panels, REVOCATION).await?;
483 Ok(true)
484 })?;
485 if !cancelled {
486 return super::verification::invalid_link(cx).await;
487 }
488 super::session::stop(cx).await?;
490 set_notification(
491 cx,
492 Notification::success(crate::t!(cx, "tablo-email-change-kept")).description(crate::t!(
493 cx,
494 "tablo-email-change-kept-description",
495 email = old
496 )),
497 );
498 private(see_other(login_url(cx)).into_response(cx)?)
499 })
500}