Skip to main content

smeltery_temper/
lib.rs

1#![doc = include_str!("../README.md")]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3
4mod actions;
5mod ctx;
6mod error;
7mod events;
8mod forms;
9pub mod messages;
10mod pipeline;
11mod responses;
12mod routes;
13pub mod testing;
14pub mod two_factor;
15mod views;
16
17use std::future::Future;
18use std::marker::PhantomData;
19use std::sync::Arc;
20
21use smeltery_core::auth::{Authenticatable, MustVerifyEmail};
22use smeltery_core::db::{PrimaryKeyOf, Record};
23use smeltery_core::routing::Router;
24use smeltery_core::{App, AppBuilder, Result};
25
26pub use actions::{
27    CreatesNewUsers, EmailChanged, PasswordInput, ResetsUserPasswords, SocialUser,
28    UpdatePasswordInput, UpdatesUserPasswords, UpdatesUserProfileInformation,
29};
30pub use ctx::{TemperCtx, ViewCtx};
31pub use error::TemperError;
32pub use events::TemperEvent;
33pub use pipeline::{PipelineStep, login_pipeline};
34pub use responses::{DefaultResponses, TemperResponses};
35pub use two_factor::{TwoFactor, TwoFactorAuthenticatable, TwoFactorSetup, TwoFactorStatus};
36pub use views::{TemperViews, ViewSetting};
37
38use events::Listener;
39use pipeline::Hook;
40use routes::Registrar;
41use views::ViewFn;
42
43/// Registers the routes of one feature.
44type FeatureFn<U> = Box<dyn FnOnce(&mut Registrar<'_, U>) + Send>;
45
46/// The throttles on Temper's form routes (`throttle:<max>,<minutes>` values; an invalid value stops the app at
47/// boot, like any `throttle:` alias).
48///
49/// ```
50/// use smeltery::temper::Limits;
51///
52/// let limits = Limits::new().login("10,1").forms("3,1");
53/// # let _ = limits;
54/// ```
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct Limits {
57    pub(crate) login: String,
58    pub(crate) forms: String,
59}
60
61impl Default for Limits {
62    fn default() -> Self {
63        Self::new()
64    }
65}
66
67impl Limits {
68    /// The defaults: `30,1` on `POST /login`, `6,1` on every other form route.
69    pub fn new() -> Self {
70        Self {
71            login: "30,1".to_owned(),
72            forms: "6,1".to_owned(),
73        }
74    }
75
76    /// The throttle of `POST /login` (default `30,1`: thirty a minute per client).
77    #[must_use]
78    pub fn login(mut self, limit: impl Into<String>) -> Self {
79        self.login = limit.into();
80        self
81    }
82
83    /// The throttle of every other form route: registration, the reset forms, the verification link, password
84    /// confirmation, profile and password updates (default `6,1`).
85    #[must_use]
86    pub fn forms(mut self, limit: impl Into<String>) -> Self {
87        self.forms = limit.into();
88        self
89    }
90}
91
92/// What every handler of one app's Temper shares.
93pub(crate) struct Shared<U> {
94    pub(crate) home: Option<String>,
95    pub(crate) views: Option<TemperViews>,
96    pub(crate) responses: Arc<dyn TemperResponses>,
97    pub(crate) listeners: Vec<Listener>,
98    pub(crate) hooks: Vec<Hook<U>>,
99    pub(crate) email_verification: bool,
100    /// Whether Temper's password-reset routes are on (an address change then deletes the pending reset token).
101    pub(crate) reset_passwords: bool,
102    /// Whether a user must give a second factor (set by `two_factor`).
103    pub(crate) second_step: Option<Required>,
104}
105
106/// Whether the user with this id must give a second factor, read from their row now.
107type Required =
108    Arc<dyn Fn(App, i64) -> smeltery_core::BoxFuture<'static, Result<bool>> + Send + Sync>;
109
110/// What `Temper::two_factor` adds.
111struct TwoFactorFeature<U> {
112    options: TwoFactor,
113    required: Required,
114    routes: FeatureFn<U>,
115    install: Box<dyn FnOnce(AppBuilder) -> AppBuilder + Send>,
116}
117
118impl<U> Shared<U> {
119    /// The request context with the configured home page.
120    pub(crate) fn ctx(&self, ctx: TemperCtx) -> TemperCtx {
121        ctx.with_home(self.home.as_deref())
122    }
123
124    /// One page's view.
125    pub(crate) fn view(&self, pick: impl Fn(&TemperViews) -> Option<&ViewFn>) -> Option<&ViewFn> {
126        self.views.as_ref().and_then(pick)
127    }
128}
129
130/// Temper's set-up for the user model `U`: which features are on, the app's actions, views and answers. Installed
131/// with [`TemperExt::temper`].
132///
133/// ```
134/// # mod user {
135/// #     use smeltery::db::prelude::*;
136/// #     #[sea_orm::model]
137/// #     #[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
138/// #     #[sea_orm(table_name = "users")]
139/// #     pub struct Model {
140/// #         #[sea_orm(primary_key)]
141/// #         pub id: i64,
142/// #         pub email: String,
143/// #         pub email_verified_at: Option<DateTimeUtc>,
144/// #         pub password: String,
145/// #         pub remember_token: Option<String>,
146/// #     }
147/// #     impl ActiveModelBehavior for ActiveModel {}
148/// #     impl smeltery::auth::Authenticatable for Model {
149/// #         fn auth_id(&self) -> i64 { self.id }
150/// #         fn password_hash(&self) -> &str { &self.password }
151/// #         fn remember_token(&self) -> Option<&str> { self.remember_token.as_deref() }
152/// #     }
153/// #     impl smeltery::auth::MustVerifyEmail for Model {
154/// #         fn email(&self) -> &str { &self.email }
155/// #         fn email_verified_at(&self) -> Option<DateTimeUtc> { self.email_verified_at }
156/// #     }
157/// # }
158/// # use user::Model as User;
159/// use smeltery::http::Html;
160/// use smeltery::temper::{Temper, TemperExt as _, TemperViews};
161///
162/// fn build(app: smeltery::AppBuilder) -> smeltery::AppBuilder {
163///     app.temper(
164///         Temper::<User>::new()
165///             .email_verification()
166///             .views(
167///                 TemperViews::new()
168///                     .login(|_| Html("login"))
169///                     .confirm_password(|_| Html("confirm your password"))
170///                     .verify_email(|_| Html("check your inbox")),
171///             ),
172///     )
173/// }
174/// # let _ = build;
175/// ```
176pub struct Temper<U> {
177    registration: Option<FeatureFn<U>>,
178    reset_passwords: Option<FeatureFn<U>>,
179    email_verification: bool,
180    profile: Option<FeatureFn<U>>,
181    passwords: Option<FeatureFn<U>>,
182    two_factor: Option<TwoFactorFeature<U>>,
183    home: Option<String>,
184    prefix: String,
185    routes: bool,
186    without: Vec<String>,
187    views: ViewSetting,
188    responses: Arc<dyn TemperResponses>,
189    listeners: Vec<Listener>,
190    hooks: Vec<Hook<U>>,
191    policies: Vec<pipeline::Policy<U>>,
192    limits: Limits,
193    _user: PhantomData<fn() -> U>,
194}
195
196impl<U> std::fmt::Debug for Temper<U> {
197    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
198        f.debug_struct("Temper")
199            .field("registration", &self.registration.is_some())
200            .field("reset_passwords", &self.reset_passwords.is_some())
201            .field("email_verification", &self.email_verification)
202            .field("update_profile_information", &self.profile.is_some())
203            .field("update_passwords", &self.passwords.is_some())
204            .field("two_factor", &self.two_factor.as_ref().map(|t| t.options))
205            .field("home", &self.home)
206            .field("prefix", &self.prefix)
207            .field("routes", &self.routes)
208            .field("without", &self.without)
209            .field("views", &self.views)
210            .field("listeners", &self.listeners.len())
211            .field("login_pipeline", &self.hooks.len())
212            .field("login_policies", &self.policies.len())
213            .field("limits", &self.limits)
214            .finish()
215    }
216}
217
218impl<U: Authenticatable + Record> Default for Temper<U> {
219    fn default() -> Self {
220        Self::new()
221    }
222}
223
224impl<U: Authenticatable + Record> Temper<U> {
225    /// Login, logout and password confirmation; every other feature off; no views yet; the default answers.
226    pub fn new() -> Self {
227        Self {
228            registration: None,
229            reset_passwords: None,
230            email_verification: false,
231            profile: None,
232            passwords: None,
233            two_factor: None,
234            home: None,
235            prefix: String::new(),
236            routes: true,
237            without: Vec::new(),
238            views: ViewSetting::Pages(TemperViews::new()),
239            responses: Arc::new(DefaultResponses),
240            listeners: Vec::new(),
241            hooks: Vec::new(),
242            policies: Vec::new(),
243            limits: Limits::new(),
244            _user: PhantomData,
245        }
246    }
247
248    /// Registration: `GET /register` (`register`) and `POST /register` (`register.store`); `action` creates the
249    /// user.
250    #[must_use]
251    pub fn registration<A: CreatesNewUsers<U>>(mut self, action: A) -> Self {
252        let action = Arc::new(action);
253        self.registration = Some(Box::new(move |reg| routes::registration(reg, action)));
254        self
255    }
256
257    /// Password resets: `GET` / `POST /forgot-password` (`password.request`, `password.email`) and `GET` /
258    /// `POST /reset-password/{token}` (`password.reset`, `password.update`).
259    #[must_use]
260    pub fn reset_passwords<A: ResetsUserPasswords<U>>(mut self, action: A) -> Self {
261        let action = Arc::new(action);
262        self.reset_passwords = Some(Box::new(move |reg| routes::reset_passwords(reg, action)));
263        self
264    }
265
266    /// Profile updates: `PUT /user/profile-information` (`user-profile-information.update`), behind `password.confirm`
267    /// (the address decides where reset links go). An address change deletes the user's pending reset link.
268    #[must_use]
269    pub fn update_profile_information<A: UpdatesUserProfileInformation<U>>(
270        mut self,
271        action: A,
272    ) -> Self {
273        let action = Arc::new(action);
274        self.profile = Some(Box::new(move |reg| routes::update_profile(reg, action)));
275        self
276    }
277
278    /// Password updates: `PUT /user/password` (`user-password.update`).
279    #[must_use]
280    pub fn update_passwords<A: UpdatesUserPasswords<U>>(mut self, action: A) -> Self {
281        let action = Arc::new(action);
282        self.passwords = Some(Box::new(move |reg| routes::update_passwords(reg, action)));
283        self
284    }
285
286    /// Where signed-in users go after logging in, registering, confirming their password or verifying their
287    /// address (default: `AUTH_HOME`).
288    #[must_use]
289    pub fn home(mut self, path: impl Into<String>) -> Self {
290        self.home = Some(path.into());
291        self
292    }
293
294    /// Put every Temper route under `prefix` (`/auth` → `/auth/login`); route names stay the same.
295    #[must_use]
296    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
297        self.prefix = prefix.into();
298        self
299    }
300
301    /// `false`: register no routes (the app declares its own and uses Temper's actions, answers and
302    /// [`login_pipeline`]).
303    #[must_use]
304    pub fn routes(mut self, routes: bool) -> Self {
305        self.routes = routes;
306        self
307    }
308
309    /// Leave out the route named `name` (the app declares its own route there). An unknown name stops the app at
310    /// boot.
311    #[must_use]
312    pub fn without_route(mut self, name: impl Into<String>) -> Self {
313        self.without.push(name.into());
314        self
315    }
316
317    /// The pages ([`TemperViews`]), or `false` for an app without pages. Without pages, clients should send
318    /// `Accept: application/json`: a browser request gets the browser answers, which redirect to page routes that
319    /// do not exist.
320    #[must_use]
321    pub fn views(mut self, views: impl Into<ViewSetting>) -> Self {
322        self.views = views.into();
323        self
324    }
325
326    /// Answer the outcomes the app's way ([`TemperResponses`]).
327    #[must_use]
328    pub fn responses(mut self, responses: impl TemperResponses) -> Self {
329        self.responses = Arc::new(responses);
330        self
331    }
332
333    /// Run `listener` for every [`TemperEvent`], after the answer is decided (it never changes or delays the
334    /// answer; under `APP_ENV=testing` it runs before the answer returns). An error or a panic is logged at `warn`.
335    #[must_use]
336    pub fn listen<F, Fut>(mut self, listener: F) -> Self
337    where
338        F: Fn(App, TemperEvent) -> Fut + Send + Sync + 'static,
339        Fut: Future<Output = Result<()>> + Send + 'static,
340    {
341        self.listeners
342            .push(Arc::new(move |app, event| Box::pin(listener(app, event))));
343        self
344    }
345
346    /// The throttles of the form routes.
347    #[must_use]
348    pub fn limits(mut self, limits: Limits) -> Self {
349        self.limits = limits;
350        self
351    }
352
353    /// Add a step to the login pipeline (run in order, after the password check or a social login, before the
354    /// sign-in): `PipelineStep::Respond(response)` stops the login with that answer, an error fails it.
355    ///
356    /// Steps gate new sign-ins only: a session that is already signed in and a sign-in restored from a remember-me
357    /// cookie never meet them. To lock an account out, also end its credentials (`auth::password_changed`) or check
358    /// the user in a middleware.
359    ///
360    /// ```
361    /// # mod user {
362    /// #     use smeltery::db::prelude::*;
363    /// #     #[sea_orm::model]
364    /// #     #[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
365    /// #     #[sea_orm(table_name = "users")]
366    /// #     pub struct Model {
367    /// #         #[sea_orm(primary_key)]
368    /// #         pub id: i64,
369    /// #         pub banned: bool,
370    /// #         pub password: String,
371    /// #         pub remember_token: Option<String>,
372    /// #     }
373    /// #     impl ActiveModelBehavior for ActiveModel {}
374    /// #     impl smeltery::auth::Authenticatable for Model {
375    /// #         fn auth_id(&self) -> i64 { self.id }
376    /// #         fn password_hash(&self) -> &str { &self.password }
377    /// #         fn remember_token(&self) -> Option<&str> { self.remember_token.as_deref() }
378    /// #     }
379    /// # }
380    /// # use user::Model as User;
381    /// use smeltery::Error;
382    /// use smeltery::temper::{PipelineStep, Temper};
383    ///
384    /// let temper = Temper::<User>::new().login_pipeline(|_ctx, user: User| async move {
385    ///     if user.banned {
386    ///         return Err(Error::validation("email", "This account is closed."));
387    ///     }
388    ///     Ok(PipelineStep::Continue)
389    /// });
390    /// # let _ = temper;
391    /// ```
392    #[must_use]
393    pub fn login_pipeline<F, Fut>(mut self, step: F) -> Self
394    where
395        F: Fn(TemperCtx, U) -> Fut + Send + Sync + 'static,
396        Fut: Future<Output = Result<PipelineStep>> + Send + 'static,
397    {
398        self.hooks.push(pipeline::hook(step));
399        self
400    }
401
402    /// Add a session-free login rule, registered as core's [`LoginPolicy`](smeltery_core::auth::LoginPolicy):
403    /// "may this user sign in now?". Unlike [`login_pipeline`](Self::login_pipeline) steps (web sign-ins only), it
404    /// gates every way in: Temper's `POST /login` (before the steps and the second factor), the two-factor challenge
405    /// (asked again before the code), registration (after `create`: a refusal keeps the account, fires `Registered`
406    /// and signs nobody in), a social login through core's `LoginCompletion`, a remember-me cookie, core's
407    /// `Auth::attempt`, and a token endpoint that asks `app.check_login(…)`. A refusal answers its status and message
408    /// (JSON clients) or sends the browser back with the message on `email` (from the challenge: to the login page);
409    /// nobody is signed in. Rules that must hold for API tokens too (a suspended account) belong here. A policy gates
410    /// new sign-ins, token issuance and remember-me restores only; to cut what the user already holds, call
411    /// `auth::end_credentials` (open sessions through the user's `credentials_epoch` column, the remember token, API
412    /// tokens, sockets).
413    ///
414    /// ```
415    /// # mod user {
416    /// #     use smeltery::db::prelude::*;
417    /// #     #[sea_orm::model]
418    /// #     #[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
419    /// #     #[sea_orm(table_name = "users")]
420    /// #     pub struct Model {
421    /// #         #[sea_orm(primary_key)]
422    /// #         pub id: i64,
423    /// #         pub suspended: bool,
424    /// #         pub password: String,
425    /// #         pub remember_token: Option<String>,
426    /// #     }
427    /// #     impl ActiveModelBehavior for ActiveModel {}
428    /// #     impl smeltery::auth::Authenticatable for Model {
429    /// #         fn auth_id(&self) -> i64 { self.id }
430    /// #         fn password_hash(&self) -> &str { &self.password }
431    /// #         fn remember_token(&self) -> Option<&str> { self.remember_token.as_deref() }
432    /// #     }
433    /// # }
434    /// # use user::Model as User;
435    /// use smeltery::auth::LoginDecision;
436    /// use smeltery::http::StatusCode;
437    /// use smeltery::temper::Temper;
438    ///
439    /// let temper = Temper::<User>::new().login_policy(|_app, user: User| async move {
440    ///     Ok(if user.suspended {
441    ///         LoginDecision::refuse(StatusCode::FORBIDDEN, "This account is suspended.")
442    ///     } else {
443    ///         LoginDecision::Allow
444    ///     })
445    /// });
446    /// # let _ = temper;
447    /// ```
448    #[must_use]
449    pub fn login_policy<F, Fut>(mut self, check: F) -> Self
450    where
451        F: Fn(App, U) -> Fut + Send + Sync + 'static,
452        Fut: Future<Output = Result<smeltery_core::auth::LoginDecision>> + Send + 'static,
453    {
454        self.policies.push(pipeline::policy(check));
455        self
456    }
457}
458
459impl<U: Authenticatable + Record + MustVerifyEmail> Temper<U> {
460    /// E-mail verification: `GET /email/verify` (`verification.notice`), `GET /email/verify/{id}/{hash}`
461    /// (`verification.verify`) and `POST /email/verification-notification` (`verification.send`), and the link
462    /// after registration and after an address change. Requiring verified addresses stays core's
463    /// `.verify_email::<User>()` (the `verified` middleware); without it every signed-in user counts as verified.
464    #[must_use]
465    pub fn email_verification(mut self) -> Self {
466        self.email_verification = true;
467        self
468    }
469}
470
471impl<U: TwoFactorAuthenticatable> Temper<U> {
472    /// Two-factor authentication: the challenge after the password (`GET` / `POST /two-factor-challenge`,
473    /// `two-factor.login`, `two-factor.login.store`) and the management routes (enable, confirm, disable, the QR
474    /// code, the secret key, the recovery codes; behind `password.confirm`; with `confirm_password(false)` only a first
475    /// enrolment goes without a recent password confirmation). Also
476    /// registers core's `SecondFactor` (other sign-in endpoints ask it), a credential listener that removes an
477    /// enrolment when a reset verifies a previously unverified address, and the console command
478    /// `temper:two-factor-disable <email> --force`.
479    #[must_use]
480    pub fn two_factor(mut self, options: TwoFactor) -> Self {
481        self.two_factor = Some(TwoFactorFeature {
482            options,
483            required: Arc::new(move |app: App, id: i64| {
484                Box::pin(async move {
485                    // A fresh row: a user value read before two-factor was enabled must not skip it.
486                    let user = two_factor::fresh::<U>(&app, id).await?.ok_or_else(|| {
487                        smeltery_core::Error::internal("the user signing in is gone")
488                    })?;
489                    Ok(options.required(&user))
490                })
491            }),
492            routes: Box::new(move |reg| two_factor::routes::register(reg, options)),
493            install: Box::new(move |app| {
494                app.second_factor(two_factor::Factor::<U> {
495                    options,
496                    _user: PhantomData,
497                })
498                .credential_listener(two_factor::ResetListener::<U>(PhantomData))
499                .commands(|c| {
500                    c.add(two_factor::DisableCommand::<U>::new());
501                })
502            }),
503        });
504        self
505    }
506}
507
508/// Installs Temper on an app: `use smeltery::temper::TemperExt as _;` then `app.temper(Temper::new()…)`.
509pub trait TemperExt: Sized {
510    /// Register `U` as the user model (`.auth::<U>()`), Temper's routes (unless `routes(false)`), the login
511    /// pipeline as core's `LoginCompletion` and `dont_flash(["code"])`. The app stops at boot with a [`TemperError`]
512    /// when a page route has no view, `without_route` names an unknown route or the prefix is invalid; core stops
513    /// it when `.auth::<…>()` is called with another model, before or after `.temper(…)`.
514    fn temper<U>(self, temper: Temper<U>) -> Self
515    where
516        U: Record
517            + Authenticatable
518            + sea_orm::FromQueryResult
519            + sea_orm::ModelTrait<Entity = <U as Record>::Entity>,
520        PrimaryKeyOf<U>: From<i64>;
521}
522
523impl TemperExt for AppBuilder {
524    fn temper<U>(self, temper: Temper<U>) -> Self
525    where
526        U: Record
527            + Authenticatable
528            + sea_orm::FromQueryResult
529            + sea_orm::ModelTrait<Entity = <U as Record>::Entity>,
530        PrimaryKeyOf<U>: From<i64>,
531    {
532        let Temper {
533            registration,
534            reset_passwords,
535            email_verification,
536            profile,
537            passwords,
538            two_factor,
539            home,
540            prefix,
541            routes,
542            without,
543            views,
544            responses,
545            listeners,
546            hooks,
547            policies,
548            limits,
549            _user,
550        } = temper;
551        let views = match views {
552            ViewSetting::Pages(views) => Some(views),
553            ViewSetting::None => None,
554        };
555        let (two_factor_options, second_step, two_factor_routes, install) = match two_factor {
556            Some(t) => (
557                Some(t.options),
558                Some(t.required),
559                Some(t.routes),
560                Some(t.install),
561            ),
562            None => (None, None, None, None),
563        };
564        let problem = setup_problem(
565            &prefix,
566            &without,
567            routes.then_some(()).and(views.as_ref()),
568            Features {
569                two_factor: two_factor_options,
570                registration: registration.is_some(),
571                reset_passwords: reset_passwords.is_some(),
572                email_verification,
573            },
574        );
575        let pages = views.is_some();
576        let has_resets = reset_passwords.is_some();
577        let shared = Arc::new(Shared {
578            home,
579            views,
580            responses,
581            listeners,
582            hooks,
583            email_verification,
584            reset_passwords: has_resets,
585            second_step,
586        });
587        let mut app = self
588            .auth::<U>()
589            // A field named `code` (one-time codes) is never flashed back as old input.
590            .dont_flash(&["code"])
591            .service(Arc::clone(&shared))
592            .login_completion(pipeline::Completion(Arc::clone(&shared)));
593        for policy in policies {
594            app = app.login_policy(policy);
595        }
596        if let Some(install) = install {
597            app = install(app);
598        }
599        if routes {
600            app = app.routes(move |r| {
601                let add = move |router: &mut Router| {
602                    let mut reg = Registrar {
603                        router,
604                        shared,
605                        limits,
606                        without,
607                        pages,
608                    };
609                    routes::core(&mut reg);
610                    for feature in [
611                        registration,
612                        reset_passwords,
613                        profile,
614                        passwords,
615                        two_factor_routes,
616                    ]
617                    .into_iter()
618                    .flatten()
619                    {
620                        feature(&mut reg);
621                    }
622                    if email_verification {
623                        routes::email_verification(&mut reg);
624                    }
625                };
626                if prefix.is_empty() {
627                    add(r);
628                } else {
629                    r.group(&prefix, add);
630                }
631            });
632        }
633        app.on_boot(move |app| async move {
634            let _ = app;
635            problem.map_or(Ok(()), |problem| Err(problem.into()))
636        })
637    }
638}
639
640/// The first set-up mistake, if any.
641/// Which features are on (for the set-up checks).
642struct Features {
643    two_factor: Option<TwoFactor>,
644    registration: bool,
645    reset_passwords: bool,
646    email_verification: bool,
647}
648
649/// `views`: the pages when routes are registered with pages.
650fn setup_problem(
651    prefix: &str,
652    without: &[String],
653    views: Option<&TemperViews>,
654    features: Features,
655) -> Option<TemperError> {
656    let Features {
657        two_factor,
658        registration,
659        reset_passwords,
660        email_verification,
661    } = features;
662    if !prefix.is_empty()
663        && (!prefix.starts_with('/') || prefix.ends_with('/') || prefix.contains(['{', '}']))
664    {
665        return Some(TemperError::InvalidPrefix(prefix.to_owned()));
666    }
667    if let Some(problem) = two_factor.and_then(|t| t.problem()) {
668        return Some(TemperError::InvalidTwoFactor(problem));
669    }
670    let known = || {
671        routes::ROUTE_NAMES
672            .iter()
673            .chain(two_factor::routes::ROUTE_NAMES)
674    };
675    if let Some(name) = without.iter().find(|name| !known().any(|k| k == name)) {
676        return Some(TemperError::UnknownRoute {
677            name: name.clone(),
678            known: known().copied().collect::<Vec<_>>().join(", "),
679        });
680    }
681    let views = views?;
682    let pages: [(bool, &'static str, &'static str, bool); 7] = [
683        (
684            two_factor.is_some(),
685            "two_factor_challenge",
686            "two-factor.login",
687            views.two_factor_challenge.is_some(),
688        ),
689        (true, "login", "login", views.login.is_some()),
690        (
691            true,
692            "confirm_password",
693            "password.confirm",
694            views.confirm_password.is_some(),
695        ),
696        (
697            registration,
698            "register",
699            "register",
700            views.register.is_some(),
701        ),
702        (
703            reset_passwords,
704            "forgot_password",
705            "password.request",
706            views.forgot_password.is_some(),
707        ),
708        (
709            reset_passwords,
710            "reset_password",
711            "password.reset",
712            views.reset_password.is_some(),
713        ),
714        (
715            email_verification,
716            "verify_email",
717            "verification.notice",
718            views.verify_email.is_some(),
719        ),
720    ];
721    pages
722        .into_iter()
723        .find(|(on, _, route, given)| *on && !given && !without.iter().any(|w| w == route))
724        .map(|(_, page, route, _)| TemperError::MissingView { page, route })
725}