Skip to main content

renox_core/auth/
module.rs

1use std::sync::Arc;
2
3use axum::extract::{Extension, State};
4use axum::response::{IntoResponse, Redirect, Response};
5use serde::{Deserialize, Serialize};
6use serde_json::{Value, json};
7
8use super::events::{LockedOut, LoggedIn, LoggedOut, LoginFailed, Registered, announce};
9use super::user::dummy_hash;
10use super::{User, intended, login, logout, passwords, verification, verify_password};
11use crate::db::Migration;
12use crate::i18n::Lang;
13use crate::validation::{Errors, Valid, Validate, ValidationError, Validator};
14use crate::{
15    AppState, AuthUser, ClientIp, Htmx, HxRedirect, Module, Result, Routes, Session, View, context,
16    view,
17};
18
19const MIGRATIONS: &[Migration] = &[
20    crate::db::framework_migration!("auth", "00010101000000_create_users_table"),
21    crate::db::framework_migration!("auth", "00010101000001_create_password_reset_tokens_table"),
22    crate::db::framework_migration!("auth", "00010101000002_create_personal_access_tokens_table"),
23    crate::db::framework_migration!("auth", "00010101000003_create_notifications_table"),
24    crate::db::framework_migration!("auth", "00010101000004_add_sessions_revoked_at_to_users"),
25    crate::db::framework_migration!(
26        "auth",
27        "00010101000005_add_abilities_to_personal_access_tokens"
28    ),
29    crate::db::framework_migration!("auth", "00010101000006_create_revoked_sessions_table"),
30    crate::db::framework_migration!("auth", "00010101000007_create_device_tokens_table"),
31    crate::db::framework_migration!("auth", "00010101000008_create_one_time_codes_table"),
32];
33
34pub(crate) struct Settings {
35    pub(super) password: crate::validation::Password,
36    pub(super) registration: bool,
37    redirect_to: Option<String>,
38    pub(super) verify_email: bool,
39    rules: Option<RulesFn>,
40    pub(super) on_registered: Option<RegisteredFn>,
41    pub(super) passwordless: super::passwordless::Passwordless,
42}
43
44type RulesFn = Arc<dyn Fn(&Registration, &mut Validator) + Send + Sync>;
45pub(super) type RegisteredFn = Arc<
46    dyn Fn(
47            AppState,
48            User,
49            Registration,
50        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result> + Send>>
51        + Send
52        + Sync,
53>;
54
55/// What was submitted to `/register`, for [`Auth::registration_rules`] and
56/// [`Auth::on_registered`]. Add the fields to your own
57/// `renox/auth/register.html` (copy the built-in one).
58#[derive(Debug, Clone)]
59#[non_exhaustive]
60pub struct Registration {
61    pub(super) fields: serde_json::Map<String, Value>,
62}
63
64impl Registration {
65    /// A submitted field, trimmed; `""` when it's missing.
66    pub fn get(&self, field: &str) -> String {
67        match self.fields.get(field) {
68            Some(Value::String(value)) => value.trim().to_owned(),
69            Some(Value::Array(values)) => values
70                .first()
71                .and_then(Value::as_str)
72                .unwrap_or_default()
73                .trim()
74                .to_owned(),
75            _ => String::new(),
76        }
77    }
78
79    /// Every value of a field sent several times (a group of checkboxes).
80    pub fn all(&self, field: &str) -> Vec<String> {
81        match self.fields.get(field) {
82            Some(Value::String(value)) => vec![value.clone()],
83            Some(Value::Array(values)) => values
84                .iter()
85                .filter_map(|v| v.as_str().map(str::to_owned))
86                .collect(),
87            _ => Vec::new(),
88        }
89    }
90}
91
92/// Login, registration, password reset and email verification pages, and
93/// the `users`, `password_reset_tokens` and `personal_access_tokens` tables.
94///
95/// Routes: `login`, `register` (unless `without_registration`), `logout`,
96/// `password.request`, `password.email`, `password.reset`,
97/// `password.update`, `password.confirm`, `verification.notice`,
98/// `verification.verify` and `verification.send`. [`Auth::account`] adds
99/// `account.show`, `account.profile`, `account.password`,
100/// `account.logout_others` and `account.destroy`;
101/// [`Auth::notifications`] adds the `notifications.*` routes.
102/// docs/authorization.md lists each one's method and address.
103/// The pages live in `renox/auth/*.html`, inside `renox/auth/layout.html`;
104/// create a file with the same name under your views to replace one.
105///
106/// Failed logins lock out 5 tries per email and IP a minute, 20 per email in
107/// 15 minutes from any IP, and 50 per IP in 15 minutes for any email (set
108/// `TRUSTED_PROXIES` behind a proxy). Logging out ends this device's
109/// session only; a new password or a password reset ends the other sessions.
110#[derive(Clone)]
111pub struct Auth {
112    password: crate::validation::Password,
113    account: bool,
114    registration: bool,
115    redirect_to: Option<String>,
116    verify_email: bool,
117    notifications: bool,
118    rules: Option<RulesFn>,
119    on_registered: Option<RegisteredFn>,
120    passwordless: super::passwordless::Passwordless,
121}
122
123impl Auth {
124    /// Registration on, account pages and email verification off, the default `Password` policy.
125    pub fn new() -> Self {
126        Self {
127            password: crate::validation::Password::default(),
128            account: false,
129            registration: true,
130            redirect_to: None,
131            verify_email: false,
132            notifications: false,
133            rules: None,
134            on_registered: None,
135            passwordless: super::passwordless::Passwordless {
136                magic_link: None,
137                same_browser: false,
138                codes: None,
139                register_on_first_use: false,
140                sent: Default::default(),
141            },
142        }
143    }
144
145    /// Turns on login by magic link: `/login/link` (route
146    /// `login.link.request`) asks for an email address and mails a link that
147    /// logs in once, for 15 minutes ([`Auth::magic_link_ttl`]), without a
148    /// password. Opening the link shows a "Log in as …?" page whose button
149    /// does the login, so mail scanners that open links don't use it up.
150    /// The login page lists the option. The second login step, the login
151    /// throttle and the audit log work as for passwords; see
152    /// [`passwordless`](super::passwordless) for the details.
153    ///
154    /// ```
155    /// # use renox::prelude::*;
156    /// # let _ =
157    /// App::new().module(Auth::new().magic_link().same_browser())
158    /// # ;
159    /// ```
160    pub fn magic_link(mut self) -> Self {
161        self.passwordless.magic_link = Some(super::passwordless::MagicLink {
162            ttl: std::time::Duration::from_secs(15 * 60),
163        });
164        self
165    }
166
167    /// How long a magic link works; 15 minutes by default. Turns magic links
168    /// on.
169    pub fn magic_link_ttl(mut self, ttl: std::time::Duration) -> Self {
170        self.passwordless.magic_link = Some(super::passwordless::MagicLink { ttl });
171        self
172    }
173
174    /// Makes a magic link work only in the browser that asked for it. Off by
175    /// default, because people read mail on another device; turn it on when
176    /// that would be a risk. (Login codes always work only in the browser
177    /// that asked for them.)
178    pub fn same_browser(mut self) -> Self {
179        self.passwordless.same_browser = true;
180        self
181    }
182
183    /// Turns on login by one-time code: `/login/code` (routes
184    /// `login.code.request`, `login.code.send`, `login.code.verify`,
185    /// `login.code.resend`; see [`passwordless`](super::passwordless)). See [`LoginCodes`](super::LoginCodes) for the
186    /// channel (mail, or SMS and WhatsApp through `App::channel`), digits,
187    /// lifetime, tries and how a phone number finds its account.
188    pub fn login_codes(mut self, mut codes: super::LoginCodes) -> Self {
189        if codes.channels.is_empty() {
190            codes = codes.channel("mail");
191        }
192        self.passwordless.codes = Some(codes);
193        self
194    }
195
196    /// Makes an account (no password, the address counted as verified, the
197    /// `on_registered` hook run) for an email address that proves it owns
198    /// it with a magic link or a code sent by mail, instead of refusing
199    /// unknown addresses. Needs registration to be open. Visitors can't tell
200    /// the difference between a known and an unknown address before proving
201    /// it. See [`register_verified`](super::register_verified).
202    pub fn register_on_first_use(mut self) -> Self {
203        self.passwordless.register_on_first_use = true;
204        self
205    }
206
207    /// Turns on the in-app notification list for the UI kit's
208    /// `notification_bell`: the `notifications.*` routes (a page that is
209    /// also the bell's panel, mark read or unread, delete, and a stream of
210    /// Server-Sent Events for new ones), and `unread_notifications` (the
211    /// logged-in user's unread count) in every view.
212    ///
213    /// ```
214    /// # use renox::prelude::*;
215    /// # let _ =
216    /// App::new().module(Auth::new().notifications())
217    /// # ;
218    /// ```
219    pub fn notifications(mut self) -> Self {
220        self.notifications = true;
221        self
222    }
223
224    /// Validates fields the app adds to the registration form, with the
225    /// built-in ones. Their errors show next to the inputs like any other.
226    ///
227    /// ```
228    /// # use renox::prelude::*;
229    /// # let _ =
230    /// Auth::new()
231    ///     .registration_rules(|form, v| {
232    ///         v.field("phone", &form.get("phone")).required().max(20);
233    ///     })
234    ///     .on_registered(|mut user, form, state| async move {
235    ///         // `phone` and `role` are columns the app added to `users`.
236    ///         user.set(&state.db, "phone", form.get("phone")).await?;
237    ///         let first = User::query().count(&state.db).await? == 1;
238    ///         user.set(&state.db, "role", if first { "admin" } else { "member" }).await
239    ///     })
240    /// # ;
241    /// ```
242    pub fn registration_rules(
243        mut self,
244        rules: impl Fn(&Registration, &mut Validator) + Send + Sync + 'static,
245    ) -> Self {
246        self.rules = Some(Arc::new(rules));
247        self
248    }
249
250    /// Runs after a new user is saved and before they're logged in, e.g. to
251    /// save the app's own fields or give a role. If it fails, the user is
252    /// deleted again and the visitor gets the error, so they can try again.
253    pub fn on_registered<F, Fut>(mut self, hook: F) -> Self
254    where
255        F: Fn(User, Registration, AppState) -> Fut + Send + Sync + 'static,
256        Fut: std::future::Future<Output = Result> + Send + 'static,
257    {
258        self.on_registered = Some(Arc::new(move |state, user, form| {
259            Box::pin(hook(user, form, state))
260        }));
261        self
262    }
263
264    /// Emails new users a verification link. Guard routes that need a
265    /// verified address with `Routes::require_verified()`.
266    pub fn verify_email(mut self) -> Self {
267        self.verify_email = true;
268        self
269    }
270
271    /// What passwords must contain on the register, reset and account
272    /// forms; `Password::min(8)` by default.
273    ///
274    /// ```
275    /// # use renox::prelude::*;
276    /// use renox::validation::Password;
277    /// # let _ =
278    /// Auth::new().password_rules(Password::min(12).mixed_case().numbers())
279    /// # ;
280    /// ```
281    pub fn password_rules(mut self, policy: crate::validation::Password) -> Self {
282        self.password = policy;
283        self
284    }
285
286    /// Adds the account page (`/account`, route `account.show`): change
287    /// name and email (a new email must be verified again with
288    /// `verify_email`), change the password, log out other devices, delete
289    /// the account. The last two ask for the password. Override the page at
290    /// `resources/views/renox/auth/account.html`.
291    pub fn account(mut self) -> Self {
292        self.account = true;
293        self
294    }
295
296    /// Hides `/register`, e.g. for back-office apps where an admin adds users.
297    pub fn without_registration(mut self) -> Self {
298        self.registration = false;
299        self
300    }
301
302    /// Where to go after logging in or registering when no page asked for
303    /// the login. Defaults to the `home` route, or `/`.
304    pub fn redirect_to(mut self, path: &str) -> Self {
305        self.redirect_to = Some(path.to_owned());
306        self
307    }
308
309    fn settings(&self) -> Settings {
310        Settings {
311            password: self.password.clone(),
312            registration: self.registration,
313            redirect_to: self.redirect_to.clone(),
314            verify_email: self.verify_email,
315            rules: self.rules.clone(),
316            on_registered: self.on_registered.clone(),
317            passwordless: self.passwordless.clone(),
318        }
319    }
320}
321
322impl Default for Auth {
323    fn default() -> Self {
324        Self::new()
325    }
326}
327
328impl Module for Auth {
329    fn name(&self) -> &'static str {
330        "auth"
331    }
332
333    fn migrations(&self) -> &'static [Migration] {
334        MIGRATIONS
335    }
336
337    fn register(&self, app: &mut crate::Registry) {
338        // For other ways of logging in (a social login): `auth::sign_in`.
339        app.auth = Some(Arc::new(self.settings()));
340        if self.notifications {
341            app.share(
342                "unread_notifications",
343                |ctx: crate::view::ViewContext| async move {
344                    match ctx.user {
345                        Some(user) => user.unread_notification_count(&ctx.state.db).await,
346                        None => Ok(0),
347                    }
348                },
349            );
350        }
351        // Schedule it, e.g. daily: `app.schedule().daily_at("03:00", …)`.
352        app.command(
353            "tokens:prune",
354            "Delete API tokens that expired more than a day ago",
355            |_args, state| async move {
356                let day = std::time::Duration::from_secs(24 * 60 * 60);
357                let pruned = super::prune_expired_tokens(&state.db, day).await?
358                    + super::DeviceToken::prune_expired(&state.db, day).await?
359                    + super::prune_expired_codes(&state.db).await?;
360                println!("Deleted {pruned} expired API tokens and login codes.");
361                Ok(())
362            },
363        );
364        app.command(
365            "notifications:prune",
366            "Delete notifications read more than --days ago (default 30)",
367            |args, state| async move {
368                let days: u64 = args
369                    .value("--days")
370                    .unwrap_or("30")
371                    .parse()
372                    .map_err(|_| crate::Error::BadRequest("--days must be a number".into()))?;
373                let age = std::time::Duration::from_secs(days * 24 * 60 * 60);
374                let pruned = super::prune_read_notifications(&state.db, age).await?;
375                println!("Deleted {pruned} notifications read more than {days} days ago.");
376                Ok(())
377            },
378        );
379    }
380
381    fn routes(&self) -> Routes {
382        let settings = Arc::new(self.settings());
383
384        let mut guest = Routes::new()
385            .get("/login", show_login)
386            .post("/login", store_login)
387            .name("login");
388        if self.registration {
389            guest = guest
390                .get("/register", show_register)
391                .post("/register", store_register)
392                .name("register");
393        }
394        let guest = guest
395            .get("/forgot-password", passwords::show_forgot)
396            .name("password.request")
397            .post("/forgot-password", passwords::send_link)
398            .name("password.email")
399            .get("/reset-password/{token}", passwords::show_reset)
400            .name("password.reset")
401            .post("/reset-password", passwords::reset)
402            .name("password.update")
403            .guest_only();
404        let verification = Routes::new()
405            .get("/verify-email", verification::notice)
406            .name("verification.notice")
407            .get("/verify-email/{id}/{hash}", verification::verify)
408            .name("verification.verify")
409            .post("/email/verification-notification", verification::resend)
410            .name("verification.send")
411            .require_auth();
412        let confirm = Routes::new()
413            .get("/confirm-password", super::account::show_confirm)
414            .post("/confirm-password", super::account::confirm)
415            .name("password.confirm")
416            .require_auth();
417        let mut routes = guest
418            .merge(verification)
419            .merge(confirm)
420            .merge(Routes::new().post("/logout", destroy).name("logout"));
421        if self.passwordless.magic_link.is_some() || self.passwordless.codes.is_some() {
422            routes = routes.merge(self.passwordless_routes());
423        }
424        if self.account {
425            routes = routes.merge(super::account::routes());
426        }
427        if self.notifications {
428            routes = routes.merge(super::inbox::routes());
429        }
430        routes.route_layer(Extension(settings))
431    }
432}
433
434impl Auth {
435    /// The magic link and login code pages, for guests.
436    fn passwordless_routes(&self) -> Routes {
437        use super::passwordless as p;
438        let mut routes = Routes::new();
439        if self.passwordless.magic_link.is_some() {
440            routes = routes
441                .get("/login/link", p::show_link_request)
442                .name("login.link.request")
443                .post("/login/link", p::send_link)
444                .name("login.link.send")
445                .get("/login/link/{token}", p::show_link)
446                .name("login.link.show")
447                .post("/login/link/{token}", p::consume_link)
448                .name("login.link.consume");
449        }
450        if self.passwordless.codes.is_some() {
451            routes = routes
452                .get("/login/code", p::show_code_request)
453                .name("login.code.request")
454                .post("/login/code", p::send_code)
455                .name("login.code.send")
456                .get("/login/code/verify", p::show_code_verify)
457                .post("/login/code/verify", p::check_code)
458                .name("login.code.verify")
459                .post("/login/code/resend", p::resend_code)
460                .name("login.code.resend");
461        }
462        routes.guest_only()
463    }
464}
465
466/// The built-in (English) texts, with the app's `renox.auth.*`
467/// translations for the request's language on top.
468pub(super) fn texts(lang: &Lang) -> Value {
469    let mut base = text();
470    if let Value::Object(map) = &mut base {
471        for (key, value) in lang.texts().iter() {
472            if let Some(key) = key.strip_prefix("renox.auth.") {
473                map.insert(key.to_owned(), Value::String(value.clone()));
474            }
475        }
476    }
477    base
478}
479
480/// A built-in message (e.g. `auth.failed`), translated if the app's lang file has it.
481pub(super) fn message(lang: &Lang, key: &str, params: &[(&str, String)]) -> String {
482    let template = crate::validation::template_for(Some(&lang.texts()), key);
483    crate::i18n::format(&template, params, None)
484}
485
486pub(super) fn after_login(state: &AppState, settings: &Settings, session: &Session) -> String {
487    let fallback = settings
488        .redirect_to
489        .clone()
490        .unwrap_or_else(|| state.url("home", &[]).unwrap_or_else(|_| "/".into()));
491    intended(session, fallback)
492}
493
494/// A full page load after logging in or out, since the layout changes.
495pub(super) fn go(htmx: &Htmx, to: String) -> Response {
496    if htmx.request {
497        HxRedirect(to).into_response()
498    } else {
499        Redirect::to(&to).into_response()
500    }
501}
502
503async fn show_login(Extension(settings): Extension<Arc<Settings>>, lang: Lang) -> View {
504    view(
505        "renox/auth/login.html",
506        context! {
507            registration => settings.registration,
508            magic_link => settings.passwordless.magic_link.is_some(),
509            login_codes => settings.passwordless.codes.is_some(),
510            text => texts(&lang),
511        },
512    )
513}
514
515#[derive(Deserialize, Serialize)]
516struct LoginForm {
517    email: String,
518    password: String,
519    remember: Option<String>,
520}
521
522/// Built-in labels for Renox's own forms; an app's lang file wins.
523pub(super) fn label(_v: &Validator, field: &'static str) -> &'static str {
524    match field {
525        "current_password" => "current password",
526        _ => field,
527    }
528}
529
530impl Validate for LoginForm {
531    fn rules(&self, v: &mut Validator) {
532        v.field("email", &super::user::normalize_email(&self.email))
533            .required()
534            .email();
535        let password = label(v, "password");
536        v.field("password", &self.password)
537            .fallback_label(password)
538            .required();
539    }
540}
541
542async fn store_login(
543    Extension(settings): Extension<Arc<Settings>>,
544    State(state): State<AppState>,
545    session: Session,
546    htmx: Htmx,
547    ClientIp(ip): ClientIp,
548    lang: Lang,
549    Valid(form): Valid<LoginForm>,
550) -> Result<Response> {
551    let failed = |key: &str, seconds: Option<u64>| {
552        let mut errors = Errors::new();
553        let seconds = seconds.map(|s| s.to_string()).unwrap_or_default();
554        errors.add("email", message(&lang, key, &[("seconds", seconds)]));
555        ValidationError::new(errors)
556            .with_input(&json!({ "email": form.email, "remember": form.remember }))
557    };
558
559    let address = ip.map(|ip| ip.to_string());
560    if let Some(seconds) = state.throttle.blocked_for(&form.email, ip).await {
561        let event = LockedOut {
562            email: form.email.clone(),
563            ip: address,
564            seconds,
565        };
566        announce(&state, event).await;
567        return Err(failed("auth.throttle", Some(seconds)).into());
568    }
569
570    let user = User::find_by_email(&state.db, &form.email).await?;
571    // Hash even when the email is unknown, so timing doesn't reveal which emails exist.
572    let hash = user
573        .as_ref()
574        .map_or_else(dummy_hash, |u| u.password.clone());
575    let valid = verify_password(&form.password, &hash).await;
576    let Some(mut user) = user.filter(|_| valid) else {
577        state.throttle.fail(&form.email, ip).await;
578        let event = LoginFailed {
579            email: form.email.clone(),
580            ip: address,
581        };
582        announce(&state, event).await;
583        return Err(failed("auth.failed", None).into());
584    };
585    user.rehash_if_needed(&state.db, &form.password).await?;
586
587    // A second step (two-factor authentication) first: the login waits in
588    // the session. The throttle isn't cleared until it's passed, so knowing
589    // the password doesn't reset the count of wrong codes.
590    if let Some(second) = &state.second_factor
591        && (second.required)(user.clone(), state.clone()).await?
592    {
593        let to = after_login(&state, &settings, &session);
594        super::second_factor::begin(
595            &session,
596            &user,
597            &form.email,
598            form.remember.is_some(),
599            to,
600            "password",
601        )?;
602        let challenge = state.url(&second.challenge, &[])?;
603        return Ok(go(&htmx, challenge));
604    }
605
606    state.throttle.clear(&form.email, ip).await;
607    let remember = form
608        .remember
609        .is_some()
610        .then_some(state.config.remember_lifetime);
611    login(&session, &user, remember)?;
612    super::account::mark_confirmed(&session)?;
613    let event = LoggedIn {
614        user_id: user.id,
615        ip: address,
616        via: "password".into(),
617    };
618    announce(&state, event).await;
619    Ok(go(&htmx, after_login(&state, &settings, &session)))
620}
621
622async fn show_register(lang: Lang) -> View {
623    view(
624        "renox/auth/register.html",
625        context! { text => texts(&lang) },
626    )
627}
628
629#[derive(Deserialize)]
630struct RegisterForm {
631    name: String,
632    email: String,
633    password: String,
634    password_confirmation: Option<String>,
635}
636
637impl Validate for RegisterForm {
638    fn rules(&self, v: &mut Validator) {
639        let (name, password) = (label(v, "name"), label(v, "password"));
640        v.field("name", &self.name)
641            .fallback_label(name)
642            .required()
643            .max(255);
644        // Checked as it will be stored, so `unique` ignores case on every database.
645        v.field("email", &super::user::normalize_email(&self.email))
646            .required()
647            .email()
648            .max(255)
649            .unique("users", "email");
650        // Checked with the app's policy in `store_register`.
651        let _ = password;
652    }
653}
654
655async fn store_register(
656    Extension(settings): Extension<Arc<Settings>>,
657    State(state): State<AppState>,
658    session: Session,
659    htmx: Htmx,
660    lang: Lang,
661    req: axum::extract::Request,
662) -> Result<Response> {
663    let rules = settings.rules.clone();
664    let policy = settings.password.clone();
665    let validated = crate::validation::extract::validate_request(
666        req,
667        &state,
668        move |form: &RegisterForm, fields, v| {
669            let password = label(v, "password");
670            v.field("password", &form.password)
671                .fallback_label(password)
672                .required()
673                .password(&policy)
674                .confirmed(&form.password_confirmation);
675            if let Some(rules) = &rules {
676                rules(
677                    &Registration {
678                        fields: fields.clone(),
679                    },
680                    v,
681                );
682            }
683        },
684    )
685    .await;
686    let (form, fields) = match validated {
687        Ok(validated) => validated,
688        Err(rejection) => return Ok(rejection),
689    };
690    let user = match User::register(&state.db, &form.name, &form.email, &form.password).await {
691        Ok(user) => user,
692        // Two sign-ups with one email at the same moment: the database's
693        // unique index stops the second, which gets the `unique` rule's answer.
694        Err(err) if err.is_unique_violation() => {
695            let template = crate::validation::template_for(Some(&lang.texts()), "unique");
696            let mut errors = Errors::new();
697            errors.add("email", crate::validation::render(&template, "email", &[]));
698            return Err(ValidationError::new(errors)
699                .with_input(&json!({ "name": form.name, "email": form.email }))
700                .into());
701        }
702        Err(err) => return Err(err),
703    };
704    let user = match &settings.on_registered {
705        None => user,
706        Some(hook) => {
707            let id = user.id;
708            if let Err(err) = hook(state.clone(), user, Registration { fields }).await {
709                // Undo the sign-up, so the visitor can try again.
710                crate::db::sql("DELETE FROM users WHERE id = ?")
711                    .bind(id)
712                    .execute(&state.db)
713                    .await?;
714                return Err(err);
715            }
716            // Read it back with what the hook changed.
717            <User as crate::db::Model>::find_or_404(&state.db, id).await?
718        }
719    };
720    if settings.verify_email {
721        verification::send_verification(&state, &user).await?;
722    }
723    let event = Registered {
724        user_id: user.id,
725        email: user.email.clone(),
726    };
727    // A module whose second step every user must pass (not only the ones
728    // who set it up) gets it here too, as at the login page.
729    if let Some(second) = &state.second_factor
730        && (second.required)(user.clone(), state.clone()).await?
731    {
732        let to = after_login(&state, &settings, &session);
733        super::second_factor::begin(&session, &user, &user.email, false, to, "password")?;
734        announce(&state, event).await;
735        let challenge = state.url(&second.challenge, &[])?;
736        return Ok(go(&htmx, challenge));
737    }
738    login(&session, &user, None)?;
739    announce(&state, event).await;
740    Ok(go(&htmx, after_login(&state, &settings, &session)))
741}
742
743async fn destroy(
744    State(state): State<AppState>,
745    session: Session,
746    user: Option<AuthUser>,
747    htmx: Htmx,
748) -> Result<Response> {
749    logout(&state.db, &session).await?;
750    if let Some(user) = user {
751        announce(&state, LoggedOut { user_id: user.id }).await;
752    }
753    Ok(go(
754        &htmx,
755        state.url("home", &[]).unwrap_or_else(|_| "/".into()),
756    ))
757}
758
759/// Words on the built-in pages (English; apps translate them with
760/// `renox.auth.*` keys in their lang files).
761pub(super) fn text() -> Value {
762    let mut text = json!({
763        "login_title": "Log in",
764        "register_title": "Create an account",
765        "name": "Name",
766        "email": "Email",
767        "password": "Password",
768        "password_confirmation": "Confirm password",
769        "remember": "Remember me",
770        "login_button": "Log in",
771        "register_button": "Register",
772        "no_account": "No account yet?",
773        "have_account": "Already registered?",
774        "forgot_link": "Forgot your password?",
775        "forgot_title": "Forgot your password?",
776        "forgot_intro": "Enter your email and we'll send you a link to choose a new password.",
777        "send_link": "Email me a reset link",
778        "back_to_login": "Back to log in",
779        "reset_title": "Choose a new password",
780        "reset_button": "Reset password",
781        "reset_link_sent": "If that email has an account, a reset link is on its way.",
782        "reset_invalid": "This password reset link is invalid or has expired.",
783        "password_reset_done": "Your password has been reset. You can log in now.",
784        "verify_title": "Verify your email",
785        "verify_intro": "We've emailed you a link to verify your address. Didn't get it?",
786        "resend_button": "Send another link",
787        "logout": "Log out",
788        "verification_sent": "A new verification link has been sent.",
789        "verified": "Your email address is verified.",
790        "mail_reset_subject": "Reset your password",
791        "mail_reset_intro": "You asked to reset your password. Choose a new one with the button below.",
792        "mail_reset_outro": "The link works for 60 minutes. If you didn't ask for this, ignore this email.",
793        "mail_verify_subject": "Verify your email address",
794        "mail_verify_intro": "Please confirm that this is your email address.",
795        "mail_verify_outro": "The link works for 60 minutes.",
796        "account_title": "Your account",
797        "profile_title": "Profile",
798        "profile_saved": "Your profile is saved.",
799        "email_unverified": "Your new email address isn't verified yet: check your inbox.",
800        "save": "Save",
801        "password_title": "Change password",
802        "set_password_title": "Set a password",
803        "set_password_intro": "You log in with a linked account. Choose a password to log in with it too.",
804        "current_password": "Current password",
805        "new_password": "New password",
806        "password_changed": "Your password is changed. Your other devices are logged out.",
807        "other_devices_title": "Other devices",
808        "other_devices_intro": "Log out everywhere else, e.g. on a phone you lost.",
809        "other_devices_button": "Log out other devices",
810        "other_devices_logged_out": "Your other devices are logged out.",
811        "delete_title": "Delete account",
812        "delete_intro": "Your account and its data are deleted for good.",
813        "delete_button": "Delete my account",
814        "delete_confirm": "Delete your account for good?",
815        "confirm_title": "Confirm your password",
816        "confirm_intro": "This is a secure area. Please confirm your password to continue.",
817        "confirm_button": "Confirm",
818    });
819    if let (Value::Object(base), Value::Object(more)) = (&mut text, passwordless_text()) {
820        base.extend(more);
821    }
822    text
823}
824
825/// Words on the passwordless login pages and mails.
826fn passwordless_text() -> Value {
827    json!({
828        "login_via_link": "Email me a login link",
829        "login_via_code": "Log in with a code",
830        "login_link_title": "Log in with a link",
831        "login_link_intro": "Enter your email address and we'll send you a link that logs you in. No password needed.",
832        "login_link_button": "Email me a link",
833        "login_link_sent": "If that address can log in, a link is on its way.",
834        "login_link_invalid": "This login link is invalid or has expired.",
835        "login_link_confirm_title": "Log in",
836        "login_link_confirm_intro": "You are about to log in as",
837        "login_link_confirm_button": "Log in",
838        "mail_link_subject": "Your login link",
839        "mail_link_intro": "Use the button below to log in. No password needed.",
840        "mail_link_outro": "The link works once and expires in :minutes minutes. If you didn't ask for it, ignore this email.",
841        "login_code_title": "Log in with a code",
842        "login_code_identifier": "Email or phone number",
843        "login_code_intro": "Enter how we know you and we'll send you a one-time code.",
844        "login_code_channel": "Send it by",
845        "login_code_button": "Send me a code",
846        "login_code_sent": "If that account can log in, a code is on its way.",
847        "login_code_verify_title": "Enter your code",
848        "login_code_verify_intro": "We sent a code by :channel. It expires in :minutes minutes.",
849        "login_code_input": "Code",
850        "login_code_verify_button": "Log in",
851        "login_code_wrong": "That code is wrong or has expired.",
852        "login_code_burned": "Too many wrong codes. Request a new one.",
853        "login_code_expired": "That code has expired. Request a new one.",
854        "login_code_resend": "Send a new code",
855        "login_code_other_way": "Send it another way:",
856        "login_code_message": "Your :app login code is :code. It expires in :minutes minutes.",
857        "mail_code_subject": "Your login code",
858        "mail_code_intro": "Your login code is:",
859        "mail_code_outro": "It expires in :minutes minutes. If you didn't ask for it, ignore this email.",
860        "channel_mail": "Email",
861        "channel_sms": "SMS",
862        "channel_whatsapp": "WhatsApp",
863    })
864}