runique 3.0.2

A Django-inspired web framework for Rust with ORM, templates, and comprehensive security middleware
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
//! Built-in password reset flow: forgot + reset via email token.
use crate::utils::config::TraceResult;
use axum::{
    Router,
    extract::{Path, State},
    response::{IntoResponse, Redirect, Response},
};
use futures_util::future::BoxFuture;
use serde::Serialize;
use std::{sync::Arc, time::Duration};

use async_trait::async_trait;

use crate::auth::session::logout;
use crate::auth::user::BuiltinUserEntity;
use crate::auth::user_trait::RuniqueUser;
use crate::context::template::Request;
use crate::forms::{
    Forms,
    field::RuniqueForm,
    fields::{hidden::HiddenField, text::TextField},
};
use crate::utils::{
    aliases::{AppResult, StrMap},
    trad::{current_lang, t, tf},
};
use crate::{context_update, impl_form_access};

// ─── ForgotPasswordForm ───────────────────────────────────────────────────────

/// "Forgot password" form: a single required email field, used to trigger a
/// reset token email without revealing whether the address exists.
#[derive(Serialize, Debug, Clone)]
#[serde(transparent)]
pub struct ForgotPasswordForm {
    pub form: Forms,
}

impl RuniqueForm for ForgotPasswordForm {
    fn register_fields(form: &mut Forms) {
        form.field(
            &TextField::text("email")
                .label(&t("reset.email_label"))
                .required(),
        );
    }

    impl_form_access!();
    // `allow_get` defaults to `false` — the reset-token email send (a
    // state-changing action) never runs on a GET, no override needed.
}

// ─── PasswordResetForm ────────────────────────────────────────────────────────

/// Password reset form submitted from the emailed link: carries the token and
/// encrypted email as hidden fields, plus email/password/confirm for the user
/// to fill in. `clean()` checks the token decrypts to the submitted email and
/// enforces the password policy (10+ chars, upper/lower/digit/special).
#[derive(Serialize, Debug, Clone)]
#[serde(transparent)]
pub struct PasswordResetForm {
    pub form: Forms,
}

#[async_trait]
impl RuniqueForm for PasswordResetForm {
    fn register_fields(form: &mut Forms) {
        form.field(&HiddenField::new("token"));
        form.field(&HiddenField::new("encrypted_email"));
        form.field(
            &TextField::text("email")
                .label(&t("reset.email_label"))
                .required(),
        );
        form.field(
            &TextField::password("password")
                .label(&t("reset.new_password_label"))
                .required(),
        );
        form.field(
            &TextField::password("confirm")
                .label(&t("reset.confirm_label"))
                .required(),
        );
    }

    async fn clean(&mut self) -> Result<(), StrMap> {
        let token = self.cleaned_string("token").unwrap_or_default();
        let encrypted = self.cleaned_string("encrypted_email").unwrap_or_default();
        let email = self.cleaned_string("email").unwrap_or_default();
        let password = self.cleaned_string("password").unwrap_or_default();
        let confirm = self.cleaned_string("confirm").unwrap_or_default();
        let mut errors = StrMap::new();

        match crate::utils::reset_token::decrypt_email(&token, &encrypted) {
            Some(ref expected) if expected.to_lowercase() == email.trim().to_lowercase() => {}
            Some(_) => {
                errors.insert("email".to_string(), t("reset.email_mismatch").to_string());
            }
            None => {
                errors.insert("token".to_string(), t("reset.invalid_link").to_string());
            }
        }

        const SPECIAL: &str = "!@#$%^&*()_+-=[]{}|;':\",./<>?";
        if password.len() < 10 {
            errors.insert(
                "password".to_string(),
                tf("reset.password_min_length", &["10"]).clone(),
            );
        } else if !password.chars().any(|c| c.is_uppercase())
            || !password.chars().any(|c| c.is_lowercase())
            || !password.chars().any(|c| c.is_ascii_digit())
            || !password.chars().any(|c| SPECIAL.contains(c))
        {
            errors.insert("password".to_string(), t("reset.password_weak").to_string());
        }

        if password != confirm {
            errors.insert(
                "confirm".to_string(),
                t("reset.password_mismatch").to_string(),
            );
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    impl_form_access!();
    // `allow_get` defaults to `false` — the password update never runs on
    // a GET, no override needed.
}

// ─── Config ───────────────────────────────────────────────────────────────────

/// Hook run just before rendering, letting the host app inject template
/// context this generic flow has no way to know about (e.g. site branding
/// pulled from the app's own DB tables). Runs for both the forgot and reset
/// templates.
pub type ExtraContextFn = Arc<dyn for<'a> Fn(&'a mut Request) -> BoxFuture<'a, ()> + Send + Sync>;

/// Password reset flow configuration registered via the builder.
#[derive(Clone)]
pub struct PasswordResetConfig {
    /// Path of the "forgot password" GET/POST route. Default: `/forgot-password`.
    pub forgot_route: String,
    /// Path prefix of the reset route; the token and encrypted email are
    /// appended as path segments (`{reset_route}/{token}/{encrypted_email}`).
    /// Default: `/reset-password`.
    pub reset_route: String,
    /// Template rendered for the "forgot password" page.
    pub forgot_template: String,
    /// Template rendered for the reset-password page (both the form and the
    /// post-reset success state).
    pub reset_template: String,
    /// Template used to render the reset email body. When `None`, a plain
    /// HTML body is built from the `reset.email_body` translation string instead.
    pub email_template: Option<String>,
    /// Configured redirect target for a successful reset. Not currently read
    /// by the built-in reset flow, which re-renders `reset_template` in place
    /// with `reset_done = true` instead of redirecting.
    pub success_redirect: String,
    /// Maximum number of requests allowed per rate-limit window on the
    /// forgot/reset routes.
    pub max_requests: u64,
    /// Rate-limit window length, in seconds, paired with `max_requests`.
    pub retry_after: u64,
    /// Lifetime of a reset token before it expires. Default: 1 hour.
    pub token_ttl: Duration,
    /// Optional hook to inject extra template context before rendering.
    pub extra_context: Option<ExtraContextFn>,
}

impl Default for PasswordResetConfig {
    fn default() -> Self {
        Self {
            forgot_route: "/forgot-password".to_string(),
            reset_route: "/reset-password".to_string(),
            forgot_template: "auth/forgot_password.html".to_string(),
            reset_template: "auth/reset_password.html".to_string(),
            email_template: None,
            success_redirect: "/".to_string(),
            max_requests: 5,
            retry_after: 300,
            token_ttl: Duration::from_secs(3600),
            extra_context: None,
        }
    }
}

impl PasswordResetConfig {
    /// Creates a config with the default routes, templates and rate limits.
    pub fn new() -> Self {
        Self::default()
    }
    /// Overrides the "forgot password" route path (default: `/forgot-password`).
    #[must_use]
    pub fn forgot_route(mut self, route: &str) -> Self {
        self.forgot_route = route.to_string();
        self
    }
    /// Overrides the reset route path prefix (default: `/reset-password`).
    #[must_use]
    pub fn reset_route(mut self, route: &str) -> Self {
        self.reset_route = route.to_string();
        self
    }
    /// Overrides the template rendered for the "forgot password" page.
    #[must_use]
    pub fn forgot_template(mut self, template: &str) -> Self {
        self.forgot_template = template.to_string();
        self
    }
    /// Overrides the template rendered for the reset-password page.
    #[must_use]
    pub fn reset_template(mut self, template: &str) -> Self {
        self.reset_template = template.to_string();
        self
    }
    /// Sets the redirect target recorded for a successful reset. See the
    /// `success_redirect` field doc: the built-in flow does not currently
    /// read this value.
    #[must_use]
    pub fn success_redirect(mut self, redirect: &str) -> Self {
        self.success_redirect = redirect.to_string();
        self
    }
    /// Sets the template used to render the reset email body.
    #[must_use]
    pub fn email_template(mut self, template: &str) -> Self {
        self.email_template = Some(template.to_string());
        self
    }
    /// Sets how long a reset token stays valid (default: 1 hour).
    #[must_use]
    pub fn token_ttl(mut self, ttl: Duration) -> Self {
        self.token_ttl = ttl;
        self
    }
    /// Registers a hook run before each render, to inject app-specific
    /// template context (e.g. site branding) this generic flow can't
    /// provide on its own.
    #[must_use]
    pub fn extra_context(mut self, hook: ExtraContextFn) -> Self {
        self.extra_context = Some(hook);
        self
    }
}

/// The origin absolute links are built on: the public URL (`.with_public_url()`),
/// else — in debug only — the request's `Host`. Production refuses to boot without
/// it when the reset or the admin is on (`cross_validate`): the `Host` header is the
/// client's to choose, and a link pointing at someone else's site would hand them
/// the token. Apps reach it through [`Request::public_url`](crate::context::template::Request::public_url).
pub(crate) fn public_link_base(
    configured: Option<&str>,
    headers: &axum::http::HeaderMap,
    debug: bool,
) -> Option<String> {
    if let Some(base) = configured {
        return Some(base.trim_end_matches('/').to_string());
    }
    if !debug {
        return None;
    }
    let host = headers
        .get(axum::http::header::HOST)
        .and_then(|v| v.to_str().ok())?;
    tracing::warn!(
        "reset link built from the request's Host header: set .with_public_url() before production"
    );
    Some(format!("http://{host}"))
}

async fn apply_extra_context(request: &mut Request, hook: &Option<ExtraContextFn>) {
    if let Some(hook) = hook {
        hook(request).await;
    }
}

// ─── handle_forgot_password ───────────────────────────────────────────────────

/// Handles both the GET (render the form) and POST (issue a reset token)
/// sides of the "forgot password" page.
///
/// On POST, whether or not the email matches a user, the response is the same
/// success notice and redirect: the handler never reveals account existence
/// through its response, and the SMTP send is fired via `tokio::spawn` rather
/// than awaited, so an existing account can't be enumerated via response timing.
pub async fn handle_forgot_password(
    request: &mut Request,
    form: ForgotPasswordForm,
    config: &PasswordResetConfig,
) -> AppResult<Response> {
    let template = config.forgot_template.as_str();
    let forgot_route = config.forgot_route.as_str();
    let reset_path = config.reset_route.as_str();
    let email_template = config.email_template.as_deref();
    let token_ttl = config.token_ttl;
    request.context.insert("lang", &current_lang().code());

    let form = match crate::forms::ValidationForm::try_new(form, request).await {
        Ok(validated) => validated.into_form(),
        Err(form) => {
            apply_extra_context(request, &config.extra_context).await;
            context_update!(request => {
                "title"       => t("reset.forgot_title").as_ref(),
                "forgot_form" => &form,
            });
            return request.render(template);
        }
    };

    let email = form.cleaned_string("email").unwrap_or_default();
    let email = email.trim().to_lowercase();

    let db = request.engine.db.clone();

    let user = BuiltinUserEntity::find_by_email(&db, &email).await;
    // Activated once, inactive now: the staff blocked it. No link — only its
    // owner hears about it, through the mailbox; the page says the same thing
    // for every address.
    let blocked = user
        .as_ref()
        .is_some_and(|u| u.activated_at.is_some() && !u.is_active);
    if blocked {
        if let Some(user) = &user
            && crate::utils::mailer_configured()
        {
            let mail = crate::utils::Email::new()
                .to(email.clone())
                .subject(t("reset.blocked_subject").to_string())
                .html(tf("reset.blocked_body", &[user.username()]).to_string());
            let log_level = crate::utils::runique_log::get_log()
                .auth
                .as_ref()
                .and_then(|a| a.reset);
            // Fire-and-forget, like the other emails of this page.
            tokio::spawn(async move {
                mail.send().await.trace_or(
                    log_level,
                    tracing::Level::WARN,
                    "blocked account email send",
                );
            });
        }
    } else if let Some(user) = user
        && let Some(token) = crate::utils::reset_token::generate(&db, user.user_id(), token_ttl)
            .await
            .trace_or(
                crate::utils::runique_log::get_log()
                    .auth
                    .as_ref()
                    .and_then(|a| a.reset),
                tracing::Level::ERROR,
                "reset token generation failed",
            )
    {
        let encrypted_email = crate::utils::reset_token::encrypt_email(&token, &email);

        if let Some(level) = crate::utils::runique_log::get_log()
            .auth
            .as_ref()
            .and_then(|a| a.reset)
        {
            crate::runique_log!(level, %email, "reset token generated");
        }

        let Some(host) = request.public_url() else {
            // Production doesn't boot without a base URL: never reached there.
            request
                .notices
                .success(t("reset.check_inbox").to_string())
                .await;
            return Ok(Redirect::to(forgot_route).into_response());
        };

        let reset_url = format!(
            "{}/{}/{}/{}",
            host,
            reset_path.trim_matches('/'),
            token,
            encrypted_email
        );

        if crate::utils::mailer_configured() {
            let username = user.username().to_string();
            let subject = t("reset.email_subject").to_string();
            let mail = crate::utils::Email::new()
                .to(email.clone())
                .subject(&subject);
            // Fire-and-forget: do not await the SMTP send — a blocking await would leak
            // whether the email exists via response time (timing enumeration attack).
            if let Some(tpl) = email_template {
                use tera::Context as TeraCtx;
                let mut ctx = TeraCtx::new();
                ctx.insert("username", &username);
                ctx.insert("reset_url", &reset_url);
                if let Ok(msg) = mail.template(&request.engine.tera, tpl, ctx) {
                    let log_level = crate::utils::runique_log::get_log()
                        .auth
                        .as_ref()
                        .and_then(|a| a.reset);
                    tokio::spawn(async move {
                        if msg
                            .send()
                            .await
                            .trace_or(log_level, tracing::Level::WARN, "reset email send")
                            .is_some()
                            && let Some(level) = log_level
                        {
                            crate::runique_log!(level, "reset email sent");
                        }
                    });
                } else {
                    tracing::warn!(
                        template = %tpl,
                        "reset email template render failed — email not sent"
                    );
                }
            } else {
                let body = tf("reset.email_body", &[&username, &reset_url, &reset_url]).clone();
                let log_level = crate::utils::runique_log::get_log()
                    .auth
                    .as_ref()
                    .and_then(|a| a.reset);
                tokio::spawn(async move {
                    if mail
                        .html(body)
                        .send()
                        .await
                        .trace_or(log_level, tracing::Level::WARN, "reset email send")
                        .is_some()
                        && let Some(level) = log_level
                    {
                        crate::runique_log!(level, "reset email sent");
                    }
                });
            }
        }
    }

    // Security: do not reveal if the email exists or not
    request
        .notices
        .success(t("reset.check_inbox").to_string())
        .await;
    Ok(Redirect::to(forgot_route).into_response())
}

// ─── handle_password_reset ────────────────────────────────────────────────────

/// Handles the reset-password page reached from the emailed link: verifies
/// the token, logs out any existing session, then renders the form (GET) or
/// consumes the token and updates the password (POST).
///
/// The token is single-use (`consume`) and resolves to a server-side
/// `user_id`; the password update is applied by that id, not by the email
/// taken from the URL, and the URL email is only cross-checked against the
/// account's real email as a UX sanity check — the URL alone cannot be used
/// to reset an arbitrary account's password.
pub async fn handle_password_reset(
    request: &mut Request,
    form: PasswordResetForm,
    token: String,
    encrypted_email: String,
    config: &PasswordResetConfig,
) -> AppResult<Response> {
    let template = config.reset_template.as_str();
    request.context.insert("lang", &current_lang().code());
    logout(&request.session, None).await.trace(
        crate::utils::runique_log::get_log()
            .session
            .as_ref()
            .and_then(|s| s.store),
        "logout before password reset",
    );

    let Some(email) = crate::utils::reset_token::decrypt_email(&token, &encrypted_email) else {
        request
            .notices
            .error(t("reset.invalid_or_expired").to_string())
            .await;
        return Ok(Redirect::to("/").into_response());
    };

    let db = request.engine.db.clone();

    if !crate::utils::reset_token::peek(&db, &token).await {
        if let Some(level) = crate::utils::runique_log::get_log()
            .auth
            .as_ref()
            .and_then(|a| a.reset)
        {
            crate::runique_log!(level, %email, "reset token invalid or expired");
        }
        request
            .notices
            .error(t("reset.invalid_or_expired").to_string())
            .await;
        return Ok(Redirect::to("/").into_response());
    }

    let mut form = match crate::forms::ValidationForm::try_new(form, request).await {
        Ok(validated) => validated.into_form(),
        Err(mut form) => {
            if request.method.is_safe() {
                form.get_form_mut().add_value("token", &token);
                form.get_form_mut()
                    .add_value("encrypted_email", &encrypted_email);
            }
            apply_extra_context(request, &config.extra_context).await;
            context_update!(request => {
                "title"           => t("reset.reset_title").as_ref(),
                "reset_form"      => &form,
                "token"           => &token,
                "encrypted_email" => &encrypted_email,
            });
            return request.render(template);
        }
    };

    let Some(user_id) = crate::utils::reset_token::consume(&db, &token).await else {
        if let Some(level) = crate::utils::runique_log::get_log()
            .auth
            .as_ref()
            .and_then(|a| a.reset)
        {
            crate::runique_log!(level, %email, "reset token consume failed");
        }
        request
            .notices
            .error(t("reset.invalid_or_expired").to_string())
            .await;
        return Ok(Redirect::to("/").into_response());
    };

    // The token binds the reset to one user_id (server-derived). Resolve and
    // mutate by that id (IDOR-safe); the URL email is only a UX cross-check.
    let Some(user) = BuiltinUserEntity::find_by_id(&db, user_id).await else {
        request
            .notices
            .error(t("reset.invalid_or_expired").to_string())
            .await;
        return Ok(Redirect::to("/").into_response());
    };
    if user.email().to_lowercase() != email.to_lowercase() {
        request
            .notices
            .error(t("reset.invalid_or_expired").to_string())
            .await;
        return Ok(Redirect::to("/").into_response());
    }

    let email_clean = form.cleaned_string("email").unwrap_or_default();
    let new_hash = form.cleaned_string("password").unwrap_or_default();

    match BuiltinUserEntity::set_password_and_activate(&db, user_id, &new_hash).await {
        Ok(()) => {
            // Every device signs in again with the new password — a stolen
            // session included. This request's own was closed on arrival.
            request.engine.close_user_sessions(user_id).await;
            if let Some(level) = crate::utils::runique_log::get_log()
                .auth
                .as_ref()
                .and_then(|a| a.reset)
            {
                crate::runique_log!(level, email = %email_clean, "password reset ok");
            }
            form.clear();
            apply_extra_context(request, &config.extra_context).await;
            context_update!(request => {
                "title"           => t("reset.success_title").as_ref(),
                "reset_form"      => &form,
                "reset_done"      => &true,
                "token"           => &token,
                "encrypted_email" => &encrypted_email,
            });
            return request.render(template);
        }
        Err(e) => {
            if let Some(level) = crate::utils::runique_log::get_log()
                .auth
                .as_ref()
                .and_then(|a| a.reset)
            {
                crate::runique_log!(level, email = %email_clean, error = %e, "password reset db error");
            }
            form.get_form_mut().database_error(&e);
        }
    }

    apply_extra_context(request, &config.extra_context).await;
    context_update!(request => {
        "title"           => t("reset.reset_title").as_ref(),
        "reset_form"      => &form,
        "token"           => &token,
        "encrypted_email" => &encrypted_email,
    });
    request.render(template)
}

// ─── Builder — auto-registered routes ──────────────────────────────────────

#[derive(Clone)]
struct ForgotState {
    config: Arc<PasswordResetConfig>,
}

#[derive(Clone)]
struct ResetState {
    config: Arc<PasswordResetConfig>,
}

async fn forgot_view(
    State(state): State<ForgotState>,
    mut request: Request,
) -> AppResult<Response> {
    let form: ForgotPasswordForm = request.form();
    handle_forgot_password(&mut request, form, &state.config).await
}

async fn reset_view(
    State(state): State<ResetState>,
    Path((token, encrypted_email)): Path<(String, String)>,
    mut request: Request,
) -> AppResult<Response> {
    let form: PasswordResetForm = request.form();
    handle_password_reset(&mut request, form, token, encrypted_email, &state.config).await
}

/// The merged forgot + reset router, with rate limiting applied to both routes.
pub fn build_router(config: Arc<PasswordResetConfig>) -> Router {
    use crate::middleware::security::rate_limit::{RateLimiter, rate_limit_middleware};
    use axum::middleware;
    use axum::routing::any;

    let limiter = Arc::new(
        RateLimiter::new()
            .max_requests(u32::try_from(config.max_requests).unwrap_or(u32::MAX))
            .retry_after(config.retry_after),
    );

    let forgot_state = ForgotState {
        config: config.clone(),
    };
    let reset_state = ResetState { config };

    let forgot_route = Router::new()
        .route(&forgot_state.config.forgot_route, any(forgot_view))
        .with_state(forgot_state)
        .route_layer(middleware::from_fn_with_state(
            limiter.clone(),
            rate_limit_middleware,
        ));

    let reset_path = format!(
        "{}/{{token}}/{{encrypted_email}}",
        reset_state.config.reset_route.trim_end_matches('/')
    );
    let reset_route = Router::new()
        .route(&reset_path, any(reset_view))
        .with_state(reset_state)
        .route_layer(middleware::from_fn_with_state(
            limiter,
            rate_limit_middleware,
        ));

    forgot_route.merge(reset_route)
}

/// Staging stored in the builder before construction.
pub struct PasswordResetStaging {
    /// Resolved configuration applied when the router is built.
    pub config: PasswordResetConfig,
}

#[cfg(test)]
mod public_link_base_tests {
    use super::public_link_base;
    use axum::http::{HeaderMap, HeaderValue, header::HOST};

    fn with_host(host: &str) -> HeaderMap {
        let mut headers = HeaderMap::new();
        headers.insert(HOST, HeaderValue::from_str(host).unwrap());
        headers
    }

    #[test]
    fn the_configured_base_wins_over_the_host() {
        let headers = with_host("evil.com");
        for debug in [true, false] {
            assert_eq!(
                public_link_base(Some("https://mysite.com/"), &headers, debug).as_deref(),
                Some("https://mysite.com")
            );
        }
    }

    #[test]
    fn production_never_uses_the_host() {
        assert_eq!(public_link_base(None, &with_host("evil.com"), false), None);
    }

    #[test]
    fn debug_falls_back_on_the_host() {
        assert_eq!(
            public_link_base(None, &with_host("localhost:3000"), true).as_deref(),
            Some("http://localhost:3000")
        );
        assert_eq!(public_link_base(None, &HeaderMap::new(), true), None);
    }
}