Compare commits

..

5 commits

Author SHA1 Message Date
bd54980d0f ✨ (user): Integra pagetop-mail y valida identidades
- Envía por correo la recuperación de contraseña y, con
  `require_email_verification`, la verificación de cuentas nuevas, que
  se confirma con un botón (los escáneres de correo abren los enlaces).
- Nueva política de nombres de usuario (`identity_policy`): sin `@`, sin
  distinguir mayúsculas y sin nombres confusables (UTS #39). Email
  validado con pagetop-mail.
- Tokens de un solo uso atómicos y ligados al usuario. Los correos a
  direcciones sin verificar no incluyen datos elegidos por el usuario.
- Bloqueo por intentos fallidos con su ventana de recuento, y el mismo
  tiempo de respuesta exista o no la cuenta. Argon2 en `spawn_blocking`.
- Límites de longitud del nombre visible y de los roles, y botones sólo
  con el permiso que exigen. Más correcciones en formularios y búsqueda.
2026-10-19 07:57:38 +02:00
a9b1b3b2a3 🐛 (mail): No exige remitente con transport log 2026-10-19 07:44:59 +02:00
f2a052d66c 🔒️ (response): Evita "open redirect" en Waypoint
El navegador descarta tabuladores y saltos de línea de una URL, así que
`/\t/evil.example` acababa en `//evil.example` (open redirect).
2026-10-19 07:23:25 +02:00
b2e9fe79e8 📝 (auth): Documenta la convención de las claves
Los ejemplos usaban `.` como separador, pero las extensiones usan
`extensión:permiso` (p. ej. `user:admin_users`). Se unifican ejemplos y
se documenta la convención en `Permission::key()`.
2026-10-19 07:20:50 +02:00
ce9635f9a8 ✨ (mail): Añade la extensión pagetop-mail
Envío de correo con lettre: plantillas con diseño y versión en texto,
adjuntos, transporte configurable y vista previa de mensajes.
2026-10-19 01:06:20 +02:00
59 changed files with 5608 additions and 362 deletions

408
Cargo.lock generated
View file

@ -127,6 +127,150 @@ dependencies = [
"password-hash", "password-hash",
] ]
[[package]]
name = "async-channel"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35"
dependencies = [
"concurrent-queue",
"event-listener 2.5.3",
"futures-core",
]
[[package]]
name = "async-channel"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
dependencies = [
"concurrent-queue",
"event-listener-strategy",
"futures-core",
"pin-project-lite",
]
[[package]]
name = "async-executor"
version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
dependencies = [
"async-task",
"concurrent-queue",
"fastrand",
"futures-lite",
"pin-project-lite",
"slab",
]
[[package]]
name = "async-global-executor"
version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c"
dependencies = [
"async-channel 2.5.0",
"async-executor",
"async-io",
"async-lock",
"blocking",
"futures-lite",
"once_cell",
]
[[package]]
name = "async-io"
version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"
dependencies = [
"autocfg",
"cfg-if",
"concurrent-queue",
"futures-io",
"futures-lite",
"parking",
"polling",
"rustix",
"slab",
"windows-sys 0.61.2",
]
[[package]]
name = "async-lock"
version = "3.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
dependencies = [
"event-listener 5.4.1",
"event-listener-strategy",
"pin-project-lite",
]
[[package]]
name = "async-process"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"
dependencies = [
"async-channel 2.5.0",
"async-io",
"async-lock",
"async-signal",
"async-task",
"blocking",
"cfg-if",
"event-listener 5.4.1",
"futures-lite",
"rustix",
]
[[package]]
name = "async-signal"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"
dependencies = [
"async-io",
"async-lock",
"atomic-waker",
"cfg-if",
"futures-core",
"futures-io",
"rustix",
"signal-hook-registry",
"slab",
"windows-sys 0.61.2",
]
[[package]]
name = "async-std"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c8e079a4ab67ae52b7403632e4618815d6db36d2a010cfe41b02c1b1578f93b"
dependencies = [
"async-channel 1.9.0",
"async-global-executor",
"async-io",
"async-lock",
"async-process",
"crossbeam-utils",
"futures-channel",
"futures-core",
"futures-io",
"futures-lite",
"gloo-timers",
"kv-log-macro",
"log",
"memchr",
"once_cell",
"pin-project-lite",
"pin-utils",
"slab",
"wasm-bindgen-futures",
]
[[package]] [[package]]
name = "async-stream" name = "async-stream"
version = "0.3.6" version = "0.3.6"
@ -149,6 +293,12 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "async-task"
version = "4.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
[[package]] [[package]]
name = "async-trait" name = "async-trait"
version = "0.1.89" version = "0.1.89"
@ -239,6 +389,12 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
[[package]] [[package]]
name = "base64ct" name = "base64ct"
version = "1.8.3" version = "1.8.3"
@ -281,6 +437,19 @@ dependencies = [
"hybrid-array", "hybrid-array",
] ]
[[package]]
name = "blocking"
version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa"
dependencies = [
"async-channel 2.5.0",
"async-task",
"futures-io",
"futures-lite",
"piper",
]
[[package]] [[package]]
name = "bstr" name = "bstr"
version = "1.12.1" version = "1.12.1"
@ -684,6 +853,22 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "email-encoding"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "420b9da095f052ea597503e39073b5b3c522f7db933fbac202d91d24492693fd"
dependencies = [
"base64 0.23.1",
"memchr",
]
[[package]]
name = "email_address"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449"
[[package]] [[package]]
name = "equivalent" name = "equivalent"
version = "1.0.2" version = "1.0.2"
@ -711,6 +896,12 @@ dependencies = [
"windows-sys 0.48.0", "windows-sys 0.48.0",
] ]
[[package]]
name = "event-listener"
version = "2.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"
[[package]] [[package]]
name = "event-listener" name = "event-listener"
version = "5.4.1" version = "5.4.1"
@ -722,6 +913,16 @@ dependencies = [
"pin-project-lite", "pin-project-lite",
] ]
[[package]]
name = "event-listener-strategy"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
dependencies = [
"event-listener 5.4.1",
"pin-project-lite",
]
[[package]] [[package]]
name = "fastrand" name = "fastrand"
version = "2.4.1" version = "2.4.1"
@ -925,6 +1126,19 @@ version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"
[[package]]
name = "futures-lite"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"
dependencies = [
"fastrand",
"futures-core",
"futures-io",
"parking",
"pin-project-lite",
]
[[package]] [[package]]
name = "futures-sink" name = "futures-sink"
version = "0.3.32" version = "0.3.32"
@ -1018,6 +1232,18 @@ dependencies = [
"regex-syntax", "regex-syntax",
] ]
[[package]]
name = "gloo-timers"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994"
dependencies = [
"futures-channel",
"futures-core",
"js-sys",
"wasm-bindgen",
]
[[package]] [[package]]
name = "grass" name = "grass"
version = "0.13.4" version = "0.13.4"
@ -1101,6 +1327,12 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hermit-abi"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
[[package]] [[package]]
name = "hex" name = "hex"
version = "0.4.3" version = "0.4.3"
@ -1134,6 +1366,17 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "hostname"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd"
dependencies = [
"cfg-if",
"libc",
"windows-link",
]
[[package]] [[package]]
name = "http" name = "http"
version = "1.4.1" version = "1.4.1"
@ -1459,6 +1702,15 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "kv-log-macro"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0de8b303297635ad57c9f5059fd9cee7a47f8e8daa09df0fcd07dd39fb22977f"
dependencies = [
"log",
]
[[package]] [[package]]
name = "lasso" name = "lasso"
version = "0.7.3" version = "0.7.3"
@ -1483,6 +1735,35 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "lettre"
version = "0.11.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2c646bd5cc763b1087b15493e29a64be6147ba8f19342004fa52048ee596eae"
dependencies = [
"async-std",
"async-trait",
"base64 0.23.1",
"email-encoding",
"email_address",
"fastrand",
"futures-io",
"futures-util",
"hostname",
"httpdate",
"idna",
"mime",
"native-tls",
"nom",
"percent-encoding",
"quoted_printable",
"socket2",
"tokio",
"tokio-native-tls",
"url",
"uuid",
]
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.186" version = "0.2.186"
@ -1544,6 +1825,9 @@ name = "log"
version = "0.4.29" version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
dependencies = [
"value-bag",
]
[[package]] [[package]]
name = "matchers" name = "matchers"
@ -1641,6 +1925,15 @@ dependencies = [
"tempfile", "tempfile",
] ]
[[package]]
name = "nom"
version = "8.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "nu-ansi-term" name = "nu-ansi-term"
version = "0.50.3" version = "0.50.3"
@ -1882,6 +2175,18 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "pagetop-mail"
version = "0.1.0"
dependencies = [
"lettre",
"mime_guess",
"pagetop",
"serde",
"thiserror",
"tokio",
]
[[package]] [[package]]
name = "pagetop-minimal" name = "pagetop-minimal"
version = "0.1.0" version = "0.1.0"
@ -1921,6 +2226,7 @@ dependencies = [
"pagetop", "pagetop",
"pagetop-admin", "pagetop-admin",
"pagetop-htmx", "pagetop-htmx",
"pagetop-mail",
"pagetop-seaorm", "pagetop-seaorm",
"rand_core", "rand_core",
"serde", "serde",
@ -1928,6 +2234,10 @@ dependencies = [
"serde_qs", "serde_qs",
"sha2 0.11.0", "sha2 0.11.0",
"thiserror", "thiserror",
"tokio",
"unicode-ident",
"unicode-normalization",
"unicode-security",
] ]
[[package]] [[package]]
@ -2097,6 +2407,23 @@ version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "pin-utils"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13bee6c73da26345c729282832b60b0363cf3dd9f4bfd81d8551b7a1c889a113"
[[package]]
name = "piper"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"
dependencies = [
"atomic-waker",
"fastrand",
"futures-io",
]
[[package]] [[package]]
name = "pkcs1" name = "pkcs1"
version = "0.7.5" version = "0.7.5"
@ -2130,6 +2457,20 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
[[package]]
name = "polling"
version = "3.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
dependencies = [
"cfg-if",
"concurrent-queue",
"hermit-abi",
"pin-project-lite",
"rustix",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "potential_utf" name = "potential_utf"
version = "0.1.5" version = "0.1.5"
@ -2223,6 +2564,12 @@ dependencies = [
"proc-macro2", "proc-macro2",
] ]
[[package]]
name = "quoted_printable"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "478e0585659a122aa407eb7e3c0e1fa51b1d8a870038bd29f0cf4a8551eea972"
[[package]] [[package]]
name = "r-efi" name = "r-efi"
version = "6.0.0" version = "6.0.0"
@ -2754,13 +3101,13 @@ version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6"
dependencies = [ dependencies = [
"base64", "base64 0.22.1",
"bytes", "bytes",
"chrono", "chrono",
"crc", "crc",
"crossbeam-queue", "crossbeam-queue",
"either", "either",
"event-listener", "event-listener 5.4.1",
"futures-core", "futures-core",
"futures-intrusive", "futures-intrusive",
"futures-io", "futures-io",
@ -2829,7 +3176,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526" checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526"
dependencies = [ dependencies = [
"atoi", "atoi",
"base64", "base64 0.22.1",
"bitflags", "bitflags",
"byteorder", "byteorder",
"bytes", "bytes",
@ -2872,7 +3219,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46" checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46"
dependencies = [ dependencies = [
"atoi", "atoi",
"base64", "base64 0.22.1",
"bitflags", "bitflags",
"byteorder", "byteorder",
"chrono", "chrono",
@ -3140,6 +3487,16 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "tokio-native-tls"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2"
dependencies = [
"native-tls",
"tokio",
]
[[package]] [[package]]
name = "tokio-stream" name = "tokio-stream"
version = "0.1.18" version = "0.1.18"
@ -3428,6 +3785,22 @@ version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"
[[package]]
name = "unicode-script"
version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee"
[[package]]
name = "unicode-security"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e4ddba1535dd35ed8b61c52166b7155d7f4e4b8847cec6f48e71dc66d8b5e50"
dependencies = [
"unicode-normalization",
"unicode-script",
]
[[package]] [[package]]
name = "unicode-xid" name = "unicode-xid"
version = "0.2.6" version = "0.2.6"
@ -3458,12 +3831,29 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "uuid"
version = "1.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606"
dependencies = [
"getrandom 0.4.2",
"js-sys",
"wasm-bindgen",
]
[[package]] [[package]]
name = "valuable" name = "valuable"
version = "0.1.1" version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
[[package]]
name = "value-bag"
version = "1.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2799ffb329a792ecfd902b71306c8a815a6ef1c0470fa9953a6aa4d4cecbe511"
[[package]] [[package]]
name = "vcpkg" name = "vcpkg"
version = "0.2.15" version = "0.2.15"
@ -3529,6 +3919,16 @@ dependencies = [
"wasm-bindgen-shared", "wasm-bindgen-shared",
] ]
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.71"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96492d0d3ffba25305a7dc88720d250b1401d7edca02cc3bcd50633b424673b8"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]] [[package]]
name = "wasm-bindgen-macro" name = "wasm-bindgen-macro"
version = "0.2.121" version = "0.2.121"

View file

@ -11,6 +11,7 @@ members = [
"extensions/pagetop-bootsier", "extensions/pagetop-bootsier",
"extensions/pagetop-htmx", "extensions/pagetop-htmx",
"extensions/pagetop-admin", "extensions/pagetop-admin",
"extensions/pagetop-mail",
"extensions/pagetop-seaorm", "extensions/pagetop-seaorm",
"extensions/pagetop-user", "extensions/pagetop-user",
] ]
@ -40,6 +41,7 @@ grass = "0.13"
indexmap = "2.14" indexmap = "2.14"
indoc = "2.0" indoc = "2.0"
itoa = "1.0" itoa = "1.0"
lettre = { version = "0.11", default-features = false }
mime_guess = "2.0" mime_guess = "2.0"
minify-js = "0.6" minify-js = "0.6"
parking_lot = "0.12" parking_lot = "0.12"
@ -64,6 +66,9 @@ tracing = "0.1"
tracing-appender = "0.2" tracing-appender = "0.2"
tracing-subscriber = { version = "0.3", features = ["json", "env-filter"] } tracing-subscriber = { version = "0.3", features = ["json", "env-filter"] }
unic-langid = { version = "0.9", features = ["macros"] } unic-langid = { version = "0.9", features = ["macros"] }
unicode-ident = "1.0"
unicode-normalization = "0.1"
unicode-security = "0.1"
url = "2.5" url = "2.5"
# Helpers # Helpers
pagetop-build = { version = "0.3", path = "helpers/pagetop-build" } pagetop-build = { version = "0.3", path = "helpers/pagetop-build" }
@ -75,6 +80,7 @@ pagetop-admin = { version = "0.1", path = "extensions/pagetop-admin" }
pagetop-aliner = { version = "0.1", path = "extensions/pagetop-aliner" } pagetop-aliner = { version = "0.1", path = "extensions/pagetop-aliner" }
pagetop-bootsier = { version = "0.1", path = "extensions/pagetop-bootsier" } pagetop-bootsier = { version = "0.1", path = "extensions/pagetop-bootsier" }
pagetop-htmx = { version = "0.1", path = "extensions/pagetop-htmx" } pagetop-htmx = { version = "0.1", path = "extensions/pagetop-htmx" }
pagetop-mail = { version = "0.1", path = "extensions/pagetop-mail" }
pagetop-seaorm = { version = "0.0", path = "extensions/pagetop-seaorm" } pagetop-seaorm = { version = "0.0", path = "extensions/pagetop-seaorm" }
pagetop-user = { version = "0.1", path = "extensions/pagetop-user" } pagetop-user = { version = "0.1", path = "extensions/pagetop-user" }
# PageTop # PageTop

View file

@ -113,17 +113,72 @@ db_host = "localhost" # Servidor de la base de datos (mysql/postgr
max_pool_size = 5 # Número máximo de conexiones simultáneas. max_pool_size = 5 # Número máximo de conexiones simultáneas.
# **< pagetop-mail >********************************************************************************
[mail]
transport = "log" # Entrega de los correos:
# "smtp" -> servidor SMTP ([mail.smtp]).
# "sendmail" -> programa sendmail local ([mail.sendmail]).
# "file" -> un archivo .eml por correo ([mail.file]).
# "log" -> se escriben en las trazas, sin enviarlos.
# "memory" -> se guardan en memoria (sólo pruebas).
#from = "Mi Aplicación <no-reply@example.com>"
# Remitente por defecto, con o sin nombre. Sin valor, cada
# correo debe indicar el suyo para enviarse (salvo con "log").
# Los de pagetop-user no lo indican: configúralo siempre.
#reply_to = "soporte@example.com" # Dirección de respuesta por defecto.
#redirect_to = "pruebas@example.com" # Entrega todos los correos sólo a esta dirección, sin
# cambiar sus cabeceras (entornos de pruebas o preproducción).
#base_url = "https://example.com" # URL pública para los enlaces de los correos. Sin valor,
# http://{bind_address}:{bind_port} (sólo para desarrollo).
previews = false # Vistas previas de los correos en /mail/preview. Sólo en
# desarrollo: cualquiera que conozca la ruta las ve.
[mail.smtp] # Servidor SMTP (transport = "smtp").
host = "localhost" # Servidor.
#port = 587 # Puerto. Sin valor -> 465 con "tls", 587 con "starttls" y 25
# en otro caso.
security = "starttls" # Cifrado de la conexión:
# "none" -> sin cifrar (servidores de pruebas).
# "opportunistic" -> STARTTLS si el servidor lo ofrece.
# "starttls" -> STARTTLS obligatorio (puerto 587).
# "tls" -> cifrada desde el inicio (puerto 465).
#username = "no-reply@example.com" # Usuario. Sin valor, no se autentica.
#password = "secreto" # Contraseña. Mejor en config/local.toml (no se versiona).
#hello_name = "example.com" # Nombre para EHLO. Sin valor, el nombre del equipo.
timeout_secs = 60 # Espera máxima de cada orden al servidor, en segundos.
pool_max_size = 10 # Conexiones abiertas como máximo, reutilizadas entre envíos.
accept_invalid_certs = false # Acepta certificados no válidos. PELIGROSO: sólo pruebas.
[mail.sendmail] # Programa sendmail (transport = "sendmail").
#command = "/usr/sbin/sendmail" # Programa. Sin valor, "sendmail" del PATH.
[mail.file] # Archivos de correo (transport = "file").
dir = "mail" # Directorio de los archivos .eml. Se crea si no existe.
# **< pagetop-user >******************************************************************************** # **< pagetop-user >********************************************************************************
[user] [user]
allow_registration = true # Permite que los visitantes creen su propia cuenta. allow_registration = true # Permite que los visitantes creen su propia cuenta.
require_email_verification = false # Las cuentas nuevas quedan pendientes ("Pending") en lugar require_email_verification = false # Las cuentas nuevas quedan pendientes ("Pending") en lugar
# de activas hasta verificar el correo. # de activas hasta confirmar la dirección desde el enlace del
# correo de verificación que se envía al registrarse.
identity_policy = "strict" # Nombres de usuario que se aceptan:
# "strict" -> letras ASCII sin tildes, dígitos, ".", "_"
# y "-", de 3 a 32 caracteres.
# "unicode" -> letras y dígitos de cualquier alfabeto, sin
# mezclarlos, ".", "_" y "-", de 3 a 32.
# "permissive" -> como "unicode", más espacios simples, "'"
# y "+", de 3 a 60.
# Con cualquiera: nunca "@", sin distinguir mayúsculas y sin
# nombres que se confundan con otro existente.
max_failed_logins = 5 # Intentos fallidos de acceso antes de bloquear la cuenta. max_failed_logins = 5 # Intentos fallidos seguidos que bloquean la cuenta. 0 -> nunca.
failed_login_window_secs = 900 # Ventana de recuento de intentos fallidos (15 minutos). failed_login_window_secs = 900 # Segundos desde el último fallo en los que el siguiente se
# Reservada: todavía no tiene efecto. # suma al recuento (15 minutos); si no, empieza de nuevo.
locked_for_secs = 600 # Duración del bloqueo de la cuenta en segundos (10 minutos). locked_for_secs = 600 # Duración del bloqueo de la cuenta en segundos (10 minutos).
# Después se dispone otra vez de todos los intentos.
login_strict = false # Dificulta que el navegador recuerde o autorrellene las login_strict = false # Dificulta que el navegador recuerde o autorrellene las
# credenciales en el formulario de acceso. # credenciales en el formulario de acceso.
@ -144,15 +199,16 @@ write_interval_secs = 60 # Segundos mínimos entre dos escrituras de
# bajarlo (o 0, escribir siempre) da más precisión si las # bajarlo (o 0, escribir siempre) da más precisión si las
# sesiones caducan tras pocos minutos sin uso. # sesiones caducan tras pocos minutos sin uso.
[user.password] # Contraseñas, cifradas con Argon2id. [user.password] # Contraseñas, cifradas con Argon2id. Si cambia cualquiera de
argon2_m_cost = 19456 # Coste de memoria en KiB. Si cambia, las contraseñas se # los tres costes, cada contraseña se vuelve a cifrar en el
# vuelven a cifrar en el siguiente acceso de cada usuario. # siguiente acceso de su usuario.
argon2_m_cost = 19456 # Coste de memoria en KiB.
argon2_t_cost = 2 # Coste de tiempo (número de iteraciones). argon2_t_cost = 2 # Coste de tiempo (número de iteraciones).
argon2_p_cost = 1 # Grado de paralelismo (número de hilos). argon2_p_cost = 1 # Grado de paralelismo (número de hilos).
min_length = 8 # Longitud mínima de las contraseñas. min_length = 8 # Longitud mínima de las contraseñas, en caracteres.
[user.seed] # Primer administrador, creado si no existe ningún usuario. [user.seed] # Primer administrador, creado si no existe ningún usuario.
admin_username = "admin" # Nombre de usuario. admin_username = "admin" # Nombre de usuario, válido según "identity_policy".
admin_email = "admin@example.com" # Correo electrónico. admin_email = "admin@example.com" # Correo electrónico.
#admin_password = "cambiar" # Contraseña. Sin valor -> se genera una aleatoria y se #admin_password = "cambiar" # Contraseña. Sin valor -> se genera una aleatoria y se
# muestra una sola vez por la salida estándar al crearlo. # muestra una sola vez por la salida estándar al crearlo.

View file

@ -0,0 +1,35 @@
[package]
name = "pagetop-mail"
version = "0.1.0"
description = """
Envío de correo electrónico para aplicaciones PageTop: SMTP, plantillas, HTML y adjuntos.
"""
categories = ["email", "web-programming"]
keywords = ["pagetop", "email", "smtp", "mail", "ssr"]
repository.workspace = true
homepage.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
[dependencies]
pagetop.workspace = true
mime_guess.workspace = true
serde.workspace = true
thiserror.workspace = true
tokio.workspace = true
[dependencies.lettre]
workspace = true
features = [
"builder",
"hostname",
"pool",
"smtp-transport",
"sendmail-transport",
"file-transport",
"tokio1-native-tls",
]

View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 Manuel Cillero
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Manuel Cillero
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,228 @@
<div align="center">
<h1>PageTop Mail</h1>
<p>Envío de correo electrónico para aplicaciones <strong>PageTop</strong>.</p>
[![Doc API](https://img.shields.io/docsrs/pagetop-mail?label=Doc%20API&style=for-the-badge&logo=Docs.rs)](https://docs.rs/pagetop-mail)
[![Crates.io](https://img.shields.io/crates/v/pagetop-mail.svg?style=for-the-badge&logo=ipfs)](https://crates.io/crates/pagetop-mail)
[![Descargas](https://img.shields.io/crates/d/pagetop-mail.svg?label=Descargas&style=for-the-badge&logo=transmission)](https://crates.io/crates/pagetop-mail)
[![Licencia](https://img.shields.io/badge/license-MIT%2FApache-blue.svg?label=Licencia&style=for-the-badge)](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-mail#licencia)
</div>
Envía correos en texto plano y HTML, con archivos adjuntos e imágenes incrustadas, por SMTP, con el
programa *sendmail* o a archivos `.eml`, todo configurado en los archivos TOML de la aplicación.
Los correos pueden crearse con plantillas que traducen sus textos al idioma del destinatario, y
comparten un diseño HTML común que la aplicación puede cambiar. Para las pruebas, los correos pueden
guardarse en memoria en lugar de enviarse.
## Sobre PageTop
[PageTop](https://docs.rs/pagetop) es un entorno de desarrollo que reivindica la esencia de la web
clásica para crear soluciones web SSR (*renderizadas en el servidor*) modulares, extensibles y
configurables, basadas en HTML, CSS y JavaScript.
## Guía rápida
**Añade la dependencia** a tu `Cargo.toml`:
```toml
[dependencies]
pagetop-mail = "..."
```
**Declara la extensión** en tu aplicación o en la extensión que envíe correos:
```rust,no_run
use pagetop::prelude::*;
struct MyApp;
#[async_trait]
impl Extension for MyApp {
fn dependencies(&self) -> Vec<ExtensionRef> {
vec![&pagetop_mail::Mail]
}
}
```
**Configura el envío** en la sección `[mail]` (todas las opciones en el módulo `config`):
```toml
[mail]
transport = "smtp"
from = "Mi Aplicación <no-reply@example.com>"
base_url = "https://example.com"
[mail.smtp]
host = "smtp.example.com"
security = "starttls" # "none", "opportunistic", "starttls" o "tls".
username = "no-reply@example.com"
password = "secreto" # Mejor en config/local.toml, que no se versiona.
```
Sin configurar, los correos se escriben en las trazas en lugar de enviarse (`transport = "log"`),
así que una aplicación en desarrollo nunca envía correo real por error. La configuración se valida
al arrancar: un ajuste no válido detiene la aplicación con un mensaje que indica el problema.
**Envía un correo** con `Email`:
```rust,no_run
use pagetop::prelude::*;
use pagetop_mail::prelude::*;
async fn notify() -> Result<(), MailError> {
Email::new()
.with_to("Ana Pérez <ana@example.com>")
.with_subject("Tu pedido ha salido")
.with_text("Tu pedido 1234 ha salido hoy.")
.with_html(html! {
p { "Tu pedido " strong { "1234" } " ha salido hoy." }
})
.send()
.await
}
```
`Email::send()` espera a que el correo se entregue; `Email::send_later()` lo envía en segundo plano
y registra en las trazas los errores.
## Plantillas
Una `MailTemplate` genera el asunto, el HTML y el texto de un correo a partir de sus datos, con los
textos traducidos mediante `Lc` al idioma del contexto que recibe. Así, cada extensión define sus
correos como tipos propios, y el mismo correo se envía a cada destinatario en su idioma:
```rust,no_run
use pagetop::prelude::*;
use pagetop_mail::prelude::*;
include_locales!(LOCALES_SHOP);
struct Welcome {
name: String,
}
impl MailTemplate for Welcome {
fn subject(&self, cx: &Context) -> String {
Lc::t("welcome-subject", &LOCALES_SHOP).lookup(cx).unwrap_or_default()
}
fn html(&self, cx: &Context) -> Option<Markup> {
let greeting = Lc::t("welcome-greeting", &LOCALES_SHOP).with_arg("name", self.name.clone());
Some(html! {
p { (greeting.using(cx)) }
p {
a href=(absolute_url("/shop")) { (Lc::t("welcome-visit", &LOCALES_SHOP).using(cx)) }
}
})
}
}
async fn welcome(request: HttpRequest) -> Result<(), MailError> {
// El contexto de la petición: el correo sale en el idioma de quien se acaba de registrar.
let cx = Context::new(request);
Email::from_template(&Welcome { name: "Ana".to_string() }, &cx)
.with_to("ana@example.com")
.send()
.await
}
```
## Enlaces en los correos
Los enlaces de un correo deben ser absolutos. `absolute_url()` antepone a una ruta la URL pública de
la aplicación, que se configura en `mail.base_url`. No se deduce de la petición, porque la cabecera
`Host` la elige el cliente y un atacante podría hacer que los enlaces de un correo de recuperación
de contraseña apuntaran a su propio servidor.
## Adjuntos e imágenes incrustadas
Un `Attachment` se crea con un contenido en memoria o leyendo un archivo, y su tipo MIME se deduce
del nombre. Con `Attachment::with_content_id()` se incrusta en el HTML, que lo muestra con `cid:`:
```rust,no_run
use pagetop::prelude::*;
use pagetop_mail::prelude::*;
async fn report(png: Vec<u8>) -> Result<(), MailError> {
Email::new()
.with_to("ana@example.com")
.with_subject("Informe")
.with_html(html! { img src="cid:logo" alt="Logo"; p { "Adjunto el informe." } })
.with_attachment(Attachment::new("logo.png", png).with_content_id("logo"))
.with_attachment(Attachment::from_path("informes/octubre.pdf").await?)
.send()
.await
}
```
## Diseño común del HTML
El HTML de los correos es sólo su contenido: al enviarlos se envuelve en un documento con un diseño
sobrio y neutro. La aplicación puede darle su propia imagen a **todos** los correos, incluidos los
de otras extensiones, registrando la acción `RenderMailLayout`.
## Vistas previas en el navegador
Con `previews = true` en `[mail]` (sólo en desarrollo), `/mail/preview` lista los correos que las
extensiones declaran con la acción `DeclareMailPreviews`, y muestra cada uno con datos de ejemplo:
cabeceras, HTML con el diseño común, texto plano y adjuntos, sin enviar nada.
## Texto plano automático
Si un correo sólo tiene HTML, al enviarlo se genera su texto plano a partir del contenido: bloques
separados por líneas, listas con guiones, y la dirección de cada enlace entre paréntesis.
## Transportes
Se elige en `mail.transport`:
| Valor | Uso |
|--------------|-----------------------------------------------------------------------------|
| `"smtp"` | Producción. Servidor SMTP con conexiones reutilizables y cifrado TLS. |
| `"sendmail"` | Producción, con un servidor de correo local (Postfix, Exim...). |
| `"file"` | Desarrollo. Guarda cada correo como `.eml` para abrirlo con un cliente. |
| `"log"` | Por defecto. Escribe los correos en las trazas, sin enviarlos. |
| `"memory"` | Pruebas. Guarda los correos en memoria para comprobarlos con `outbox`. |
En entornos de pruebas con datos reales, `mail.redirect_to` entrega todos los correos a una sola
dirección, sin cambiar sus cabeceras.
Para probar el envío SMTP en desarrollo sin enviar correo real, un servidor como
[Mailpit](https://mailpit.axllent.org) recoge los correos y los muestra en el navegador:
```toml
[mail]
transport = "smtp"
[mail.smtp]
host = "localhost"
port = 1025
security = "none"
```
## Créditos
Este *crate* se apoya en [lettre](https://lettre.rs), la biblioteca de correo de referencia en Rust,
distribuida bajo licencia [MIT](https://github.com/lettre/lettre/blob/master/LICENSE).
## Advertencia
**PageTop** es un proyecto personal para aprender [Rust](https://www.rust-lang.org/es) y conocer su
ecosistema. Su API está sujeta a cambios frecuentes. No se recomienda su uso en producción, al menos
hasta que se libere la versión **1.0.0**.
## Licencia
El código está disponible bajo una doble licencia:
* **Licencia MIT**
([LICENSE-MIT](LICENSE-MIT) o también https://opensource.org/licenses/MIT)
* **Licencia Apache, Versión 2.0**
([LICENSE-APACHE](LICENSE-APACHE) o también https://www.apache.org/licenses/LICENSE-2.0)
Puedes elegir la licencia que prefieras. Este enfoque de doble licencia es el estándar de facto en
el ecosistema Rust.

View file

@ -0,0 +1,8 @@
# Configuración para las pruebas de este crate: guarda los correos en memoria en lugar de enviarlos
# y ofrece las vistas previas.
[mail]
transport = "memory"
from = "PageTop Tests <tests@example.com>"
base_url = "https://example.com/"
previews = true

View file

@ -0,0 +1,141 @@
//! Archivos adjuntos e imágenes incrustadas ([`Attachment`]).
use pagetop::prelude::*;
use crate::MailError;
use lettre::message::SinglePart;
use lettre::message::header::ContentType;
use std::fmt;
use std::path::Path;
use std::sync::Arc;
/// Archivo adjunto a un correo, o recurso incrustado en su HTML.
///
/// Un adjunto tiene un nombre de archivo, un contenido y un tipo MIME. Si no se indica el tipo, se
/// deduce de la extensión del nombre (`informe.pdf` -> `application/pdf`) y, si no se reconoce, se
/// usa `application/octet-stream`.
///
/// Con [`with_content_id()`](Self::with_content_id) el adjunto pasa a ser un recurso **incrustado**
/// (*inline*), típicamente una imagen que el HTML del correo muestra con `src="cid:..."`. Sólo se
/// incrustan si el correo tiene HTML; si no, se envían como adjuntos normales.
///
/// El contenido se comparte al clonar el adjunto, sin copiarlo.
///
/// # Ejemplos
///
/// ```rust,no_run
/// # use pagetop::prelude::*;
/// # use pagetop_mail::prelude::*;
/// # async fn example(pdf: Vec<u8>, png: Vec<u8>) -> Result<(), MailError> {
/// // Un PDF generado por la aplicación.
/// let report = Attachment::new("informe.pdf", pdf);
///
/// // Un archivo del disco, con el nombre del archivo.
/// let terms = Attachment::from_path("docs/condiciones.pdf").await?;
///
/// // Un logotipo que el HTML muestra con <img src="cid:logo">.
/// let logo = Attachment::new("logo.png", png).with_content_id("logo");
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Getters)]
pub struct Attachment {
/// Nombre del archivo, tal como lo verá el destinatario.
filename: String,
/// Tipo MIME del contenido.
content_type: String,
/// Identificador del recurso incrustado, si lo es.
content_id: Option<String>,
#[getters(skip)]
body: Arc<[u8]>,
}
impl Attachment {
/// Crea un adjunto con el nombre de archivo y el contenido dados.
pub fn new(filename: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
let filename = filename.into();
let content_type = mime_guess::from_path(&filename)
.first_or_octet_stream()
.essence_str()
.to_owned();
Attachment {
filename,
content_type,
content_id: None,
body: Arc::from(body.into()),
}
}
/// Crea un adjunto leyendo un archivo del disco. El nombre del adjunto es el del archivo.
///
/// Falla con [`MailError::ReadAttachment`] si no se puede leer el archivo.
pub async fn from_path(path: impl AsRef<Path>) -> Result<Self, MailError> {
let path = path.as_ref();
let body = tokio::fs::read(path)
.await
.map_err(|source| MailError::ReadAttachment {
path: path.to_path_buf(),
source,
})?;
let filename = path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
Ok(Attachment::new(filename, body))
}
/// Contenido del adjunto.
pub fn body(&self) -> &[u8] {
&self.body
}
/// Indica si es un recurso incrustado en el HTML del correo.
pub fn is_inline(&self) -> bool {
self.content_id.is_some()
}
// Convierte el adjunto en una parte del mensaje. Los recursos incrustados sólo se incrustan si
// `inline` es `true` (el correo tiene HTML).
pub(crate) fn to_part(&self, inline: bool) -> Result<SinglePart, MailError> {
let content_type = ContentType::parse(&self.content_type)
.map_err(|_| MailError::InvalidContentType(self.content_type.clone()))?;
let attachment = match self.content_id() {
Some(id) if inline => lettre::message::Attachment::new_inline(id.clone()),
_ => lettre::message::Attachment::new(self.filename.clone()),
};
Ok(attachment.body(self.body.to_vec(), content_type))
}
}
// Muestra el tamaño del contenido en lugar de sus bytes.
impl fmt::Debug for Attachment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Attachment")
.field("filename", &self.filename)
.field("content_type", &self.content_type)
.field("content_id", &self.content_id)
.field("body_len", &self.body.len())
.finish()
}
}
#[builder_impl]
impl Attachment {
// **< Attachment BUILDER >*********************************************************************
/// Cambia el tipo MIME deducido del nombre del archivo (p. ej. `"text/csv; charset=utf-8"`).
/// Si no es válido, el envío falla con [`MailError::InvalidContentType`].
pub fn with_content_type(mut self, content_type: impl Into<String>) -> Self {
self.content_type = content_type.into();
self
}
/// Incrusta el adjunto en el HTML del correo con el identificador dado, que el HTML usa como
/// `cid:<identificador>` (p. ej. `img src="cid:logo"`).
pub fn with_content_id(mut self, content_id: impl Into<String>) -> Self {
self.content_id = Some(content_id.into());
self
}
}

View file

@ -0,0 +1,173 @@
//! Ajustes de configuración de `pagetop-mail`.
//!
//! Ejemplo:
//!
//! ```toml
//! [mail]
//! transport = "smtp"
//! from = "Mi Aplicación <no-reply@example.com>"
//! base_url = "https://example.com"
//!
//! [mail.smtp]
//! host = "smtp.example.com"
//! security = "starttls"
//! username = "no-reply@example.com"
//! password = "secreto"
//! ```
//!
//! Uso:
//!
//! ```rust,no_run
//! use pagetop_mail::config;
//!
//! assert_eq!(config::SETTINGS.smtp.host, "smtp.example.com");
//! ```
//!
//! Todas las opciones, con su valor por defecto, se documentan en [`MailSettings`] y sus
//! subsecciones ([`SmtpSettings`], [`SendmailSettings`] y [`FileSettings`]).
//!
//! Consulta [`pagetop::config`] para ver cómo PageTop lee los archivos de configuración y aplica
//! los valores a los ajustes.
use pagetop::prelude::*;
use serde::Deserialize;
/// Ajustes de la sección `[mail]`, cargados al arrancar la aplicación.
pub static SETTINGS: LazySettings<MailSettings> = LazySettings::new();
/// Sección **`[mail]`** de la configuración.
#[settings(section = "mail")]
pub struct MailSettings {
/// Cómo se entregan los correos. Por defecto se escriben en las trazas sin enviarlos
/// ([`MailTransport::Log`]), para que una aplicación sin configurar no envíe correo real.
pub transport: MailTransport,
/// Remitente por defecto, para los correos que no indican uno propio. Admite la dirección sola
/// (`"no-reply@example.com"`) o con nombre (`"Mi Aplicación <no-reply@example.com>"`). Sin
/// valor, cada correo debe indicar su remitente para enviarse, salvo con
/// [`MailTransport::Log`], que sólo lo escribe en las trazas. Los correos de otras extensiones,
/// como los de `pagetop-user`, no lo indican: conviene configurarlo siempre.
pub from: Option<String>,
/// Dirección de respuesta por defecto, para los correos que no indican una propia.
pub reply_to: Option<String>,
/// Si se indica, todos los correos se entregan **sólo** a esta dirección en lugar de a sus
/// destinatarios, que se conservan en las cabeceras (`To`, `Cc`). Pensado para entornos de
/// pruebas o preproducción con datos reales.
pub redirect_to: Option<String>,
/// URL pública de la aplicación (p. ej. `"https://example.com"`), para construir los enlaces
/// absolutos de los correos con [`absolute_url()`](crate::absolute_url). Debe empezar por
/// `http://` o `https://`, o la aplicación no arranca. Sin valor, se usa la dirección y el
/// puerto de escucha del servidor (`http://localhost:8080`), que sólo sirve en desarrollo.
pub base_url: Option<String>,
/// Ofrece en `/mail/preview` las vistas previas de los correos que declaran las extensiones
/// (ver [`preview`](crate::preview)). Sólo para desarrollo: muestra las plantillas a cualquiera
/// que conozca la ruta.
#[default = false]
pub previews: bool,
/// Servidor SMTP, en la subsección `[mail.smtp]`.
pub smtp: SmtpSettings,
/// Programa *sendmail*, en la subsección `[mail.sendmail]`.
pub sendmail: SendmailSettings,
/// Archivos de correo, en la subsección `[mail.file]`.
pub file: FileSettings,
}
/// Forma de entregar los correos. Usado en [`MailSettings::transport`].
#[derive(AutoDefault, Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum MailTransport {
/// Envía los correos a un servidor SMTP (ver [`SmtpSettings`]).
Smtp,
/// Entrega los correos al programa *sendmail* local (ver [`SendmailSettings`]).
Sendmail,
/// Guarda cada correo como un archivo `.eml` en un directorio (ver [`FileSettings`]). Útil en
/// desarrollo para abrirlos con un cliente de correo.
File,
/// No envía nada: escribe en las trazas el remitente, los destinatarios, el asunto y el texto
/// de cada correo. Es el valor por defecto. No debe usarse en producción, porque los textos
/// pueden incluir enlaces con *tokens* de un solo uso.
#[default]
Log,
/// No envía nada: guarda los correos en memoria para que las pruebas los consulten con
/// [`outbox`](crate::outbox).
Memory,
}
/// Subsección **`[mail.smtp]`** de la configuración.
#[settings]
pub struct SmtpSettings {
/// Servidor SMTP.
#[default = "localhost"]
pub host: String,
/// Puerto del servidor. Sin valor, el habitual según la seguridad: 465 con
/// [`SmtpSecurity::Tls`], 587 con [`SmtpSecurity::StartTls`] y 25 en los demás casos.
pub port: Option<u16>,
/// Cifrado de la conexión.
#[default(SmtpSecurity::StartTls)]
pub security: SmtpSecurity,
/// Usuario para autenticarse en el servidor. Sin valor, no se autentica.
pub username: Option<String>,
/// Contraseña del usuario. Conviene guardarla en `config/local.toml`, que no se versiona.
pub password: Option<String>,
/// Nombre con el que se presenta la aplicación al servidor (`EHLO`). Sin valor, el nombre del
/// equipo.
pub hello_name: Option<String>,
/// Segundos de espera máxima de cada orden al servidor.
#[default = 60]
pub timeout_secs: u64,
/// Número máximo de conexiones abiertas con el servidor, que se reutilizan entre envíos.
#[default = 10]
pub pool_max_size: u32,
/// Acepta certificados no válidos (caducados, autofirmados o de otro servidor). **Peligroso**:
/// sólo para servidores de pruebas, nunca en producción.
#[default = false]
pub accept_invalid_certs: bool,
}
/// Cifrado de la conexión SMTP. Usado en [`SmtpSettings::security`].
#[derive(AutoDefault, Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SmtpSecurity {
/// Sin cifrado. Sólo para servidores locales o de pruebas (p. ej. Mailpit o MailHog).
None,
/// Cifra con `STARTTLS` si el servidor lo ofrece y, si no, envía sin cifrar.
Opportunistic,
/// Exige `STARTTLS`: empieza sin cifrar y cifra antes de autenticarse. Es el valor por
/// defecto (puerto 587).
#[default]
StartTls,
/// Conexión cifrada desde el principio, también llamada SMTPS (puerto 465).
Tls,
}
/// Subsección **`[mail.sendmail]`** de la configuración.
#[settings]
pub struct SendmailSettings {
/// Programa que recibe los correos. Sin valor, `sendmail` del `PATH`.
pub command: Option<String>,
}
/// Subsección **`[mail.file]`** de la configuración.
#[settings]
pub struct FileSettings {
/// Directorio donde se guardan los correos. Se crea al arrancar si no existe.
#[default = "mail"]
pub dir: String,
}
#[cfg(test)]
mod tests {
use super::{MailSettings, config};
// `reference.toml` documents every option; with unknown keys rejected, loading it proves that
// it only documents keys that exist, with values of the right type.
const REFERENCE: &str = include_str!("../../../config/reference.toml");
#[test]
fn reference_toml_documents_only_existing_keys() {
config::load_from_str::<MailSettings>(REFERENCE).unwrap();
}
}

View file

@ -0,0 +1,351 @@
//! Correos electrónicos ([`Email`]).
use pagetop::prelude::*;
use crate::{Attachment, MailError, MailTemplate, Mailbox, layout, text, transport};
use lettre::Message;
use lettre::message::{MultiPart, MultiPartBuilder, SinglePart};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
/// Correo electrónico listo para enviar.
///
/// Se compone con los métodos `with_*()` y se envía con [`send()`](Self::send), que espera a que
/// el servidor lo acepte, o con [`send_later()`](Self::send_later), que lo envía en segundo plano.
/// También puede crearse a partir de una plantilla con [`from_template()`](Self::from_template).
///
/// Un correo puede tener texto plano, HTML o ambos (los clientes de correo muestran el que
/// prefieran), además de archivos adjuntos y de imágenes incrustadas en el HTML (ver
/// [`Attachment`]). El HTML de [`with_html()`](Self::with_html) es sólo el contenido: al enviarlo
/// se envuelve en el diseño común de los correos (ver
/// [`RenderMailLayout`](crate::RenderMailLayout)).
///
/// Si sólo tiene HTML, al enviarlo se genera el texto plano a partir de él, porque los filtros de
/// correo no deseado penalizan los correos sin texto. Escríbelo con
/// [`with_text()`](Self::with_text) sólo si el generado no queda bien.
///
/// Si no se indica el remitente o la dirección de respuesta se usan los de la configuración
/// (`mail.from` y `mail.reply_to`). Las direcciones se validan al enviar.
///
/// # Ejemplo
///
/// ```rust,no_run
/// use pagetop::prelude::*;
/// use pagetop_mail::prelude::*;
///
/// async fn send_report(pdf: Vec<u8>) -> Result<(), MailError> {
/// Email::new()
/// .with_to("Ana Pérez <ana@example.com>")
/// .with_cc("contabilidad@example.com")
/// .with_subject("Informe mensual")
/// .with_text("Adjunto el informe del mes.")
/// .with_html(html! {
/// p { "Adjunto el " strong { "informe" } " del mes." }
/// })
/// .with_attachment(Attachment::new("informe.pdf", pdf))
/// .send()
/// .await
/// }
/// ```
#[derive(AutoDefault, Clone, Debug, Getters)]
pub struct Email {
/// Remitente, si se ha indicado.
from: Option<Mailbox>,
/// Dirección de respuesta, si se ha indicado.
reply_to: Option<Mailbox>,
/// Destinatarios principales.
to: Vec<Mailbox>,
/// Destinatarios en copia.
cc: Vec<Mailbox>,
/// Destinatarios en copia oculta.
bcc: Vec<Mailbox>,
/// Asunto.
subject: String,
/// Texto plano, si lo tiene.
text: Option<String>,
/// HTML, si lo tiene: el contenido mientras se compone y el documento completo una vez
/// enviado.
html: Option<Markup>,
#[getters(skip)]
html_is_document: bool,
/// Archivos adjuntos e imágenes incrustadas.
attachments: Vec<Attachment>,
#[getters(skip)]
langid: Option<&'static LanguageIdentifier>,
}
impl Email {
/// Crea un correo vacío.
pub fn new() -> Self {
Email::default()
}
/// Crea un correo con el asunto, el HTML y el texto de una plantilla, generados en el idioma
/// del contexto, que también es el del diseño común del HTML.
///
/// El contexto puede ser el de la petición en curso, si el destinatario es quien la hace (p.
/// ej. al registrarse), o uno creado para el destinatario con
/// `Context::default().with_langid(...)`.
pub fn from_template(template: &impl MailTemplate, cx: &Context) -> Self {
let mut email = Email::new()
.with_subject(template.subject(cx))
.with_langid(cx);
if let Some(html) = template.html(cx) {
email.alter_html(html);
}
if let Some(text) = template.text(cx) {
email.alter_text(text);
}
email
}
/// Idioma del correo: el indicado con [`with_langid()`](Self::with_langid) o, si no, el idioma
/// por defecto de la aplicación.
pub fn langid(&self) -> &'static LanguageIdentifier {
self.langid.unwrap_or_else(Locale::default_langid)
}
/// Envía el correo y espera a que se entregue (al servidor SMTP, a *sendmail*, al archivo...).
///
/// Falla si alguna dirección o el tipo MIME de algún adjunto no son válidos, si falta el
/// remitente (salvo con `transport = "log"`, que sólo escribe el correo en las trazas) o los
/// destinatarios, o si la entrega falla.
pub async fn send(self) -> Result<(), MailError> {
transport::deliver(self).await
}
/// Envía el correo en segundo plano, sin esperar al resultado. Si falla, se registra el error
/// en las trazas.
///
/// La respuesta de la petición no espera al servidor de correo, y su tiempo no revela si el
/// correo se ha enviado (p. ej., si existe la cuenta para la que se pide recuperar la
/// contraseña). A cambio, los correos pendientes se pierden si la aplicación se detiene antes
/// de enviarlos, y no se reintentan si fallan.
pub fn send_later(self) {
tokio::spawn(async move {
let subject = self.subject.clone();
if let Err(err) = self.send().await {
let mut message = err.to_string();
let mut source = std::error::Error::source(&err);
while let Some(cause) = source {
message.push_str(": ");
message.push_str(&cause.to_string());
source = cause.source();
}
trace::error!("Cannot send email \"{subject}\": {message}");
}
});
}
// Completa el correo antes de enviarlo: remitente y dirección de respuesta por defecto, el
// texto plano a partir del HTML si no tiene, y el documento HTML con el diseño común. El texto
// se genera antes del diseño para que no incluya su pie.
pub(crate) fn prepare(mut self, from: Option<&Mailbox>, reply_to: Option<&Mailbox>) -> Self {
if self.from.is_none() {
self.from = from.cloned();
}
if self.reply_to.is_none() {
self.reply_to = reply_to.cloned();
}
if self.text.is_none()
&& let Some(html) = &self.html
{
self.text = Some(text::html_to_text(html.as_str()));
}
if !self.html_is_document
&& let Some(content) = self.html.take()
{
let cx = Context::default().with_langid(&Locale::Resolved(self.langid()));
self.html = Some(layout::render(&cx, &self, &content));
self.html_is_document = true;
}
self
}
// Compone el mensaje MIME:
//
// - texto y HTML -> multipart/alternative (el texto primero, el preferido al final).
// - HTML con imágenes incrustadas -> multipart/related con el HTML y las imágenes.
// - con adjuntos -> multipart/mixed con el cuerpo y los adjuntos.
pub(crate) fn to_message(&self) -> Result<Message, MailError> {
let from = self.from.as_ref().ok_or(MailError::MissingFrom)?;
if self.to.is_empty() && self.cc.is_empty() && self.bcc.is_empty() {
return Err(MailError::NoRecipients);
}
let from = from.to_lettre()?;
let mut builder = Message::builder()
.message_id(Some(message_id(from.email.domain())))
.from(from)
.subject(self.subject.as_str());
if let Some(reply_to) = &self.reply_to {
builder = builder.reply_to(reply_to.to_lettre()?);
}
for mailbox in &self.to {
builder = builder.to(mailbox.to_lettre()?);
}
for mailbox in &self.cc {
builder = builder.cc(mailbox.to_lettre()?);
}
for mailbox in &self.bcc {
builder = builder.bcc(mailbox.to_lettre()?);
}
let has_html = self.html.is_some();
let html = match &self.html {
Some(html) => {
let part = SinglePart::html(html.as_str().to_owned());
let mut inline = self.attachments.iter().filter(|a| a.is_inline()).peekable();
if inline.peek().is_some() {
let images = inline
.map(|attachment| attachment.to_part(true).map(Part::Single))
.collect::<Result<Vec<_>, _>>()?;
Some(multipart(MultiPart::related(), Part::Single(part), images))
} else {
Some(Part::Single(part))
}
}
None => None,
};
let text = self
.text
.as_ref()
.map(|t| Part::Single(SinglePart::plain(t.clone())));
let mut body = match (text, html) {
(Some(text), Some(html)) => multipart(MultiPart::alternative(), text, vec![html]),
(Some(part), None) | (None, Some(part)) => part,
(None, None) => Part::Single(SinglePart::plain(String::new())),
};
let attached = self
.attachments
.iter()
.filter(|a| !(has_html && a.is_inline()))
.map(|attachment| attachment.to_part(false).map(Part::Single))
.collect::<Result<Vec<_>, _>>()?;
if !attached.is_empty() {
body = multipart(MultiPart::mixed(), body, attached);
}
match body {
Part::Single(part) => builder.singlepart(part),
Part::Multi(multi) => builder.multipart(multi),
}
.map_err(MailError::Build)
}
}
#[builder_impl]
impl Email {
// **< Email BUILDER >**************************************************************************
/// Establece el remitente, en lugar del de la configuración (`mail.from`).
pub fn with_from(mut self, from: impl Into<Mailbox>) -> Self {
self.from = Some(from.into());
self
}
/// Establece la dirección de respuesta, en lugar de la de la configuración (`mail.reply_to`).
pub fn with_reply_to(mut self, reply_to: impl Into<Mailbox>) -> Self {
self.reply_to = Some(reply_to.into());
self
}
/// Añade un destinatario principal (`To`).
pub fn with_to(mut self, to: impl Into<Mailbox>) -> Self {
self.to.push(to.into());
self
}
/// Añade un destinatario en copia (`Cc`).
pub fn with_cc(mut self, cc: impl Into<Mailbox>) -> Self {
self.cc.push(cc.into());
self
}
/// Añade un destinatario en copia oculta (`Bcc`), que no ven los demás destinatarios.
pub fn with_bcc(mut self, bcc: impl Into<Mailbox>) -> Self {
self.bcc.push(bcc.into());
self
}
/// Establece el asunto. Los caracteres de control (saltos de línea, tabuladores...) se cambian
/// por espacios: el asunto puede incluir datos de usuario, y una cabecera es una sola línea.
pub fn with_subject(mut self, subject: impl Into<String>) -> Self {
self.subject = subject
.into()
.chars()
.map(|c| if c.is_control() { ' ' } else { c })
.collect();
self
}
/// Establece el texto plano.
pub fn with_text(mut self, text: impl Into<String>) -> Self {
self.text = Some(text.into());
self
}
/// Establece el contenido HTML, que al enviarse se envuelve en el diseño común de los correos.
pub fn with_html(mut self, content: Markup) -> Self {
self.html = Some(content);
self.html_is_document = false;
self
}
/// Establece el documento HTML completo, que se envía tal cual, sin el diseño común. Útil si el
/// HTML se genera con otra herramienta.
pub fn with_html_document(mut self, document: Markup) -> Self {
self.html = Some(document);
self.html_is_document = true;
self
}
/// Añade un archivo adjunto o una imagen incrustada.
pub fn with_attachment(mut self, attachment: Attachment) -> Self {
self.attachments.push(attachment);
self
}
/// Establece el idioma del correo, que usa el diseño común del HTML.
pub fn with_langid(mut self, language: &impl LangId) -> Self {
self.langid = Some(language.langid());
self
}
}
// Genera la cabecera `Message-ID`, que los filtros de correo no deseado penalizan si falta. Sólo
// tiene que ser única: la hora, un contador y el proceso lo garantizan sin depender del azar. El
// dominio es el del remitente y no el nombre del equipo, que en un contenedor suele ser aleatorio y
// también penalizan algunos filtros.
fn message_id(domain: &str) -> String {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_nanos());
let count = COUNTER.fetch_add(1, Ordering::Relaxed);
format!("<{nanos:x}.{count:x}.{:x}@{domain}>", std::process::id())
}
// Parte de un mensaje MIME: simple o compuesta por otras partes.
enum Part {
Single(SinglePart),
Multi(MultiPart),
}
// Compone una parte del tipo dado con `first` y el resto de partes, en ese orden.
fn multipart(kind: MultiPartBuilder, first: Part, rest: Vec<Part>) -> Part {
let mut multi = match first {
Part::Single(part) => kind.singlepart(part),
Part::Multi(multi) => kind.multipart(multi),
};
for part in rest {
multi = match part {
Part::Single(part) => multi.singlepart(part),
Part::Multi(part) => multi.multipart(part),
};
}
Part::Multi(multi)
}

View file

@ -0,0 +1,68 @@
//! Errores de `pagetop-mail`.
use std::path::PathBuf;
/// Errores al configurar el envío de correo o al componer y enviar un correo.
#[derive(Debug, thiserror::Error)]
pub enum MailError {
/// Una dirección de correo no es válida.
#[error("invalid email address \"{address}\"")]
InvalidAddress {
/// Dirección tal como se indicó.
address: String,
/// Motivo del error.
#[source]
source: lettre::address::AddressError,
},
/// Un ajuste de la sección `[mail]` no es válido.
#[error("invalid mail setting \"{key}\"")]
InvalidSetting {
/// Clave del ajuste, p. ej. `"mail.from"`.
key: &'static str,
/// Motivo del error.
#[source]
source: Box<MailError>,
},
/// Una URL no es absoluta (no empieza por `http://` ni `https://`).
#[error("invalid URL \"{0}\": it must start with http:// or https://")]
InvalidUrl(String),
/// El correo no indica remitente y no hay uno por defecto (`mail.from`).
#[error("email has no sender: set mail.from or use Email::with_from()")]
MissingFrom,
/// El correo no tiene ningún destinatario (`To`, `Cc` ni `Bcc`).
#[error("email has no recipients")]
NoRecipients,
/// El tipo de contenido de un adjunto no es un tipo MIME válido.
#[error("invalid content type \"{0}\" for attachment")]
InvalidContentType(String),
/// No se puede leer el archivo de un adjunto.
#[error("cannot read attachment \"{path}\"")]
ReadAttachment {
/// Ruta del archivo.
path: PathBuf,
/// Error devuelto al leerlo.
#[source]
source: std::io::Error,
},
/// No se puede crear el directorio de los archivos de correo (`mail.file.dir`).
#[error("cannot create mail directory \"{path}\"")]
CreateDir {
/// Ruta del directorio.
path: PathBuf,
/// Error devuelto al crearlo.
#[source]
source: std::io::Error,
},
/// No se puede componer el mensaje.
#[error("cannot build email message")]
Build(#[source] lettre::error::Error),
/// Error de conexión, de cifrado o de entrega con el servidor SMTP.
#[error("SMTP error")]
Smtp(#[source] lettre::transport::smtp::Error),
/// Error al entregar el correo al programa *sendmail*.
#[error("sendmail error")]
Sendmail(#[source] lettre::transport::sendmail::Error),
/// Error al guardar el correo como archivo.
#[error("cannot write email file")]
File(#[source] lettre::transport::file::Error),
}

View file

@ -0,0 +1,151 @@
//! Diseño común del HTML de los correos y acción [`RenderMailLayout`] para cambiarlo.
use pagetop::prelude::*;
use crate::{Email, LOCALES_MAIL};
use std::ops::ControlFlow;
/// Tipo de función que genera el documento HTML completo de un correo.
///
/// Recibe:
///
/// - `cx`: contexto con el idioma del correo, para traducir los textos del diseño.
/// - `email`: el correo, p. ej. para usar su asunto como título del documento.
/// - `content`: el contenido HTML del correo, que el diseño debe incluir sin modificar.
pub type FnRenderMailLayout = fn(cx: &Context, email: &Email, content: &Markup) -> Markup;
/// Acción para cambiar el diseño común del HTML de los correos.
///
/// Todos los correos con contenido HTML ([`Email::with_html()`] o una
/// [`MailTemplate`](crate::MailTemplate)) se envuelven al enviarlos en un documento HTML completo:
/// cabecera, estilos y pie. El diseño por defecto es sobrio y neutro: un recuadro blanco de hasta
/// 600 píxeles de ancho sobre fondo gris, con el nombre de la aplicación al pie.
///
/// Una aplicación (o una extensión) registra esta acción para dar a **todos** los correos su propia
/// imagen, incluidos los que envían otras extensiones como `pagetop-user`. Si hay varias, se aplica
/// sólo la de menor peso.
///
/// Los clientes de correo ignoran las hojas de estilo externas y muchos ignoran también los estilos
/// del `<head>`: lo seguro es escribir los estilos en línea (`style="..."`) y maquetar con tablas.
///
/// # Ejemplo
///
/// ```rust,no_run
/// use pagetop::prelude::*;
/// use pagetop_mail::prelude::*;
///
/// fn my_layout(cx: &Context, email: &Email, content: &Markup) -> Markup {
/// html! {
/// (DOCTYPE)
/// html lang=(cx.langid().to_string()) {
/// head {
/// meta charset="utf-8";
/// title { (email.subject()) }
/// }
/// body style="font-family: Georgia, serif;" {
/// img src="https://example.com/logo.png" alt="Example" width="120";
/// (content)
/// }
/// }
/// }
/// }
///
/// struct MyApp;
///
/// #[async_trait]
/// impl Extension for MyApp {
/// fn dependencies(&self) -> Vec<ExtensionRef> {
/// vec![&pagetop_mail::Mail]
/// }
///
/// fn actions(&self) -> Vec<ActionBox> {
/// actions![RenderMailLayout::new(my_layout)]
/// }
/// }
/// ```
///
/// [`Email::with_html()`]: crate::Email::with_html
pub struct RenderMailLayout {
f: FnRenderMailLayout,
weight: Weight,
}
impl ActionDispatcher for RenderMailLayout {
fn weight(&self) -> Weight {
self.weight
}
}
impl RenderMailLayout {
/// Registra una función que genera el documento HTML de los correos.
pub fn new(f: FnRenderMailLayout) -> Self {
RenderMailLayout { f, weight: 0 }
}
/// Opcional. Si varias extensiones registran esta acción, se aplica la de menor peso. Se pueden
/// usar valores negativos.
pub fn with_weight(mut self, value: Weight) -> Self {
self.weight = value;
self
}
}
// Genera el documento HTML del correo con la acción de menor peso o, sin ninguna, con el diseño por
// defecto.
pub(crate) fn render(cx: &Context, email: &Email, content: &Markup) -> Markup {
let mut document = None;
try_dispatch_actions(|action: &RenderMailLayout| {
document = Some((action.f)(cx, email, content));
ControlFlow::Break(())
});
document.unwrap_or_else(|| default_layout(cx, email, content))
}
// Estilos en línea del diseño por defecto.
const PAGE_STYLE: &str = "margin: 0; padding: 0; background-color: #f4f4f5;";
const CARD_STYLE: &str = "max-width: 600px; background-color: #ffffff; border-radius: 6px;";
const CONTENT_STYLE: &str = concat!(
"font-family: -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; ",
"padding: 32px; font-size: 16px; line-height: 1.5; color: #1f2937;"
);
const FOOTER_STYLE: &str = concat!(
"font-family: -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; ",
"margin: 16px 0 0; font-size: 12px; color: #6b7280;"
);
fn default_layout(cx: &Context, email: &Email, content: &Markup) -> Markup {
html! {
(DOCTYPE)
html lang=(cx.langid().to_string()) {
head {
meta charset="utf-8";
meta name="viewport" content="width=device-width, initial-scale=1";
meta name="color-scheme" content="light";
title { (email.subject()) }
}
body style=(PAGE_STYLE) {
table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
style=(PAGE_STYLE)
{
tr {
td align="center" style="padding: 24px 12px;" {
table role="presentation" width="100%" cellpadding="0" cellspacing="0"
border="0" style=(CARD_STYLE)
{
tr {
td style=(CONTENT_STYLE) { (content) }
}
}
p style=(FOOTER_STYLE) {
(Lc::t("mail_footer", &LOCALES_MAIL)
.with_arg("app", &global::SETTINGS.app.name)
.using(cx))
}
}
}
}
}
}
}
}

View file

@ -0,0 +1,339 @@
/*!
<div align="center">
<h1>PageTop Mail</h1>
<p>Envío de correo electrónico para aplicaciones <strong>PageTop</strong>.</p>
[![Doc API](https://img.shields.io/docsrs/pagetop-mail?label=Doc%20API&style=for-the-badge&logo=Docs.rs)](https://docs.rs/pagetop-mail)
[![Crates.io](https://img.shields.io/crates/v/pagetop-mail.svg?style=for-the-badge&logo=ipfs)](https://crates.io/crates/pagetop-mail)
[![Descargas](https://img.shields.io/crates/d/pagetop-mail.svg?label=Descargas&style=for-the-badge&logo=transmission)](https://crates.io/crates/pagetop-mail)
[![Licencia](https://img.shields.io/badge/license-MIT%2FApache-blue.svg?label=Licencia&style=for-the-badge)](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-mail#licencia)
</div>
Envía correos en texto plano y HTML, con archivos adjuntos e imágenes incrustadas, por SMTP, con el
programa *sendmail* o a archivos `.eml`, todo configurado en los archivos TOML de la aplicación.
Los correos pueden crearse con plantillas que traducen sus textos al idioma del destinatario, y
comparten un diseño HTML común que la aplicación puede cambiar. Para las pruebas, los correos pueden
guardarse en memoria en lugar de enviarse.
## Sobre PageTop
[PageTop](https://docs.rs/pagetop) es un entorno de desarrollo que reivindica la esencia de la web
clásica para crear soluciones web SSR (*renderizadas en el servidor*) modulares, extensibles y
configurables, basadas en HTML, CSS y JavaScript.
## Guía rápida
**Añade la dependencia** a tu `Cargo.toml`:
```toml
[dependencies]
pagetop-mail = "..."
```
**Declara la extensión** en tu aplicación o en la extensión que envíe correos:
```rust,no_run
use pagetop::prelude::*;
struct MyApp;
#[async_trait]
impl Extension for MyApp {
fn dependencies(&self) -> Vec<ExtensionRef> {
vec![&pagetop_mail::Mail]
}
}
```
**Configura el envío** en la sección `[mail]` (todas las opciones en [`config`]):
```toml
[mail]
transport = "smtp"
from = "Mi Aplicación <no-reply@example.com>"
base_url = "https://example.com"
[mail.smtp]
host = "smtp.example.com"
security = "starttls" # "none", "opportunistic", "starttls" o "tls".
username = "no-reply@example.com"
password = "secreto" # Mejor en config/local.toml, que no se versiona.
```
Sin configurar, los correos se escriben en las trazas en lugar de enviarse (`transport = "log"`),
así que una aplicación en desarrollo nunca envía correo real por error. La configuración se valida
al arrancar: un ajuste no válido detiene la aplicación con un mensaje que indica el problema.
**Envía un correo** con [`Email`]:
```rust,no_run
use pagetop::prelude::*;
use pagetop_mail::prelude::*;
async fn notify() -> Result<(), MailError> {
Email::new()
.with_to("Ana Pérez <ana@example.com>")
.with_subject("Tu pedido ha salido")
.with_text("Tu pedido 1234 ha salido hoy.")
.with_html(html! {
p { "Tu pedido " strong { "1234" } " ha salido hoy." }
})
.send()
.await
}
```
[`Email::send()`] espera a que el correo se entregue; [`Email::send_later()`] lo envía en segundo
plano y registra en las trazas los errores.
## Plantillas
Una [`MailTemplate`] genera el asunto, el HTML y el texto de un correo a partir de sus datos, con
los textos traducidos mediante [`Lc`] al idioma del contexto que recibe. Así, cada extensión
define sus correos como tipos propios, y el mismo correo se envía a cada destinatario en su idioma:
```rust,no_run
# use pagetop::prelude::*;
# use pagetop_mail::prelude::*;
# include_locales!(LOCALES_SHOP);
struct Welcome {
name: String,
}
impl MailTemplate for Welcome {
fn subject(&self, cx: &Context) -> String {
Lc::t("welcome-subject", &LOCALES_SHOP).lookup(cx).unwrap_or_default()
}
fn html(&self, cx: &Context) -> Option<Markup> {
let greeting = Lc::t("welcome-greeting", &LOCALES_SHOP).with_arg("name", self.name.clone());
Some(html! {
p { (greeting.using(cx)) }
p {
a href=(absolute_url("/shop")) { (Lc::t("welcome-visit", &LOCALES_SHOP).using(cx)) }
}
})
}
}
async fn welcome(request: HttpRequest) -> Result<(), MailError> {
// El contexto de la petición: el correo sale en el idioma de quien se acaba de registrar.
let cx = Context::new(request);
Email::from_template(&Welcome { name: "Ana".to_string() }, &cx)
.with_to("ana@example.com")
.send()
.await
}
```
## Enlaces en los correos
Los enlaces de un correo deben ser absolutos. [`absolute_url()`] antepone a una ruta la URL pública
de la aplicación, que se configura en `mail.base_url`. No se deduce de la petición, porque la
cabecera `Host` la elige el cliente y un atacante podría hacer que los enlaces de un correo de
recuperación de contraseña apuntaran a su propio servidor.
## Adjuntos e imágenes incrustadas
Un [`Attachment`] se crea con un contenido en memoria o leyendo un archivo, y su tipo MIME se deduce
del nombre. Con [`Attachment::with_content_id()`] se incrusta en el HTML, que lo muestra con
`cid:`:
```rust,no_run
# use pagetop::prelude::*;
# use pagetop_mail::prelude::*;
# async fn example(png: Vec<u8>) -> Result<(), MailError> {
Email::new()
.with_to("ana@example.com")
.with_subject("Informe")
.with_html(html! { img src="cid:logo" alt="Logo"; p { "Adjunto el informe." } })
.with_attachment(Attachment::new("logo.png", png).with_content_id("logo"))
.with_attachment(Attachment::from_path("informes/octubre.pdf").await?)
.send()
.await
# }
```
## Diseño común del HTML
El HTML de los correos es sólo su contenido: al enviarlos se envuelve en un documento con un diseño
sobrio y neutro. La aplicación puede darle su propia imagen a **todos** los correos, incluidos los
de otras extensiones, registrando la acción [`RenderMailLayout`].
## Vistas previas en el navegador
Con `previews = true` en `[mail]` (sólo en desarrollo), `/mail/preview` lista los correos que las
extensiones declaran con la acción [`DeclareMailPreviews`], y muestra cada uno con datos de ejemplo:
cabeceras, HTML con el diseño común, texto plano y adjuntos, sin enviar nada. Ver [`preview`].
## Texto plano automático
Si un correo sólo tiene HTML, al enviarlo se genera su texto plano a partir del contenido: bloques
separados por líneas, listas con guiones, y la dirección de cada enlace entre paréntesis.
## Transportes
Se elige en `mail.transport`:
| Valor | Uso |
|--------------|-----------------------------------------------------------------------------|
| `"smtp"` | Producción. Servidor SMTP con conexiones reutilizables y cifrado TLS. |
| `"sendmail"` | Producción, con un servidor de correo local (Postfix, Exim...). |
| `"file"` | Desarrollo. Guarda cada correo como `.eml` para abrirlo con un cliente. |
| `"log"` | Por defecto. Escribe los correos en las trazas, sin enviarlos. |
| `"memory"` | Pruebas. Guarda los correos en memoria para comprobarlos con [`outbox`]. |
En entornos de pruebas con datos reales, `mail.redirect_to` entrega todos los correos a una sola
dirección, sin cambiar sus cabeceras.
Para probar el envío SMTP en desarrollo sin enviar correo real, un servidor como
[Mailpit](https://mailpit.axllent.org) recoge los correos y los muestra en el navegador:
```toml
[mail]
transport = "smtp"
[mail.smtp]
host = "localhost"
port = 1025
security = "none"
```
*/
#![doc(
html_favicon_url = "https://git.cillero.es/manuelcillero/pagetop/raw/branch/main/assets/favicon.ico"
)]
use pagetop::prelude::*;
use std::sync::LazyLock;
pub mod config;
mod error;
pub use error::MailError;
mod mailbox;
pub use mailbox::Mailbox;
mod attachment;
pub use attachment::Attachment;
mod template;
pub use template::MailTemplate;
mod layout;
pub use layout::{FnRenderMailLayout, RenderMailLayout};
mod email;
pub use email::Email;
pub mod outbox;
pub mod preview;
pub use preview::{DeclareMailPreviews, MailPreviews};
mod text;
mod transport;
include_locales!(LOCALES_MAIL);
/// Prelude de `pagetop-mail`.
pub mod prelude {
pub use crate::absolute_url;
pub use crate::{Attachment, Email, MailError, MailTemplate, Mailbox};
pub use crate::{DeclareMailPreviews, MailPreviews, RenderMailLayout};
}
/// Implementa la extensión `pagetop-mail`.
pub struct Mail;
#[async_trait]
impl Extension for Mail {
fn name(&self) -> Lc {
Lc::t("extension_name", &LOCALES_MAIL)
}
fn description(&self) -> Lc {
Lc::t("extension_description", &LOCALES_MAIL)
}
fn settings(&self) -> Option<&'static dyn LoadSettings> {
Some(&config::SETTINGS)
}
async fn initialize(&self) -> Result<(), BoxError> {
// Construir el transporte al arrancar valida los ajustes; preparar la aplicación varias
// veces en el mismo proceso (las pruebas lo hacen) reutiliza el ya construido.
transport::mailer()?.log_startup();
Ok(())
}
fn configure_router(&self, router: Router) -> Router {
if !config::SETTINGS.previews {
return router;
}
router
.route(preview::PREVIEW_PATH, web::get(preview::list_get))
.route(
&util::join!(preview::PREVIEW_PATH, "/{key}"),
web::get(preview::preview_get),
)
}
}
/// Devuelve la URL absoluta de una ruta de la aplicación, para los enlaces de los correos.
///
/// Antepone a la ruta la URL pública configurada en `mail.base_url` o, si no hay ninguna, la
/// dirección y el puerto de escucha del servidor (sólo útil en desarrollo). Una ruta que ya es una
/// URL externa (`https://...`) se devuelve sin cambios.
///
/// Si la ruta debe conservar el idioma de la petición en curso, constrúyela con
/// [`Context::route()`].
///
/// # Ejemplo
///
/// ```rust,no_run
/// # use pagetop::prelude::*;
/// # use pagetop_mail::prelude::*;
/// // Con `base_url = "https://example.com"`.
/// assert_eq!(absolute_url("/user/verify"), "https://example.com/user/verify");
/// ```
pub fn absolute_url(path: impl Into<RoutePath>) -> String {
let path = path.into().to_string();
if util::url_looks_external(&path) {
return path;
}
if path.starts_with('/') {
util::join!(base_url(), path)
} else {
util::join!(base_url(), "/", path)
}
}
// URL pública de la aplicación, sin la barra final.
fn base_url() -> &'static str {
static BASE_URL: LazyLock<String> = LazyLock::new(|| {
match config::SETTINGS
.base_url
.as_deref()
.and_then(util::non_blank)
{
Some(url) => url.trim_end_matches('/').to_owned(),
None => {
let server = &global::SETTINGS.server;
util::join!(
"http://",
&server.bind_address,
":",
server.bind_port.to_string()
)
}
}
});
&BASE_URL
}

View file

@ -0,0 +1,20 @@
extension_name = Mail
extension_description = Sends emails over SMTP, sendmail or files, with templates, HTML and attachments.
mail_footer = Message sent by { $app }.
# **< Email previews >**
preview_title = Email previews
preview_empty = No extension declares email previews.
preview_back = Back to the list
preview_from = From
preview_reply_to = Reply to
preview_to = To
preview_cc = Cc
preview_bcc = Bcc
preview_subject = Subject
preview_attachments = Attachments
preview_html = HTML
preview_text = Plain text
preview_none = None

View file

@ -0,0 +1,20 @@
extension_name = Correo electrónico
extension_description = Envía correos por SMTP, sendmail o archivos, con plantillas, HTML y adjuntos.
mail_footer = Mensaje enviado por { $app }.
# **< Vistas previas de correos >**
preview_title = Vistas previas de correos
preview_empty = Ninguna extensión declara vistas previas de correos.
preview_back = Volver a la lista
preview_from = Remitente
preview_reply_to = Responder a
preview_to = Para
preview_cc = Cc
preview_bcc = Cco
preview_subject = Asunto
preview_attachments = Adjuntos
preview_html = HTML
preview_text = Texto plano
preview_none = Ninguno

View file

@ -0,0 +1,138 @@
//! Direcciones de correo con nombre opcional ([`Mailbox`]).
use pagetop::prelude::*;
use crate::MailError;
use std::fmt;
/// Dirección de correo, con el nombre opcional de su titular.
///
/// Se crea a partir de una cadena con la dirección sola (`"ana@example.com"`) o con nombre
/// (`"Ana Pérez <ana@example.com>"`, o con el nombre entre comillas), o de una tupla
/// `(nombre, dirección)`. Ésta última es la forma segura cuando el nombre procede de datos de
/// usuario, porque puede contener comas, comillas u otros caracteres especiales.
///
/// La dirección no se valida al crearla, sino al enviar el correo, que falla con
/// [`MailError::InvalidAddress`] si no es válida.
///
/// # Ejemplos
///
/// ```rust
/// # use pagetop_mail::prelude::*;
/// let ana = Mailbox::from("Ana Pérez <ana@example.com>");
/// assert_eq!(ana.name(), Some(&"Ana Pérez".to_string()));
/// assert_eq!(ana.address(), "ana@example.com");
///
/// let luis = Mailbox::from(("Luis, el de soporte", "luis@example.com"));
/// assert_eq!(luis.name(), Some(&"Luis, el de soporte".to_string()));
///
/// let anon = Mailbox::from("no-reply@example.com");
/// assert_eq!(anon.name(), None);
/// ```
#[derive(AutoDefault, Clone, Debug, Eq, Getters, PartialEq)]
pub struct Mailbox {
/// Nombre del titular, si lo tiene.
name: Option<String>,
/// Dirección de correo.
address: String,
}
impl Mailbox {
/// Crea una dirección de correo sin nombre.
pub fn new(address: impl Into<String>) -> Self {
Mailbox {
name: None,
address: address.into().trim().to_owned(),
}
}
/// Crea una dirección de correo con el nombre de su titular. Un nombre vacío equivale a no
/// indicarlo, y los caracteres de control del nombre (saltos de línea, tabuladores...) se
/// cambian por espacios.
pub fn with_name(name: impl Into<String>, address: impl Into<String>) -> Self {
// `lettre` provoca un `panic!` al componer una cabecera con un nombre que tenga caracteres
// de control, y el nombre puede proceder de datos de usuario.
let name: String = name
.into()
.chars()
.map(|c| if c.is_control() { ' ' } else { c })
.collect();
Mailbox {
name: util::non_blank(&name).map(str::to_owned),
..Mailbox::new(address)
}
}
/// Comprueba que la dirección sea válida, con el mismo criterio que se aplica al enviar.
///
/// Sirve para validar una dirección al recibirla (p. ej. de un formulario), antes de guardarla.
/// Falla con [`MailError::InvalidAddress`] si no es válida.
///
/// ```rust
/// # use pagetop_mail::prelude::*;
/// assert!(Mailbox::new("ana@example.com").validate().is_ok());
/// assert!(Mailbox::new("ana.example.com").validate().is_err());
/// ```
pub fn validate(&self) -> Result<(), MailError> {
self.to_lettre().map(drop)
}
// Convierte la dirección al tipo de `lettre`, validándola.
pub(crate) fn to_lettre(&self) -> Result<lettre::message::Mailbox, MailError> {
let address = self.address.parse::<lettre::Address>().map_err(|source| {
MailError::InvalidAddress {
address: self.address.clone(),
source,
}
})?;
Ok(lettre::message::Mailbox::new(self.name.clone(), address))
}
}
impl From<&str> for Mailbox {
fn from(value: &str) -> Self {
let value = value.trim();
// "Nombre <dirección>": la dirección es lo que va entre los últimos `<` y `>`.
if let Some(rest) = value.strip_suffix('>')
&& let Some((name, address)) = rest.rsplit_once('<')
{
let name = name.trim();
let name = name
.strip_prefix('"')
.and_then(|n| n.strip_suffix('"'))
.unwrap_or(name);
return Mailbox::with_name(name, address);
}
Mailbox::new(value)
}
}
impl From<String> for Mailbox {
fn from(value: String) -> Self {
Mailbox::from(value.as_str())
}
}
impl From<&String> for Mailbox {
fn from(value: &String) -> Self {
Mailbox::from(value.as_str())
}
}
impl<N: Into<String>, A: Into<String>> From<(N, A)> for Mailbox {
fn from((name, address): (N, A)) -> Self {
Mailbox::with_name(name, address)
}
}
/// Muestra la dirección como `Nombre <dirección>`, o sólo la dirección si no tiene nombre. Es una
/// representación para trazas y pruebas, no la codificación de las cabeceras del correo.
impl fmt::Display for Mailbox {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.name {
Some(name) => write!(f, "{name} <{}>", self.address),
None => f.write_str(&self.address),
}
}
}

View file

@ -0,0 +1,87 @@
//! Correos guardados en memoria por el transporte `"memory"`, para comprobarlos en las pruebas.
//!
//! Con `transport = "memory"` en la sección `[mail]` de la configuración de pruebas, los correos no
//! se envían: se guardan aquí, ya completos (con el remitente por defecto y el documento HTML con
//! el diseño común), y las pruebas los recogen con [`take()`] o [`take_to()`].
//!
//! Los correos se acumulan mientras nadie los recoja, así que este transporte no debe usarse fuera
//! de las pruebas.
//!
//! # Ejemplo
//!
//! ```rust,no_run
//! use pagetop::prelude::*;
//! use pagetop_mail::prelude::*;
//! use pagetop_mail::outbox;
//!
//! #[pagetop::test]
//! async fn sends_welcome_email() {
//! // ... ejecuta lo que debe enviar el correo a ana@example.com ...
//!
//! let sent = outbox::take_to("ana@example.com");
//! assert_eq!(sent.len(), 1);
//! assert_eq!(sent[0].email().subject(), "Bienvenida");
//! }
//! ```
//!
//! Las pruebas de un mismo binario se ejecutan en paralelo y comparten estos correos: con
//! [`take_to()`] cada prueba recoge sólo los de sus destinatarios, sin llevarse los de otras.
use pagetop::prelude::*;
use crate::Email;
use std::sync::{Mutex, MutexGuard, PoisonError};
static OUTBOX: Mutex<Vec<SentEmail>> = Mutex::new(Vec::new());
/// Correo guardado por el transporte `"memory"`.
#[derive(Clone, Debug, Getters)]
pub struct SentEmail {
/// El correo tal como se envió, con el remitente y la dirección de respuesta por defecto ya
/// aplicados, y el documento HTML completo.
email: Email,
/// Direcciones a las que se entregó (todas, incluidas las de `Cc` y `Bcc`, o sólo la de
/// `mail.redirect_to` si está configurada).
envelope_to: Vec<String>,
/// Mensaje completo en formato RFC 5322, con cabeceras y partes codificadas.
raw: String,
}
impl SentEmail {
/// Indica si el correo se entregó a la dirección dada (sin distinguir mayúsculas).
pub fn is_delivered_to(&self, address: &str) -> bool {
self.envelope_to
.iter()
.any(|to| to.eq_ignore_ascii_case(address.trim()))
}
}
/// Recoge todos los correos guardados, en el orden en que se enviaron.
pub fn take() -> Vec<SentEmail> {
std::mem::take(&mut *lock())
}
/// Recoge los correos entregados a la dirección dada, en el orden en que se enviaron, y deja los
/// demás.
pub fn take_to(address: &str) -> Vec<SentEmail> {
let mut outbox = lock();
let (taken, kept) = outbox
.drain(..)
.partition(|sent: &SentEmail| sent.is_delivered_to(address));
*outbox = kept;
taken
}
pub(crate) fn push(email: Email, envelope_to: Vec<String>, raw: Vec<u8>) {
lock().push(SentEmail {
email,
envelope_to,
raw: String::from_utf8_lossy(&raw).into_owned(),
});
}
// Una prueba que falla con el bloqueo tomado no debe impedir que las demás sigan usándolo.
fn lock() -> MutexGuard<'static, Vec<SentEmail>> {
OUTBOX.lock().unwrap_or_else(PoisonError::into_inner)
}

View file

@ -0,0 +1,248 @@
//! Vistas previas de los correos en el navegador ([`DeclareMailPreviews`]).
//!
//! Con `previews = true` en la sección `[mail]`, la aplicación ofrece en [`PREVIEW_PATH`] la lista
//! de los correos que declaran las extensiones, y una página para cada uno con sus cabeceras, el
//! HTML tal como se enviaría (con el diseño común), su texto plano y sus adjuntos. Así se diseñan y
//! revisan los correos sin enviarlos.
//!
//! Las vistas previas usan datos de ejemplo y no envían nada, pero muestran las plantillas a
//! cualquiera que conozca la ruta: **actívalas sólo en desarrollo**.
//!
//! Cada vista previa se genera con el contexto de la petición, así que se puede ver en otro idioma
//! añadiendo `?lang=` a la ruta (p. ej. `/mail/preview/user.password_reset?lang=en-US`), si la
//! negociación de idioma lo permite.
use pagetop::prelude::*;
use crate::{Email, LOCALES_MAIL, transport};
/// Ruta de la lista de vistas previas. Cada correo se ve en `{PREVIEW_PATH}/{clave}`.
pub const PREVIEW_PATH: &str = "/mail/preview";
/// Tipo de función que genera un correo de ejemplo para su vista previa.
///
/// Recibe el contexto de la petición, con su idioma, y devuelve el correo como se enviaría, con
/// datos de ejemplo. Para que la vista previa siga el idioma de la petición, el correo debe crearse
/// con [`Email::from_template()`] o indicar el idioma con [`Email::with_langid()`].
pub type FnMailPreview = fn(cx: &Context) -> Email;
/// Tipo de función que declara vistas previas en un [`MailPreviews`].
pub type FnDeclareMailPreviews = fn(previews: &mut MailPreviews);
/// Vistas previas declaradas por las extensiones. Ver [`DeclareMailPreviews`].
#[derive(AutoDefault)]
pub struct MailPreviews {
previews: Vec<MailPreview>,
}
struct MailPreview {
key: &'static str,
title: Lc,
build: FnMailPreview,
}
impl MailPreviews {
/// Añade la vista previa de un correo.
///
/// - `key`: identificador único, que forma parte de la ruta (p. ej. `"shop.order_shipped"`).
/// Conviene empezarlo por el nombre de la extensión.
/// - `title`: título descriptivo para la lista.
/// - `build`: función que genera el correo con datos de ejemplo.
pub fn add(&mut self, key: &'static str, title: Lc, build: FnMailPreview) {
self.previews.push(MailPreview { key, title, build });
}
// Recoge las vistas previas de todas las extensiones, ordenadas por su clave.
fn collect() -> Self {
let mut previews = MailPreviews::default();
dispatch_actions(|action: &DeclareMailPreviews| (action.f)(&mut previews));
previews.previews.sort_by_key(|preview| preview.key);
previews
}
}
/// Acción para declarar vistas previas de correos.
///
/// Cada extensión que envía correos puede registrar esta acción para que sus correos se puedan
/// revisar en el navegador con datos de ejemplo (ver la [documentación del módulo](self)).
///
/// # Ejemplo
///
/// ```rust,no_run
/// use pagetop::prelude::*;
/// use pagetop_mail::prelude::*;
///
/// fn order_shipped(cx: &Context) -> Email {
/// Email::new()
/// .with_to("cliente@example.com")
/// .with_subject("Tu pedido ha salido")
/// .with_html(html! { p { "Tu pedido " strong { "1234" } " ha salido hoy." } })
/// .with_langid(cx)
/// }
///
/// fn declare_previews(previews: &mut MailPreviews) {
/// previews.add("shop.order_shipped", Lc::n("Pedido enviado"), order_shipped);
/// }
///
/// struct Shop;
///
/// #[async_trait]
/// impl Extension for Shop {
/// fn dependencies(&self) -> Vec<ExtensionRef> {
/// vec![&pagetop_mail::Mail]
/// }
///
/// fn actions(&self) -> Vec<ActionBox> {
/// actions![DeclareMailPreviews::new(declare_previews)]
/// }
/// }
/// ```
pub struct DeclareMailPreviews {
f: FnDeclareMailPreviews,
weight: Weight,
}
impl ActionDispatcher for DeclareMailPreviews {
fn weight(&self) -> Weight {
self.weight
}
}
impl DeclareMailPreviews {
/// Registra una función que declara vistas previas.
pub fn new(f: FnDeclareMailPreviews) -> Self {
DeclareMailPreviews { f, weight: 0 }
}
/// Opcional. Las acciones de menor peso se aplican antes. Se pueden usar valores negativos.
pub fn with_weight(mut self, value: Weight) -> Self {
self.weight = value;
self
}
}
// **< Handlers >***********************************************************************************
// GET {PREVIEW_PATH} - Lista de las vistas previas.
pub(crate) async fn list_get(request: HttpRequest) -> Result<Markup, ErrorPage> {
Page::new(request)
.with_title(Lc::t("preview_title", &LOCALES_MAIL))
.with_child(Html::with(|cx| {
let previews = MailPreviews::collect();
html! {
h1 { (Lc::t("preview_title", &LOCALES_MAIL).using(cx)) }
@if previews.previews.is_empty() {
p { (Lc::t("preview_empty", &LOCALES_MAIL).using(cx)) }
} @else {
ul {
@for preview in &previews.previews {
li {
a href=(cx.route(preview_path(preview.key))) {
(preview.title.using(cx))
}
" "
code { (preview.key) }
}
}
}
}
}
}))
.render()
.await
}
// GET {PREVIEW_PATH}/{key} - Vista previa de un correo.
pub(crate) async fn preview_get(
request: HttpRequest,
web::Path(key): web::Path<String>,
) -> Result<Markup, ErrorPage> {
let previews = MailPreviews::collect();
let Some(preview) = previews.previews.iter().find(|p| p.key == key) else {
return Err(ErrorPage::NotFound(Some(request)));
};
let cx = Context::new(request.clone());
let email = transport::prepare_preview((preview.build)(&cx));
let title = preview.title.clone();
Page::new(request)
.with_title(title.clone())
.with_child(Html::with(move |cx| render_preview(cx, &title, &email)))
.render()
.await
}
fn preview_path(key: &str) -> String {
util::join!(PREVIEW_PATH, "/", key)
}
fn render_preview(cx: &mut Context, title: &Lc, email: &Email) -> Markup {
let none = Lc::t("preview_none", &LOCALES_MAIL);
let list = |mailboxes: &[crate::Mailbox]| {
let mut list = String::new();
for mailbox in mailboxes {
if !list.is_empty() {
list.push_str(", ");
}
list.push_str(&mailbox.to_string());
}
list
};
let headers = [
("preview_from", email.from().map(ToString::to_string)),
(
"preview_reply_to",
email.reply_to().map(ToString::to_string),
),
("preview_to", Some(list(email.to()))),
("preview_cc", Some(list(email.cc()))),
("preview_bcc", Some(list(email.bcc()))),
("preview_subject", Some(email.subject().to_owned())),
];
html! {
p { a href=(cx.route(PREVIEW_PATH)) { (Lc::t("preview_back", &LOCALES_MAIL).using(cx)) } }
h1 { (title.using(cx)) }
dl {
@for (label, value) in headers {
dt { (Lc::t(label, &LOCALES_MAIL).using(cx)) }
dd {
@match value.filter(|v| !v.is_empty()) {
Some(value) => (value),
None => em { (none.using(cx)) },
}
}
}
dt { (Lc::t("preview_attachments", &LOCALES_MAIL).using(cx)) }
dd {
@if email.attachments().is_empty() {
em { (none.using(cx)) }
} @else {
ul {
@for attachment in email.attachments() {
li {
(attachment.filename()) " (" (attachment.content_type()) ", "
(attachment.body().len()) " B"
@if let Some(id) = attachment.content_id() {
", cid:" (id)
}
")"
}
}
}
}
}
}
@if let Some(html) = email.html() {
h2 { (Lc::t("preview_html", &LOCALES_MAIL).using(cx)) }
// `sandbox` vacío aísla el correo: sin scripts, sin formularios y sin navegar desde él.
iframe
title=[Lc::t("preview_html", &LOCALES_MAIL).lookup(cx)]
srcdoc=(html.as_str())
sandbox=""
style="width: 100%; height: 640px; border: 1px solid #d1d5db;" {}
}
@if let Some(text) = email.text() {
h2 { (Lc::t("preview_text", &LOCALES_MAIL).using(cx)) }
pre style="white-space: pre-wrap;" { (text) }
}
}
}

View file

@ -0,0 +1,85 @@
//! Plantillas de correo ([`MailTemplate`]).
use pagetop::prelude::*;
/// Plantilla de correo: asunto, contenido HTML y texto plano generados a partir de unos datos.
///
/// Una plantilla es un tipo propio con los datos que necesita el correo (nombre del destinatario,
/// enlaces, importes...). Sus métodos reciben un [`Context`] con el idioma del destinatario, así
/// que los textos se escriben con [`Lc`] y el HTML con [`html!`], igual que en un componente, y
/// las fechas se formatean con los métodos de [`Contextual`].
///
/// El correo se crea con [`Email::from_template()`](crate::Email::from_template), que llama a los
/// tres métodos. El HTML es sólo el **contenido**: al enviarlo se envuelve en el diseño común de
/// los correos (ver [`RenderMailLayout`](crate::RenderMailLayout)). El texto plano es opcional: si
/// la plantilla sólo genera HTML, al enviar el correo se obtiene a partir de él. Escríbelo sólo si
/// el generado no queda bien.
///
/// # Ejemplo
///
/// ```rust,no_run
/// use pagetop::prelude::*;
/// use pagetop_mail::prelude::*;
///
/// include_locales!(LOCALES_SHOP);
///
/// struct OrderShipped {
/// customer: String,
/// order: u32,
/// tracking_url: String,
/// }
///
/// impl MailTemplate for OrderShipped {
/// fn subject(&self, cx: &Context) -> String {
/// Lc::t("mail-shipped-subject", &LOCALES_SHOP)
/// .with_arg("order", self.order.to_string())
/// .lookup(cx)
/// .unwrap_or_default()
/// }
///
/// fn html(&self, cx: &Context) -> Option<Markup> {
/// let greeting =
/// Lc::t("mail-greeting", &LOCALES_SHOP).with_arg("name", self.customer.clone());
/// let track = Lc::t("mail-track", &LOCALES_SHOP);
/// Some(html! {
/// p { (greeting.using(cx)) }
/// p { a href=(self.tracking_url) { (track.using(cx)) } }
/// })
/// }
///
/// fn text(&self, cx: &Context) -> Option<String> {
/// let greeting = Lc::t("mail-greeting", &LOCALES_SHOP)
/// .with_arg("name", self.customer.clone())
/// .lookup(cx)
/// .unwrap_or_default();
/// Some(util::join!(greeting, "\n\n", &self.tracking_url))
/// }
/// }
///
/// async fn notify(language: &impl LangId) -> Result<(), MailError> {
/// let template = OrderShipped {
/// customer: "Ana".to_string(),
/// order: 1234,
/// tracking_url: absolute_url("/orders/1234"),
/// };
/// let cx = Context::default().with_langid(language);
/// Email::from_template(&template, &cx)
/// .with_to("ana@example.com")
/// .send()
/// .await
/// }
/// ```
pub trait MailTemplate {
/// Asunto del correo, en el idioma del contexto.
fn subject(&self, cx: &Context) -> String;
/// Contenido HTML del correo, sin el documento que lo envuelve. Por defecto, ninguno.
fn html(&self, _cx: &Context) -> Option<Markup> {
None
}
/// Texto plano del correo. Por defecto, ninguno: al enviarlo se genera a partir del HTML.
fn text(&self, _cx: &Context) -> Option<String> {
None
}
}

View file

@ -0,0 +1,402 @@
// Conversión del HTML de un correo en su texto plano alternativo.
//
// No es un intérprete HTML completo: basta para el HTML de los correos, que normalmente sale de
// `html!` y está bien formado. Los bloques (párrafos, encabezados, listas, filas de tabla...) se
// separan con saltos de línea, los elementos de lista se marcan con "- ", los enlaces añaden su
// dirección entre paréntesis y las imágenes su texto alternativo. Se descartan `head`, `title`,
// `style` y `script`, y los comentarios.
// Elementos que separan párrafos (una línea en blanco) y que separan líneas.
const PARAGRAPHS: &[&str] = &[
"p",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"ul",
"ol",
"table",
"blockquote",
"pre",
"dl",
];
const LINES: &[&str] = &[
"div", "tr", "li", "dt", "dd", "section", "article", "header", "footer", "body", "html",
];
// Elementos cuyo contenido no es texto del correo.
const SKIPPED: &[&str] = &["head", "title", "style", "script"];
pub(crate) fn html_to_text(html: &str) -> String {
let mut text = Text::default();
let mut links: Vec<(usize, Option<String>)> = Vec::new();
let mut pre = 0usize;
let mut rest = html;
while let Some(start) = rest.find('<') {
text.push(&decode(&rest[..start]), pre > 0);
rest = &rest[start..];
if let Some(comment) = rest.strip_prefix("<!--") {
rest = comment.find("-->").map_or("", |end| &comment[end + 3..]);
continue;
}
let Some(tag) = Tag::parse(rest) else {
// Un `<` que no abre una etiqueta es texto.
text.push("<", pre > 0);
rest = &rest[1..];
continue;
};
rest = &rest[tag.len..];
if !tag.closing && SKIPPED.contains(&tag.name.as_str()) {
let close = ["</", &tag.name].concat();
rest = match find_ignore_case(rest, &close) {
Some(pos) => {
let after = &rest[pos..];
after.find('>').map_or("", |gt| &after[gt + 1..])
}
None => "",
};
continue;
}
match (tag.name.as_str(), tag.closing) {
("br", _) => text.line_break(),
("hr", _) => {
text.block(2);
text.emit("----");
text.block(2);
}
("li", false) => {
text.block(1);
text.emit("- ");
}
("td" | "th", true) => text.space(),
("img", _) => {
if let Some(alt) = tag.attr("alt").filter(|alt| !alt.trim().is_empty()) {
text.push(&alt, false);
}
}
("a", false) => links.push((text.len(), tag.attr("href"))),
("a", true) => {
if let Some((start, Some(href))) = links.pop() {
let label = text.since(start).trim().to_owned();
let target = href.strip_prefix("mailto:").unwrap_or(&href);
let is_link = !(href.is_empty()
|| href.starts_with('#')
|| href.starts_with("cid:")
|| href.starts_with("javascript:"));
if is_link && label != target && label != href {
text.emit_inline(&["(", target, ")"].concat());
}
}
}
("pre", closing) => {
text.block(2);
if closing {
pre = pre.saturating_sub(1);
} else {
pre += 1;
}
}
(name, _) if PARAGRAPHS.contains(&name) => text.block(2),
(name, _) if LINES.contains(&name) => text.block(1),
_ => {}
}
}
text.push(&decode(rest), pre > 0);
text.finish()
}
// Texto en construcción, con los separadores pendientes hasta que llegue más texto: así no quedan
// espacios ni saltos de línea sobrantes al principio, al final o entre bloques.
#[derive(Default)]
struct Text {
buf: String,
newlines: usize,
space: bool,
}
impl Text {
fn len(&self) -> usize {
self.buf.len()
}
fn since(&self, start: usize) -> &str {
self.buf.get(start..).unwrap_or_default()
}
// Añade texto. Fuera de `pre` cualquier secuencia de espacios en blanco cuenta como un espacio.
fn push(&mut self, s: &str, preformatted: bool) {
if preformatted {
if !s.is_empty() {
self.flush();
self.buf.push_str(s);
}
return;
}
for c in s.chars() {
if c.is_whitespace() {
self.space();
} else {
self.flush();
self.buf.push(c);
}
}
}
// Añade un texto tal cual, tras los separadores pendientes.
fn emit(&mut self, s: &str) {
self.flush();
self.buf.push_str(s);
}
// Añade un texto separado por un espacio de lo anterior en la misma línea.
fn emit_inline(&mut self, s: &str) {
self.space();
self.emit(s);
}
fn space(&mut self) {
if self.newlines == 0 {
self.space = true;
}
}
fn line_break(&mut self) {
self.newlines = (self.newlines + 1).min(2);
self.space = false;
}
fn block(&mut self, newlines: usize) {
self.newlines = self.newlines.max(newlines);
self.space = false;
}
fn flush(&mut self) {
if !self.buf.is_empty() {
if self.newlines > 0 {
let trimmed = self.buf.trim_end_matches(' ').len();
self.buf.truncate(trimmed);
for _ in 0..self.newlines {
self.buf.push('\n');
}
} else if self.space && !self.buf.ends_with([' ', '\n']) {
self.buf.push(' ');
}
}
self.newlines = 0;
self.space = false;
}
fn finish(self) -> String {
let mut out = String::with_capacity(self.buf.len());
for line in self.buf.lines() {
out.push_str(line.trim_end());
out.push('\n');
}
out.trim().to_owned()
}
}
// Etiqueta HTML leída al principio de un texto que empieza por `<`.
struct Tag<'a> {
name: String,
closing: bool,
attrs: &'a str,
// Longitud de la etiqueta completa, de `<` a `>`.
len: usize,
}
impl<'a> Tag<'a> {
fn parse(s: &'a str) -> Option<Self> {
let body = s.strip_prefix('<')?;
let (closing, body) = match body.strip_prefix('/') {
Some(body) => (true, body),
None => (false, body),
};
// `<!DOCTYPE ...>` y similares se leen como etiquetas sin nombre conocido.
let first = body.chars().next()?;
if !(first.is_ascii_alphabetic() || first == '!') {
return None;
}
// Busca el `>` final fuera de los valores entre comillas.
let mut quote = None;
let mut end = None;
for (i, c) in body.char_indices() {
match (quote, c) {
(Some(q), c) if c == q => quote = None,
(None, '"' | '\'') => quote = Some(c),
(None, '>') => {
end = Some(i);
break;
}
_ => {}
}
}
let end = end?;
let inner = body[..end].trim_end_matches('/');
let name_len = inner
.find(|c: char| c.is_whitespace())
.unwrap_or(inner.len());
Some(Tag {
name: inner[..name_len].to_ascii_lowercase(),
closing,
attrs: &inner[name_len..],
len: s.len() - body.len() + end + 1,
})
}
// Valor del atributo `name`, ya decodificado.
fn attr(&self, name: &str) -> Option<String> {
let mut rest = self.attrs;
loop {
rest = rest.trim_start();
if rest.is_empty() {
return None;
}
let key_len = rest
.find(|c: char| c == '=' || c.is_whitespace())
.unwrap_or(rest.len());
let key = &rest[..key_len];
rest = rest[key_len..].trim_start();
let value = match rest.strip_prefix('=') {
Some(after) => {
let after = after.trim_start();
let (value, next) = match after.chars().next() {
Some(q @ ('"' | '\'')) => {
let inner = &after[1..];
let end = inner.find(q).unwrap_or(inner.len());
(&inner[..end], inner.get(end + 1..).unwrap_or_default())
}
_ => {
let end = after.find(char::is_whitespace).unwrap_or(after.len());
(&after[..end], &after[end..])
}
};
rest = next;
value
}
None => "",
};
if key.eq_ignore_ascii_case(name) {
return Some(decode(value));
}
}
}
}
// Posición de `needle` en `haystack` sin distinguir mayúsculas (ASCII).
fn find_ignore_case(haystack: &str, needle: &str) -> Option<usize> {
haystack
.to_ascii_lowercase()
.find(&needle.to_ascii_lowercase())
}
// Decodifica las entidades HTML habituales y las numéricas; deja tal cual las desconocidas.
fn decode(s: &str) -> String {
if !s.contains('&') {
return s.to_owned();
}
let mut out = String::with_capacity(s.len());
let mut rest = s;
while let Some(amp) = rest.find('&') {
out.push_str(&rest[..amp]);
rest = &rest[amp..];
let decoded = rest.find(';').filter(|&end| end <= 10).and_then(|end| {
let entity = &rest[1..end];
let c = match entity {
"amp" => Some('&'),
"lt" => Some('<'),
"gt" => Some('>'),
"quot" => Some('"'),
"apos" => Some('\''),
"nbsp" => Some(' '),
_ => entity.strip_prefix('#').and_then(|num| {
let code = match num.strip_prefix(['x', 'X']) {
Some(hex) => u32::from_str_radix(hex, 16).ok(),
None => num.parse().ok(),
};
code.and_then(char::from_u32)
}),
};
c.map(|c| (c, end))
});
match decoded {
Some((c, end)) => {
out.push(c);
rest = &rest[end + 1..];
}
None => {
out.push('&');
rest = &rest[1..];
}
}
}
out.push_str(rest);
out
}
#[cfg(test)]
mod tests {
use super::html_to_text;
#[test]
fn blocks_lists_and_line_breaks_become_lines() {
let html = "<h1>Title</h1><p>Hello <strong>Ana</strong>,<br>welcome.</p>\
<ul><li>One</li><li>Two</li></ul><p>Bye</p>";
assert_eq!(
html_to_text(html),
"Title\n\nHello Ana,\nwelcome.\n\n- One\n- Two\n\nBye"
);
}
#[test]
fn whitespace_is_collapsed_outside_pre() {
let html = "<p> Lots of\n\n space </p><pre> keep\n this</pre>";
assert_eq!(html_to_text(html), "Lots of space\n\n keep\n this");
}
#[test]
fn links_show_their_target_unless_it_is_the_label() {
let html = r##"<p><a href="https://x.com/a?b=1&amp;c=2">Open</a></p>
<p><a href="https://x.com">https://x.com</a></p>
<p><a href="mailto:ana@example.com">ana@example.com</a></p>
<p><a href="mailto:ana@example.com">Write to Ana</a></p>
<p><a href="#top">Top</a></p>"##;
assert_eq!(
html_to_text(html),
"Open (https://x.com/a?b=1&c=2)\n\nhttps://x.com\n\nana@example.com\n\n\
Write to Ana (ana@example.com)\n\nTop"
);
}
#[test]
fn entities_are_decoded() {
assert_eq!(
html_to_text("<p>a &amp; b &lt;c&gt; &quot;d&quot; &#39;e&#x27; &copy;</p>"),
"a & b <c> \"d\" 'e' &copy;"
);
}
#[test]
fn head_styles_scripts_and_comments_are_dropped() {
let html = "<!DOCTYPE html><html><head><title>T</title><style>p{}</style></head>\
<body><!-- hidden --><script>x()</script><p>Visible</p></body></html>";
assert_eq!(html_to_text(html), "Visible");
}
#[test]
fn tables_and_images_keep_their_text() {
let html = r#"<table><tr><td>A</td><td>B</td></tr><tr><td>C</td><td>D</td></tr></table>
<p><img src="cid:logo" alt="Logo"> <img src="x.png" alt=""></p>"#;
assert_eq!(html_to_text(html), "A B\nC D\n\nLogo");
}
#[test]
fn stray_less_than_is_text() {
assert_eq!(html_to_text("<p>1 < 2</p>"), "1 < 2");
}
}

View file

@ -0,0 +1,274 @@
// Entrega de los correos con el transporte configurado en `[mail]`.
use pagetop::prelude::*;
use crate::config::{self, MailTransport, SmtpSecurity, SmtpSettings};
use crate::{Email, MailError, Mailbox, outbox};
use lettre::address::Envelope;
use lettre::transport::smtp::PoolConfig;
use lettre::transport::smtp::authentication::Credentials;
use lettre::transport::smtp::client::{Tls, TlsParameters};
use lettre::transport::smtp::extension::ClientId;
use lettre::{
Address, AsyncFileTransport, AsyncSendmailTransport, AsyncSmtpTransport, AsyncTransport,
Tokio1Executor,
};
use std::path::PathBuf;
use std::sync::OnceLock;
// Transporte y direcciones por defecto, construidos una sola vez a partir de los ajustes.
static MAILER: OnceLock<Mailer> = OnceLock::new();
pub(crate) struct Mailer {
transport: Transport,
from: Option<Mailbox>,
reply_to: Option<Mailbox>,
redirect_to: Option<Address>,
}
enum Transport {
Smtp(AsyncSmtpTransport<Tokio1Executor>),
Sendmail(AsyncSendmailTransport<Tokio1Executor>),
File(AsyncFileTransport<Tokio1Executor>),
Log,
Memory,
}
// Devuelve el transporte, construyéndolo en el primer uso. `Mail::initialize()` lo construye al
// arrancar para detener la aplicación si los ajustes no son válidos; fuera de una aplicación (p.
// ej. en pruebas) se construye en el primer envío.
pub(crate) fn mailer() -> Result<&'static Mailer, MailError> {
if let Some(mailer) = MAILER.get() {
return Ok(mailer);
}
let mailer = Mailer::from_settings()?;
// Si otro hilo se adelanta, se queda el suyo y se descarta éste.
Ok(MAILER.get_or_init(|| mailer))
}
pub(crate) async fn deliver(email: Email) -> Result<(), MailError> {
let mailer = mailer()?;
let email = email.prepare(mailer.from.as_ref(), mailer.reply_to.as_ref());
// Escribirlo en las trazas no necesita remitente: así una aplicación sin configurar muestra sus
// correos aunque no tenga `mail.from`.
if let Transport::Log = mailer.transport {
return log_email(&email, mailer.redirect_to.as_ref());
}
let message = email.to_message()?;
let envelope = match &mailer.redirect_to {
Some(address) => Envelope::new(message.envelope().from().cloned(), vec![address.clone()])
.map_err(MailError::Build)?,
None => message.envelope().clone(),
};
let raw = message.formatted();
match &mailer.transport {
Transport::Smtp(smtp) => {
smtp.send_raw(&envelope, &raw)
.await
.map_err(MailError::Smtp)?;
}
Transport::Sendmail(sendmail) => {
sendmail
.send_raw(&envelope, &raw)
.await
.map_err(MailError::Sendmail)?;
}
Transport::File(file) => {
file.send_raw(&envelope, &raw)
.await
.map_err(MailError::File)?;
}
Transport::Memory => {
outbox::push(email, recipients(&envelope), raw);
}
Transport::Log => unreachable!("log transport is handled before building the message"),
}
Ok(())
}
// Escribe el correo en las trazas en lugar de enviarlo (`transport = "log"`). Valida las
// direcciones igual que al enviar, salvo que falte el remitente.
fn log_email(email: &Email, redirect_to: Option<&Address>) -> Result<(), MailError> {
for mailbox in email.from().into_iter().chain(email.reply_to()) {
mailbox.to_lettre()?;
}
let mut recipients = Vec::new();
for mailbox in email.to().iter().chain(email.cc()).chain(email.bcc()) {
recipients.push(mailbox.to_lettre()?.email.to_string());
}
if recipients.is_empty() {
return Err(MailError::NoRecipients);
}
if let Some(address) = redirect_to {
recipients = vec![address.to_string()];
}
let body = email
.text()
.cloned()
.or_else(|| email.html().map(|html| html.as_str().to_owned()))
.unwrap_or_default();
trace::info!(
"Email not delivered (mail.transport = \"log\")\n\
From: {}\nTo: {}\nSubject: {}\n\n{}",
email.from().map(ToString::to_string).unwrap_or_default(),
recipients.join(", "),
email.subject(),
body
);
Ok(())
}
// Completa un correo como si se fuera a enviar, para mostrar su vista previa. Si los ajustes no
// son válidos (la aplicación no habría arrancado), se muestra sin las direcciones por defecto.
pub(crate) fn prepare_preview(email: Email) -> Email {
let mailer = mailer().ok();
email.prepare(
mailer.and_then(|m| m.from.as_ref()),
mailer.and_then(|m| m.reply_to.as_ref()),
)
}
// Direcciones a las que se entrega el correo.
fn recipients(envelope: &Envelope) -> Vec<String> {
envelope.to().iter().map(ToString::to_string).collect()
}
impl Mailer {
fn from_settings() -> Result<Self, MailError> {
let settings = &*config::SETTINGS;
let transport = match settings.transport {
MailTransport::Smtp => Transport::Smtp(smtp_transport(&settings.smtp)?),
MailTransport::Sendmail => Transport::Sendmail(match &settings.sendmail.command {
Some(command) => AsyncSendmailTransport::new_with_command(command),
None => AsyncSendmailTransport::new(),
}),
MailTransport::File => {
let dir = PathBuf::from(&settings.file.dir);
std::fs::create_dir_all(&dir).map_err(|source| MailError::CreateDir {
path: dir.clone(),
source,
})?;
Transport::File(AsyncFileTransport::new(dir))
}
MailTransport::Log => Transport::Log,
MailTransport::Memory => Transport::Memory,
};
let redirect_to = match settings.redirect_to.as_deref().and_then(util::non_blank) {
Some(address) => Some(address.parse::<Address>().map_err(|source| {
invalid_setting(
"mail.redirect_to",
MailError::InvalidAddress {
address: address.to_owned(),
source,
},
)
})?),
None => None,
};
if let Some(url) = settings.base_url.as_deref().and_then(util::non_blank)
&& !(url.starts_with("http://") || url.starts_with("https://"))
{
return Err(invalid_setting(
"mail.base_url",
MailError::InvalidUrl(url.to_owned()),
));
}
Ok(Mailer {
transport,
from: setting_mailbox("mail.from", settings.from.as_deref())?,
reply_to: setting_mailbox("mail.reply_to", settings.reply_to.as_deref())?,
redirect_to,
})
}
// Avisa en las trazas de los ajustes que conviene revisar.
pub(crate) fn log_startup(&self) {
let settings = &*config::SETTINGS;
match self.transport {
Transport::Log => trace::warn!(
"mail.transport is \"log\": emails are written to the log, not delivered"
),
Transport::Memory => trace::warn!(
"mail.transport is \"memory\": emails are kept in memory, not delivered \
(tests only)"
),
Transport::Smtp(_) | Transport::Sendmail(_) | Transport::File(_) => {
if self.from.is_none() {
trace::warn!("mail.from is not set: every email must set its own sender");
}
if settings
.base_url
.as_deref()
.and_then(util::non_blank)
.is_none()
{
trace::warn!(
"mail.base_url is not set: links in emails point to {}",
crate::base_url()
);
}
}
}
if settings.previews {
trace::warn!(
"mail.previews is enabled: email previews are public at {} (development only)",
crate::preview::PREVIEW_PATH
);
}
if let Some(address) = &self.redirect_to {
trace::warn!("mail.redirect_to is set: all emails are delivered only to {address}");
}
}
}
fn smtp_transport(smtp: &SmtpSettings) -> Result<AsyncSmtpTransport<Tokio1Executor>, MailError> {
let tls_parameters = || {
TlsParameters::builder(smtp.host.clone())
.dangerous_accept_invalid_certs(smtp.accept_invalid_certs)
.build()
.map_err(|err| invalid_setting("mail.smtp", MailError::Smtp(err)))
};
let (tls, default_port) = match smtp.security {
SmtpSecurity::None => (Tls::None, 25),
SmtpSecurity::Opportunistic => (Tls::Opportunistic(tls_parameters()?), 25),
SmtpSecurity::StartTls => (Tls::Required(tls_parameters()?), 587),
SmtpSecurity::Tls => (Tls::Wrapper(tls_parameters()?), 465),
};
let mut builder = AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(&smtp.host)
.port(smtp.port.unwrap_or(default_port))
.tls(tls)
.timeout(Some(std::time::Duration::from_secs(smtp.timeout_secs)))
.pool_config(PoolConfig::new().max_size(smtp.pool_max_size));
if let Some(username) = smtp.username.as_deref().and_then(util::non_blank) {
builder = builder.credentials(Credentials::new(
username.to_owned(),
smtp.password.clone().unwrap_or_default(),
));
}
if let Some(name) = smtp.hello_name.as_deref().and_then(util::non_blank) {
builder = builder.hello_name(ClientId::Domain(name.to_owned()));
}
Ok(builder.build())
}
// Lee una dirección de los ajustes, comprobando que sea válida.
fn setting_mailbox(key: &'static str, value: Option<&str>) -> Result<Option<Mailbox>, MailError> {
let Some(value) = value.and_then(util::non_blank) else {
return Ok(None);
};
let mailbox = Mailbox::from(value);
mailbox
.to_lettre()
.map_err(|err| invalid_setting(key, err))?;
Ok(Some(mailbox))
}
fn invalid_setting(key: &'static str, source: MailError) -> MailError {
MailError::InvalidSetting {
key,
source: Box::new(source),
}
}

View file

@ -0,0 +1,381 @@
// The tests run with `config/common.toml` of this crate: memory transport, a default sender and
// `https://example.com/` as base URL. Tests in a binary run in parallel and share the outbox, so
// each test uses its own recipient and collects its emails with `outbox::take_to()`.
use pagetop::prelude::*;
use pagetop_mail::outbox::{self, SentEmail};
use pagetop_mail::prelude::*;
async fn send_one(email: Email, recipient: &str) -> SentEmail {
email.send().await.unwrap();
let mut sent = outbox::take_to(recipient);
assert_eq!(sent.len(), 1, "expected exactly one email for {recipient}");
sent.remove(0)
}
// **< Mailbox >************************************************************************************
#[pagetop::test]
async fn mailbox_parses_address_with_and_without_name() {
let plain = Mailbox::from(" ana@example.com ");
assert_eq!(plain.name(), None);
assert_eq!(plain.address(), "ana@example.com");
let named = Mailbox::from("Ana Pérez <ana@example.com>");
assert_eq!(named.name().map(String::as_str), Some("Ana Pérez"));
assert_eq!(named.address(), "ana@example.com");
let quoted = Mailbox::from("\"Pérez, Ana\" <ana@example.com>");
assert_eq!(quoted.name().map(String::as_str), Some("Pérez, Ana"));
let tuple = Mailbox::from((" ", "ana@example.com"));
assert_eq!(tuple.name(), None, "a blank name must be dropped");
assert_eq!(named.to_string(), "Ana Pérez <ana@example.com>");
assert_eq!(plain.to_string(), "ana@example.com");
}
#[pagetop::test]
async fn mailbox_validates_its_address() {
assert!(
Mailbox::from("Ana Pérez <ana@example.com>")
.validate()
.is_ok()
);
for invalid in [
"",
"ana",
"ana@",
"@example.com",
"ana @example.com",
"a@b@example.com",
] {
assert!(
matches!(
Mailbox::new(invalid).validate(),
Err(MailError::InvalidAddress { .. })
),
"{invalid:?} must be rejected"
);
}
}
#[pagetop::test]
async fn control_characters_in_names_cannot_inject_headers() {
// `lettre` panics on a header with control characters; the name may come from user data.
let mailbox = Mailbox::with_name("Ana\r\nBcc: evil@example.com", "control@example.com");
assert_eq!(
mailbox.name().map(String::as_str),
Some("Ana Bcc: evil@example.com")
);
let sent = send_one(
Email::new()
.with_to(mailbox)
.with_subject("Hi\r\nBcc: evil@example.com")
.with_text("Hi"),
"control@example.com",
)
.await;
assert_eq!(sent.envelope_to(), &["control@example.com".to_string()]);
assert!(!sent.raw().contains("\r\nBcc:"));
// A subject is a single line: control characters become spaces.
assert_eq!(sent.email().subject(), "Hi Bcc: evil@example.com");
}
// **< Composition >********************************************************************************
#[pagetop::test]
async fn text_email_uses_default_sender_and_reaches_every_recipient() {
let sent = send_one(
Email::new()
.with_to("text-to@example.com")
.with_cc("text-cc@example.com")
.with_bcc("text-bcc@example.com")
.with_subject("Plain text")
.with_text("Hello"),
"text-to@example.com",
)
.await;
let from = sent.email().from().unwrap();
assert_eq!(from.address(), "tests@example.com");
assert_eq!(sent.envelope_to().len(), 3);
assert!(sent.is_delivered_to("TEXT-BCC@example.com"));
assert!(sent.raw().contains("Subject: Plain text"));
assert!(
sent.raw()
.lines()
.any(|line| line.starts_with("Message-ID: <") && line.ends_with("@example.com>")),
"Message-ID must use the sender domain"
);
assert!(sent.raw().contains("Content-Type: text/plain"));
// Bcc recipients get the email but must not appear in its headers.
assert!(!sent.raw().contains("text-bcc@example.com"));
}
#[pagetop::test]
async fn explicit_sender_overrides_default_sender() {
let sent = send_one(
Email::new()
.with_from(("Support", "support@example.com"))
.with_reply_to("help@example.com")
.with_to("override@example.com")
.with_text("Hi"),
"override@example.com",
)
.await;
assert_eq!(
sent.email().from().unwrap().address(),
"support@example.com"
);
assert!(sent.raw().contains("From: Support <support@example.com>"));
assert!(sent.raw().contains("Reply-To: help@example.com"));
}
#[pagetop::test]
async fn text_and_html_are_sent_as_alternatives() {
let sent = send_one(
Email::new()
.with_to("alternative@example.com")
.with_subject("Both")
.with_text("Text version")
.with_html(html! { p { "HTML version" } }),
"alternative@example.com",
)
.await;
assert!(sent.raw().contains("multipart/alternative"));
assert!(sent.raw().contains("text/plain"));
assert!(sent.raw().contains("text/html"));
}
#[pagetop::test]
async fn html_content_is_wrapped_in_the_default_layout() {
let sent = send_one(
Email::new()
.with_to("layout@example.com")
.with_subject("Layout <test>")
.with_langid(&Locale::resolve("es-ES"))
.with_html(html! { p { "Body content" } }),
"layout@example.com",
)
.await;
let html = sent.email().html().unwrap().as_str();
assert!(html.starts_with("<!DOCTYPE html>"));
assert!(html.contains(r#"<html lang="es-ES">"#));
assert!(html.contains("<title>Layout &lt;test&gt;</title>"));
assert!(html.contains("<p>Body content</p>"));
assert!(
html.contains("Mensaje enviado por"),
"footer must follow the email language"
);
}
#[pagetop::test]
async fn html_document_is_sent_without_layout() {
let sent = send_one(
Email::new()
.with_to("document@example.com")
.with_html_document(html! { html { body { "Own document" } } }),
"document@example.com",
)
.await;
assert_eq!(
sent.email().html().unwrap().as_str(),
"<html><body>Own document</body></html>"
);
}
// **< Attachments >********************************************************************************
#[pagetop::test]
async fn attachments_are_sent_as_mixed_parts_with_guessed_content_type() {
let sent = send_one(
Email::new()
.with_to("attachment@example.com")
.with_text("See attached")
.with_attachment(Attachment::new("report.pdf", b"%PDF-1.4".to_vec()))
.with_attachment(
Attachment::new("data.bin", vec![0u8, 1, 2]).with_content_type("text/csv"),
),
"attachment@example.com",
)
.await;
let raw = sent.raw();
assert!(raw.contains("multipart/mixed"));
assert!(raw.contains("Content-Type: application/pdf"));
assert!(raw.contains(r#"filename="report.pdf""#));
assert!(raw.contains("Content-Type: text/csv"));
}
#[pagetop::test]
async fn inline_images_are_related_to_the_html() {
let sent = send_one(
Email::new()
.with_to("inline@example.com")
.with_html(html! { img src="cid:logo"; })
.with_attachment(
Attachment::new("logo.png", vec![137u8, 80, 78, 71]).with_content_id("logo"),
),
"inline@example.com",
)
.await;
let raw = sent.raw();
assert!(raw.contains("multipart/related"));
assert!(raw.contains("Content-ID: <logo>"));
assert!(!raw.contains("multipart/mixed"));
}
#[pagetop::test]
async fn inline_images_without_html_are_sent_as_attachments() {
let sent = send_one(
Email::new()
.with_to("inline-text@example.com")
.with_text("No HTML")
.with_attachment(Attachment::new("logo.png", vec![1u8]).with_content_id("logo")),
"inline-text@example.com",
)
.await;
assert!(sent.raw().contains("multipart/mixed"));
assert!(!sent.raw().contains("multipart/related"));
}
#[pagetop::test]
async fn attachment_reads_file_from_disk() {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml");
let attachment = Attachment::from_path(path).await.unwrap();
assert_eq!(attachment.filename(), "Cargo.toml");
assert!(!attachment.body().is_empty());
assert!(!attachment.is_inline());
let missing = Attachment::from_path("does/not/exist.pdf").await;
assert!(matches!(missing, Err(MailError::ReadAttachment { .. })));
}
#[pagetop::test]
async fn invalid_content_type_fails_on_send() {
let result = Email::new()
.with_to("bad-type@example.com")
.with_attachment(Attachment::new("x", vec![]).with_content_type("not a type"))
.send()
.await;
assert!(matches!(result, Err(MailError::InvalidContentType(_))));
}
// **< Errors >*************************************************************************************
#[pagetop::test]
async fn email_without_recipients_fails() {
let result = Email::new().with_text("Nobody").send().await;
assert!(matches!(result, Err(MailError::NoRecipients)));
}
#[pagetop::test]
async fn invalid_address_fails() {
let result = Email::new().with_to("not-an-address").send().await;
let Err(MailError::InvalidAddress { address, .. }) = result else {
panic!("expected an invalid address error, got {result:?}");
};
assert_eq!(address, "not-an-address");
}
// **< Templates >**********************************************************************************
struct Greeting {
name: String,
}
impl MailTemplate for Greeting {
fn subject(&self, cx: &Context) -> String {
util::join!("Hello ", &self.name, " [", cx.langid().to_string(), "]")
}
fn html(&self, _cx: &Context) -> Option<Markup> {
Some(html! { p { "Hello " (self.name) } })
}
fn text(&self, _cx: &Context) -> Option<String> {
Some(util::join!("Hello ", &self.name))
}
}
#[pagetop::test]
async fn template_builds_subject_html_and_text_in_the_context_language() {
let cx = Context::default().with_langid(&Locale::resolve("es-ES"));
let email = Email::from_template(
&Greeting {
name: "Ana".to_string(),
},
&cx,
)
.with_to("template@example.com");
assert_eq!(email.subject(), "Hello Ana [es-ES]");
assert_eq!(email.text().map(String::as_str), Some("Hello Ana"));
assert_eq!(email.langid().to_string(), "es-ES");
let sent = send_one(email, "template@example.com").await;
let html = sent.email().html().unwrap().as_str();
assert!(html.contains(r#"<html lang="es-ES">"#));
assert!(html.contains("<p>Hello Ana</p>"));
}
// **< URLs >***************************************************************************************
#[pagetop::test]
async fn absolute_url_prepends_the_configured_base_url() {
assert_eq!(
absolute_url("/user/verify"),
"https://example.com/user/verify"
);
assert_eq!(absolute_url("user"), "https://example.com/user");
assert_eq!(
absolute_url(RoutePath::new("/search").with_param("q", "mail")),
"https://example.com/search?q=mail"
);
assert_eq!(absolute_url("https://other.org/x"), "https://other.org/x");
}
// **< Plain text from HTML >***********************************************************************
#[pagetop::test]
async fn html_only_email_gets_plain_text_from_its_content() {
let sent = send_one(
Email::new()
.with_to("auto-text@example.com")
.with_html(html! {
p { "Hello " strong { "Ana" } }
p { a href="https://example.com/x" { "Open" } }
}),
"auto-text@example.com",
)
.await;
// Generated from the content, before the layout: the footer is not part of it.
assert_eq!(
sent.email().text().map(String::as_str),
Some("Hello Ana\n\nOpen (https://example.com/x)")
);
assert!(sent.raw().contains("multipart/alternative"));
}
#[pagetop::test]
async fn explicit_text_is_not_replaced() {
let sent = send_one(
Email::new()
.with_to("own-text@example.com")
.with_text("Own text")
.with_html(html! { p { "HTML" } }),
"own-text@example.com",
)
.await;
assert_eq!(sent.email().text().map(String::as_str), Some("Own text"));
}

View file

@ -0,0 +1,55 @@
// The action registry is built once per test binary, so the custom layout lives in its own file.
use pagetop::prelude::*;
use pagetop_mail::outbox;
use pagetop_mail::prelude::*;
struct TestApp;
#[async_trait]
impl Extension for TestApp {
fn dependencies(&self) -> Vec<ExtensionRef> {
vec![&pagetop_mail::Mail]
}
fn actions(&self) -> Vec<ActionBox> {
actions![
RenderMailLayout::new(heavier_layout).with_weight(10),
RenderMailLayout::new(custom_layout),
]
}
}
fn custom_layout(cx: &Context, email: &Email, content: &Markup) -> Markup {
html! {
html lang=(cx.langid().to_string()) {
body { h1 { (email.subject()) } div class="custom" { (content) } }
}
}
}
fn heavier_layout(_cx: &Context, _email: &Email, _content: &Markup) -> Markup {
html! { "heavier layout must not be used" }
}
#[pagetop::test]
async fn lightest_registered_layout_replaces_the_default_one() {
Application::prepare(&TestApp).await;
Email::new()
.with_to("custom-layout@example.com")
.with_subject("Custom")
.with_html(html! { p { "Content" } })
.send()
.await
.unwrap();
let sent = outbox::take_to("custom-layout@example.com");
assert_eq!(
sent[0].email().html().unwrap().as_str(),
concat!(
r#"<html lang="en-US"><body><h1>Custom</h1>"#,
r#"<div class="custom"><p>Content</p></div></body></html>"#
)
);
}

View file

@ -0,0 +1,64 @@
// `config/common.toml` enables the previews. The action registry is built once per test binary, so
// the previews declared here live in their own file.
use pagetop::prelude::*;
use pagetop_mail::prelude::*;
struct TestApp;
#[async_trait]
impl Extension for TestApp {
fn dependencies(&self) -> Vec<ExtensionRef> {
vec![&pagetop_mail::Mail]
}
fn actions(&self) -> Vec<ActionBox> {
actions![DeclareMailPreviews::new(declare_previews)]
}
}
fn declare_previews(previews: &mut MailPreviews) {
previews.add("test.welcome", Lc::n("Welcome email"), welcome);
}
fn welcome(cx: &Context) -> Email {
Email::new()
.with_to("Ana <ana@example.com>")
.with_subject("Welcome")
.with_html(html! { p { "Hello " a href="https://example.com/start" { "start" } } })
.with_attachment(Attachment::new("terms.pdf", b"%PDF".to_vec()))
.with_langid(cx)
}
async fn get(app: &Router, uri: &str) -> (web::http::StatusCode, String) {
let req = web::test::TestRequest::get().uri(uri).to_request();
let resp = web::test::send_request(app, req).await;
let status = resp.status();
(status, web::test::read_body_text(resp).await)
}
#[pagetop::test]
async fn previews_are_listed_and_rendered_without_sending() {
let app = web::test::init_router(Application::prepare(&TestApp).await.test());
let (status, body) = get(&app, "/mail/preview").await;
assert_eq!(status, web::http::StatusCode::OK);
assert!(body.contains(r#"href="/mail/preview/test.welcome""#));
assert!(body.contains("Welcome email"));
let (status, body) = get(&app, "/mail/preview/test.welcome").await;
assert_eq!(status, web::http::StatusCode::OK);
// Default sender applied, as when sending.
assert!(body.contains("PageTop Tests &lt;tests@example.com&gt;"));
assert!(body.contains("Ana &lt;ana@example.com&gt;"));
// The HTML goes in an isolated iframe, already wrapped in the layout.
assert!(body.contains("srcdoc=\"&lt;!DOCTYPE html&gt;"));
assert!(body.contains(r#"sandbox="""#));
// Generated plain text and attachments.
assert!(body.contains("Hello start (https://example.com/start)"));
assert!(body.contains("terms.pdf (application/pdf, 4 B)"));
assert!(pagetop_mail::outbox::take_to("ana@example.com").is_empty());
let (status, _) = get(&app, "/mail/preview/missing").await;
assert_eq!(status, web::http::StatusCode::NOT_FOUND);
}

View file

@ -23,10 +23,17 @@ pagetop.workspace = true
pagetop-admin.workspace = true pagetop-admin.workspace = true
pagetop-seaorm.workspace = true pagetop-seaorm.workspace = true
pagetop-htmx.workspace = true pagetop-htmx.workspace = true
pagetop-mail.workspace = true
serde.workspace = true serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
serde_qs.workspace = true serde_qs.workspace = true
thiserror.workspace = true thiserror.workspace = true
tokio.workspace = true
# Nombres de usuario
unicode-ident.workspace = true
unicode-normalization.workspace = true
unicode-security.workspace = true
# Criptografía # Criptografía
argon2.workspace = true argon2.workspace = true

View file

@ -2,16 +2,18 @@
use pagetop::prelude::*; use pagetop::prelude::*;
use pagetop_seaorm::db::{ use pagetop_seaorm::db::{
ActiveModelTrait, ActiveValue, ColumnTrait, Condition, EntityTrait, IntoActiveModel, ActiveModelTrait, ActiveValue, ColumnTrait, EntityTrait, IntoActiveModel, PaginatorTrait,
PaginatorTrait, QueryFilter, Set, dbconn, QueryFilter, Set, dbconn,
}; };
use crate::account::UserStatus; use crate::account::UserStatus;
use crate::config::SETTINGS; use crate::config::SETTINGS;
use crate::entity::{role_permission, user}; use crate::entity::{role_permission, user};
use crate::error::AuthError; use crate::error::AuthError;
use crate::identity::{self, Email, Username};
use crate::password; use crate::password;
use crate::permission::UserPermission; use crate::permission::UserPermission;
use crate::service::user_admin::{ensure_email_available, ensure_username_available};
use crate::session; use crate::session;
// **< login >************************************************************************************** // **< login >**************************************************************************************
@ -20,6 +22,11 @@ use crate::session;
/// ///
/// Acepta nombre de usuario o email como primer parámetro. Aplica la política de bloqueo /// Acepta nombre de usuario o email como primer parámetro. Aplica la política de bloqueo
/// por intentos fallidos y rehashea la contraseña si los parámetros de coste han cambiado. /// por intentos fallidos y rehashea la contraseña si los parámetros de coste han cambiado.
///
/// Sólo con la contraseña correcta se informa de que la cuenta está bloqueada
/// ([`AuthError::AccountBlocked`]) o pendiente de verificar ([`AuthError::AccountPending`]): sin
/// ella, cualquiera sabría así qué cuentas existen y en qué estado están. Por lo mismo, sin cuenta
/// se tarda lo mismo que con una contraseña errónea.
pub async fn login( pub async fn login(
username_or_email: &str, username_or_email: &str,
plain_password: &str, plain_password: &str,
@ -27,16 +34,17 @@ pub async fn login(
) -> Result<String, AuthError> { ) -> Result<String, AuthError> {
let now = Utc::now(); let now = Utc::now();
// Buscar usuario por username o email. // Buscar usuario por email o por username, sin distinguir mayúsculas. Un nombre de usuario
let user_model = user::Entity::find() // nunca contiene `@`, así que la entrada sólo puede ser uno de los dos.
.filter( let filter = if username_or_email.contains('@') {
Condition::any() user::Column::EmailKey.eq(identity::email_key(username_or_email))
.add(user::Column::Username.eq(username_or_email)) } else {
.add(user::Column::Email.eq(username_or_email)), user::Column::UsernameKey.eq(identity::username_key(username_or_email))
) };
.one(dbconn()) let Some(user_model) = user::Entity::find().filter(filter).one(dbconn()).await? else {
.await? password::verify_password_without_account(plain_password).await;
.ok_or(AuthError::InvalidCredentials)?; return Err(AuthError::InvalidCredentials);
};
// Comprobar bloqueo temporal por intentos fallidos. // Comprobar bloqueo temporal por intentos fallidos.
if let Some(locked_until) = user_model.locked_until if let Some(locked_until) = user_model.locked_until
@ -45,6 +53,12 @@ pub async fn login(
return Err(AuthError::AccountLocked); return Err(AuthError::AccountLocked);
} }
// Verificar contraseña.
if !password::verify_password_async(plain_password, &user_model.password_hash).await {
register_failed_login(&user_model, now).await?;
return Err(AuthError::InvalidCredentials);
}
// Comprobar estado de la cuenta. // Comprobar estado de la cuenta.
match UserStatus::from_i16(user_model.status) { match UserStatus::from_i16(user_model.status) {
UserStatus::Blocked => return Err(AuthError::AccountBlocked), UserStatus::Blocked => return Err(AuthError::AccountBlocked),
@ -52,12 +66,6 @@ pub async fn login(
UserStatus::Active => {} UserStatus::Active => {}
} }
// Verificar contraseña.
if !password::verify_password(plain_password, &user_model.password_hash) {
register_failed_login(&user_model, now).await?;
return Err(AuthError::InvalidCredentials);
}
// Actualizar last_login_at y resetear contador de fallos. // Actualizar last_login_at y resetear contador de fallos.
let user_id = user_model.id; let user_id = user_model.id;
let needs_rehash = password::needs_rehash(&user_model.password_hash); let needs_rehash = password::needs_rehash(&user_model.password_hash);
@ -65,9 +73,10 @@ pub async fn login(
active.last_login_at = Set(Some(now)); active.last_login_at = Set(Some(now));
active.last_access_at = Set(Some(now)); active.last_access_at = Set(Some(now));
active.failed_login_count = Set(0); active.failed_login_count = Set(0);
active.failed_login_at = Set(None);
active.locked_until = Set(None); active.locked_until = Set(None);
if needs_rehash { if needs_rehash {
let new_hash = password::hash_password(plain_password)?; let new_hash = password::hash_password_async(plain_password).await?;
active.password_hash = Set(new_hash); active.password_hash = Set(new_hash);
} }
active.update(dbconn()).await?; active.update(dbconn()).await?;
@ -91,35 +100,23 @@ pub async fn logout(sid: &str) -> Result<(), AuthError> {
/// Registra un nuevo usuario. Devuelve el `user_id` asignado. /// Registra un nuevo usuario. Devuelve el `user_id` asignado.
/// ///
/// Valida: longitud de contraseña, coincidencia de confirmación, y unicidad de username y email. /// Valida: username según la política de identidad y email (ver
/// [`IdentityPolicy`](crate::config::IdentityPolicy)), longitud de contraseña, coincidencia de
/// confirmación, y que ni el username (o uno que se confunda con él) ni el email estén en uso.
pub async fn register( pub async fn register(
username: &str, username: &str,
email: &str, email: &str,
plain_password: &str, plain_password: &str,
confirm_password: &str, confirm_password: &str,
) -> Result<i32, AuthError> { ) -> Result<i32, AuthError> {
let username = identity::username(username, SETTINGS.identity_policy, None)?;
let email = identity::email(email)?;
password::validate_strength(plain_password)?; password::validate_strength(plain_password)?;
password::passwords_match(plain_password, confirm_password)?; password::passwords_match(plain_password, confirm_password)?;
ensure_username_available(&username, None).await?;
ensure_email_available(&email, None).await?;
// Comprobar unicidad de username y email. let hash = password::hash_password_async(plain_password).await?;
if user::Entity::find()
.filter(user::Column::Username.eq(username))
.one(dbconn())
.await?
.is_some()
{
return Err(AuthError::UsernameTaken);
}
if user::Entity::find()
.filter(user::Column::Email.eq(email))
.one(dbconn())
.await?
.is_some()
{
return Err(AuthError::EmailTaken);
}
let hash = password::hash_password(plain_password)?;
let now = Utc::now(); let now = Utc::now();
let status = if SETTINGS.require_email_verification { let status = if SETTINGS.require_email_verification {
UserStatus::Pending UserStatus::Pending
@ -127,10 +124,8 @@ pub async fn register(
UserStatus::Active UserStatus::Active
}; };
let new_user = user::ActiveModel { let mut new_user = user::ActiveModel {
id: ActiveValue::NotSet, id: ActiveValue::NotSet,
username: Set(username.to_owned()),
email: Set(email.to_owned()),
email_verified_at: Set(None), email_verified_at: Set(None),
password_hash: Set(hash), password_hash: Set(hash),
status: Set(status.as_i16()), status: Set(status.as_i16()),
@ -146,7 +141,10 @@ pub async fn register(
is_admin: Set(false), is_admin: Set(false),
created_at: Set(now), created_at: Set(now),
updated_at: Set(now), updated_at: Set(now),
..Default::default()
}; };
username.set_on(&mut new_user);
email.set_on(&mut new_user);
let result = user::Entity::insert(new_user).exec(dbconn()).await?; let result = user::Entity::insert(new_user).exec(dbconn()).await?;
let user_id = result.last_insert_id; let user_id = result.last_insert_id;
@ -169,11 +167,11 @@ pub(crate) async fn change_own_password(
.one(dbconn()) .one(dbconn())
.await? .await?
.ok_or(AuthError::UserNotFound)?; .ok_or(AuthError::UserNotFound)?;
if !password::verify_password(current_password, &user_model.password_hash) { if !password::verify_password_async(current_password, &user_model.password_hash).await {
return Err(AuthError::InvalidCredentials); return Err(AuthError::InvalidCredentials);
} }
password::validate_strength(new_password)?; password::validate_strength(new_password)?;
let hash = password::hash_password(new_password)?; let hash = password::hash_password_async(new_password).await?;
user::ActiveModel { user::ActiveModel {
id: Set(user_id), id: Set(user_id),
@ -197,16 +195,21 @@ async fn register_failed_login(
user_model: &user::Model, user_model: &user::Model,
now: DateTime<Utc>, now: DateTime<Utc>,
) -> Result<(), AuthError> { ) -> Result<(), AuthError> {
let new_count = user_model.failed_login_count + 1; let (count, locked_until) = failed_login_outcome(
let lock_at = if new_count >= SETTINGS.max_failed_logins { user_model.failed_login_count,
Some(now + Duration::seconds(SETTINGS.locked_for_secs)) user_model.failed_login_at,
} else { now,
None FailedLoginPolicy {
}; max: SETTINGS.max_failed_logins,
window: Duration::seconds(SETTINGS.failed_login_window_secs),
locked_for: Duration::seconds(SETTINGS.locked_for_secs),
},
);
user::ActiveModel { user::ActiveModel {
id: Set(user_model.id), id: Set(user_model.id),
failed_login_count: Set(new_count), failed_login_count: Set(count),
locked_until: Set(lock_at), failed_login_at: Set(Some(now)),
locked_until: Set(locked_until),
updated_at: Set(now), updated_at: Set(now),
..Default::default() ..Default::default()
} }
@ -215,6 +218,34 @@ async fn register_failed_login(
Ok(()) Ok(())
} }
struct FailedLoginPolicy {
max: i32,
window: Duration,
locked_for: Duration,
}
// Nuevo recuento tras un intento fallido en `now` y, si alcanza el máximo, hasta cuándo queda
// bloqueada la cuenta. Un fallo cuenta junto a los anteriores sólo si el último fue hace menos de
// la ventana; si no, el recuento empieza de nuevo. Al bloquear, el recuento vuelve a cero para
// que, pasado el bloqueo, se disponga otra vez de todos los intentos. Con un máximo de `0` nunca
// se bloquea.
fn failed_login_outcome(
count: i32,
last_failed: Option<DateTime<Utc>>,
now: DateTime<Utc>,
policy: FailedLoginPolicy,
) -> (i32, Option<DateTime<Utc>>) {
let count = match last_failed {
Some(t) if now - t < policy.window => count.saturating_add(1),
_ => 1,
};
if policy.max > 0 && count >= policy.max {
(0, Some(now + policy.locked_for))
} else {
(count, None)
}
}
// **< seed_initial_data >************************************************************************** // **< seed_initial_data >**************************************************************************
/// Prepara una instalación nueva si no existe ningún usuario en la base de datos. /// Prepara una instalación nueva si no existe ningún usuario en la base de datos.
@ -226,11 +257,27 @@ async fn register_failed_login(
/// Concede además al rol "authenticated" los permisos que todo usuario espera tener sobre su /// Concede además al rol "authenticated" los permisos que todo usuario espera tener sobre su
/// propia cuenta: editar su perfil y cambiar su contraseña. Sólo en la instalación nueva; después /// propia cuenta: editar su perfil y cambiar su contraseña. Sólo en la instalación nueva; después
/// los gestiona el administrador desde la interfaz. /// los gestiona el administrador desde la interfaz.
pub(crate) async fn seed_initial_data() { ///
do_seed().await; /// Falla con [`AuthError::InvalidSetting`] si el nombre de usuario o el email configurados no son
/// válidos, aunque ya existan usuarios, como cualquier otro ajuste no válido.
pub(crate) async fn seed_initial_data() -> Result<(), AuthError> {
let cfg = &SETTINGS.seed;
let username = identity::username(&cfg.admin_username, SETTINGS.identity_policy, None)
.map_err(|err| invalid_setting("user.seed.admin_username", err))?;
let email = identity::email(&cfg.admin_email)
.map_err(|err| invalid_setting("user.seed.admin_email", err))?;
do_seed(username, email).await;
Ok(())
} }
async fn do_seed() { fn invalid_setting(key: &'static str, source: AuthError) -> AuthError {
AuthError::InvalidSetting {
key,
source: Box::new(source),
}
}
async fn do_seed(username: Username, email: Email) {
let count = user::Entity::find().count(dbconn()).await.unwrap_or(1); let count = user::Entity::find().count(dbconn()).await.unwrap_or(1);
if count > 0 { if count > 0 {
return; return;
@ -261,10 +308,9 @@ async fn do_seed() {
}; };
let now = Utc::now(); let now = Utc::now();
let new_admin = user::ActiveModel { let admin_username = username.value().to_owned();
let mut new_admin = user::ActiveModel {
id: ActiveValue::NotSet, id: ActiveValue::NotSet,
username: Set(cfg.admin_username.clone()),
email: Set(cfg.admin_email.clone()),
email_verified_at: Set(Some(now)), email_verified_at: Set(Some(now)),
password_hash: Set(hash), password_hash: Set(hash),
status: Set(UserStatus::Active.as_i16()), status: Set(UserStatus::Active.as_i16()),
@ -280,14 +326,17 @@ async fn do_seed() {
is_admin: Set(true), is_admin: Set(true),
created_at: Set(now), created_at: Set(now),
updated_at: Set(now), updated_at: Set(now),
..Default::default()
}; };
username.set_on(&mut new_admin);
email.set_on(&mut new_admin);
match user::Entity::insert(new_admin).exec(dbconn()).await { match user::Entity::insert(new_admin).exec(dbconn()).await {
Ok(_) => { Ok(_) => {
if generated { if generated {
println!( println!(
"\npagetop-user: admin account created.\n username: {}\n password: {}\n", "\npagetop-user: admin account created.\n username: {}\n password: {}\n",
cfg.admin_username, admin_password admin_username, admin_password
); );
} }
} }
@ -316,3 +365,50 @@ async fn do_seed() {
); );
} }
} }
#[cfg(test)]
mod tests {
use super::*;
fn at(secs: i64) -> DateTime<Utc> {
DateTime::from_timestamp(1_800_000_000 + secs, 0).unwrap()
}
fn outcome(count: i32, last: Option<i64>, now: i64) -> (i32, Option<DateTime<Utc>>) {
let policy = FailedLoginPolicy {
max: 3,
window: Duration::seconds(900),
locked_for: Duration::seconds(600),
};
failed_login_outcome(count, last.map(at), at(now), policy)
}
#[pagetop::test]
async fn failures_within_the_window_accumulate() {
assert_eq!(outcome(0, None, 0), (1, None));
assert_eq!(outcome(1, Some(0), 100), (2, None));
}
#[pagetop::test]
async fn reaching_the_maximum_locks_and_resets_the_count() {
assert_eq!(outcome(2, Some(0), 100), (0, Some(at(700))));
}
#[pagetop::test]
async fn zero_maximum_never_locks() {
let policy = FailedLoginPolicy {
max: 0,
window: Duration::seconds(900),
locked_for: Duration::seconds(600),
};
assert_eq!(
failed_login_outcome(9, Some(at(0)), at(1), policy),
(10, None)
);
}
#[pagetop::test]
async fn a_failure_after_the_window_starts_a_new_count() {
assert_eq!(outcome(2, Some(0), 900), (1, None));
}
}

View file

@ -7,6 +7,7 @@ use crate::LOCALES_USER;
use crate::role_path; use crate::role_path;
use crate::component::error_banner; use crate::component::error_banner;
use crate::service::role_admin::{ROLE_LABEL_MAX_CHARS, ROLE_MACHINE_NAME_MAX_CHARS};
#[derive(AutoDefault, Clone, Copy, Debug, PartialEq)] #[derive(AutoDefault, Clone, Copy, Debug, PartialEq)]
pub(crate) enum RoleFormMode { pub(crate) enum RoleFormMode {
@ -48,7 +49,7 @@ impl Component for RoleForm {
.with_label(Lc::t("field-machine-name", &LOCALES_USER)) .with_label(Lc::t("field-machine-name", &LOCALES_USER))
.with_help_text(Lc::t("help-machine-name-immutable", &LOCALES_USER)) .with_help_text(Lc::t("help-machine-name-immutable", &LOCALES_USER))
.with_required(true) .with_required(true)
.with_maxlength(Some(64)), .with_maxlength(ROLE_MACHINE_NAME_MAX_CHARS),
RoleFormMode::Edit => form::input::Field::text() RoleFormMode::Edit => form::input::Field::text()
.with_name("machine_name") .with_name("machine_name")
.with_value(self.machine_name()) .with_value(self.machine_name())
@ -68,7 +69,7 @@ impl Component for RoleForm {
.with_value(self.label()) .with_value(self.label())
.with_label(Lc::t("field-label", &LOCALES_USER)) .with_label(Lc::t("field-label", &LOCALES_USER))
.with_required(true) .with_required(true)
.with_maxlength(Some(128)), .with_maxlength(ROLE_LABEL_MAX_CHARS),
) )
.with_child( .with_child(
form::Textarea::new() form::Textarea::new()

View file

@ -6,6 +6,7 @@ use pagetop_htmx::hx_table::sort_link;
use crate::ADMIN_ROLES_PATH; use crate::ADMIN_ROLES_PATH;
use crate::LOCALES_USER; use crate::LOCALES_USER;
use crate::permission::UserPermission;
use crate::role_path; use crate::role_path;
use crate::service::role_admin::{RoleListItem, RoleSortField}; use crate::service::role_admin::{RoleListItem, RoleSortField};
@ -227,8 +228,8 @@ fn label_cell(role: &RoleListItem, waypoint: &Waypoint) -> Html {
}) })
} }
// Construye la celda de acciones: gestionar permisos siempre, y editar/borrar sólo si el rol no // Construye la celda de acciones: gestionar permisos si se tiene `user:admin_permissions`, y
// está bloqueado por el sistema. Devuelve un componente `Html` para que el marcado se genere cuando // editar/borrar sólo si el rol no está bloqueado por el sistema. Devuelve un componente `Html` para que el marcado se genere cuando
// `Table` renderice la celda, no al construir la fila. // `Table` renderice la celda, no al construir la fila.
async fn actions_cell( async fn actions_cell(
role: &RoleListItem, role: &RoleListItem,
@ -242,20 +243,29 @@ async fn actions_cell(
let locked = role.locked; let locked = role.locked;
let waypoint = waypoint.clone(); let waypoint = waypoint.clone();
let permissions_href = waypoint.append_to(cx.route(role_path(id, "permissions"))); let can_manage_permissions = cx
.request()
.is_some_and(|request| has_permission(request, &UserPermission::AdminPermissions));
// Los botones se renderizan aquí, no dentro del `Html::with()` de abajo: necesitan pasar por su // Los botones se renderizan aquí, no dentro del `Html::with()` de abajo: necesitan pasar por su
// propio ciclo de renderizado (`.render().await`) para que el tema activo los estilice igual // propio ciclo de renderizado (`.render().await`) para que el tema activo los estilice igual
// (ver `pagetop-bootsier::theme::bs::button`), incluida la traducción de `data-dialog-*` que // (ver `pagetop-bootsier::theme::bs::button`), incluida la traducción de `data-dialog-*` que
// usa el botón de borrado. // usa el botón de borrado.
let permissions_button = Button::anchor( let permissions_button = if can_manage_permissions {
let permissions_href = waypoint.append_to(cx.route(role_path(id, "permissions")));
Some(
Button::anchor(
Lc::t("btn-manage-permissions", &LOCALES_USER), Lc::t("btn-manage-permissions", &LOCALES_USER),
permissions_href, permissions_href,
) )
.with_style(button::Style::Solid(Intent::Neutral)) .with_style(button::Style::Solid(Intent::Neutral))
.with_size(button::Size::Small) .with_size(button::Size::Small)
.render(cx) .render(cx)
.await; .await,
)
} else {
None
};
let (edit_button, delete_button) = if locked { let (edit_button, delete_button) = if locked {
(None, None) (None, None)
@ -290,15 +300,11 @@ async fn actions_cell(
}; };
Html::with(move |_cx| { Html::with(move |_cx| {
let buttons = [&permissions_button, &edit_button, &delete_button];
html! { html! {
(permissions_button) @for (i, button) in buttons.into_iter().flatten().enumerate() {
@if let Some(edit_button) = &edit_button { @if i > 0 { " " }
" " (button)
(edit_button)
}
@if let Some(delete_button) = &delete_button {
" "
(delete_button)
} }
} }
}) })

View file

@ -3,12 +3,13 @@
use pagetop::prelude::*; use pagetop::prelude::*;
use crate::LOCALES_USER; use crate::LOCALES_USER;
use crate::config::{user_language_applies, user_timezone_applies}; use crate::config::{SETTINGS, user_language_applies, user_timezone_applies};
use crate::user_path; use crate::user_path;
use crate::{ADMIN_USERS_PATH, PROFILE_EDIT_PATH}; use crate::{ADMIN_USERS_PATH, PROFILE_EDIT_PATH};
use crate::component::{PasswordConfirm, error_banner}; use crate::component::{PasswordConfirm, error_banner};
use crate::service::user_admin::ABOUT_MAX_CHARS; use crate::identity::{EMAIL_MAX_CHARS, USERNAME_MIN_CHARS, username_help, username_max_chars};
use crate::service::user_admin::{ABOUT_MAX_CHARS, DISPLAY_NAME_MAX_CHARS};
use super::{USER_ADMIN_FORM_ID, roles_fieldset}; use super::{USER_ADMIN_FORM_ID, roles_fieldset};
@ -71,22 +72,30 @@ impl Component for UserForm {
.with_name("username") .with_name("username")
.with_value(self.username()) .with_value(self.username())
.with_label(Lc::t("field-username-admin", &LOCALES_USER)) .with_label(Lc::t("field-username-admin", &LOCALES_USER))
.with_help_text(if username_readonly {
Lc::none()
} else {
username_help(SETTINGS.identity_policy)
})
.with_required(true) .with_required(true)
.with_readonly(username_readonly) .with_readonly(username_readonly)
.with_maxlength(Some(64)), .with_minlength(USERNAME_MIN_CHARS)
.with_maxlength(username_max_chars(SETTINGS.identity_policy)),
) )
.with_child( .with_child(
form::input::Field::email() form::input::Field::email()
.with_name("email") .with_name("email")
.with_value(self.email()) .with_value(self.email())
.with_label(Lc::t("field-email", &LOCALES_USER)) .with_label(Lc::t("field-email", &LOCALES_USER))
.with_required(true), .with_required(true)
.with_maxlength(EMAIL_MAX_CHARS),
) )
.with_child( .with_child(
form::input::Field::text() form::input::Field::text()
.with_name("display_name") .with_name("display_name")
.with_value(self.display_name()) .with_value(self.display_name())
.with_label(Lc::t("field-display-name", &LOCALES_USER)), .with_label(Lc::t("field-display-name", &LOCALES_USER))
.with_maxlength(DISPLAY_NAME_MAX_CHARS),
); );
// Sólo se ofrecen si se aplican (ver `config::user_language_applies()` y // Sólo se ofrecen si se aplican (ver `config::user_language_applies()` y

View file

@ -9,6 +9,8 @@ use crate::{LOCALES_USER, LOGIN_PATH, PASSWORD_RESET_PATH, REGISTER_PATH};
#[derive(AutoDefault, Clone, Debug, Getters)] #[derive(AutoDefault, Clone, Debug, Getters)]
pub struct LoginForm { pub struct LoginForm {
error: Option<Lc>, error: Option<Lc>,
/// Usuario o email con el que se rellena el campo.
username: String,
/// Página a la que volver tras iniciar sesión. /// Página a la que volver tras iniciar sesión.
waypoint: Waypoint, waypoint: Waypoint,
} }
@ -32,6 +34,7 @@ impl Component for LoginForm {
form::input::Field::text().with_autocomplete(Some(form::Autocomplete::username())) form::input::Field::text().with_autocomplete(Some(form::Autocomplete::username()))
} }
.with_name(if strict { "ident" } else { "username" }) .with_name(if strict { "ident" } else { "username" })
.with_value(self.username())
.with_label(Lc::t("field-username", &LOCALES_USER)) .with_label(Lc::t("field-username", &LOCALES_USER))
.with_autofocus(true) .with_autofocus(true)
.with_required(true); .with_required(true);
@ -104,6 +107,12 @@ impl LoginForm {
self self
} }
/// Rellena el usuario o email, p. ej. con el enviado si el inicio de sesión falla.
pub fn with_username(mut self, username: impl Into<String>) -> Self {
self.username = username.into();
self
}
pub fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self { pub fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self {
self.waypoint = waypoint.into(); self.waypoint = waypoint.into();
self self

View file

@ -4,11 +4,13 @@
use pagetop::prelude::*; use pagetop::prelude::*;
use crate::LOCALES_USER; use crate::LOCALES_USER;
use crate::config::SETTINGS;
/// Campos de contraseña y confirmación, compuestos a partir de /// Campos de contraseña y confirmación, compuestos a partir de
/// [`form::input::Field::password()`] del core. No valida en ningún momento que ambos valores /// [`form::input::Field::password()`] del core. No valida en ningún momento que ambos valores
/// coincidan (eso ocurre en el servidor, tras el envío del formulario), sólo renderiza los dos /// coincidan (eso ocurre en el servidor, tras el envío del formulario), sólo renderiza los dos
/// campos, uno junto al otro, sin ningún contenedor propio. /// campos, uno junto al otro, sin ningún contenedor propio. El de la contraseña indica la longitud
/// mínima configurada (`user.password.min_length`), como ayuda y con `minlength`.
#[derive(AutoDefault, Clone, Debug, Getters)] #[derive(AutoDefault, Clone, Debug, Getters)]
pub(crate) struct PasswordConfirm { pub(crate) struct PasswordConfirm {
/// Devuelve la etiqueta del campo de contraseña. /// Devuelve la etiqueta del campo de contraseña.
@ -21,7 +23,7 @@ pub(crate) struct PasswordConfirm {
impl Component for PasswordConfirm { impl Component for PasswordConfirm {
// Las etiquetas por defecto cubren los dos casos más habituales (alta de cuenta, alta de // Las etiquetas por defecto cubren los dos casos más habituales (alta de cuenta, alta de
// usuario desde administración); `with_password_label()` cubre los casos distintos // usuario desde administración); `with_password_label()` cubre los casos distintos
// (restablecimiento por un administrador y cambio de la contraseña propia). // (restablecimientos y cambio de la contraseña propia).
fn new() -> Self { fn new() -> Self {
Self { Self {
password_label: Lc::t("field-password", &LOCALES_USER), password_label: Lc::t("field-password", &LOCALES_USER),
@ -30,10 +32,19 @@ impl Component for PasswordConfirm {
} }
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> { async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
// `minlength` cuenta unidades UTF-16 y el servidor caracteres: con caracteres fuera del
// plano básico (emojis) el navegador puede aceptar una contraseña que el servidor rechaza,
// pero nunca al revés.
let min_length = SETTINGS.password.min_length;
let mut password = form::input::Field::password() let mut password = form::input::Field::password()
.with_name("password") .with_name("password")
.with_label(self.password_label().clone()) .with_label(self.password_label().clone())
.with_help_text(
Lc::t("help-password-min-length", &LOCALES_USER)
.with_number("n", u32::try_from(min_length).unwrap_or(u32::MAX)),
)
.with_autocomplete(Some(form::Autocomplete::new_password())) .with_autocomplete(Some(form::Autocomplete::new_password()))
.with_minlength(u16::try_from(min_length).unwrap_or(u16::MAX))
.with_required(true); .with_required(true);
let mut confirm = form::input::Field::password() let mut confirm = form::input::Field::password()
.with_name("confirm_password") .with_name("confirm_password")

View file

@ -3,7 +3,7 @@
use pagetop::prelude::*; use pagetop::prelude::*;
use crate::LOCALES_USER; use crate::LOCALES_USER;
use crate::component::error_banner; use crate::component::{PasswordConfirm, error_banner};
#[derive(AutoDefault, Clone, Debug)] #[derive(AutoDefault, Clone, Debug)]
pub struct PasswordResetConfirmForm { pub struct PasswordResetConfirmForm {
@ -24,19 +24,8 @@ impl Component for PasswordResetConfirmForm {
.with_method(form::Method::Post) .with_method(form::Method::Post)
.with_child(error_banner(self.error.clone())) .with_child(error_banner(self.error.clone()))
.with_child( .with_child(
form::input::Field::password() PasswordConfirm::new()
.with_name("password") .with_password_label(Lc::t("field-new-password", &LOCALES_USER)),
.with_label(Lc::t("field-new-password", &LOCALES_USER))
.with_autocomplete(Some(form::Autocomplete::new_password()))
.with_autofocus(true)
.with_required(true),
)
.with_child(
form::input::Field::password()
.with_name("confirm_password")
.with_label(Lc::t("field-confirm-password", &LOCALES_USER))
.with_autocomplete(Some(form::Autocomplete::new_password()))
.with_required(true),
) )
.with_child(Button::submit(Lc::t("btn-set-password", &LOCALES_USER))); .with_child(Button::submit(Lc::t("btn-set-password", &LOCALES_USER)));

View file

@ -5,10 +5,14 @@ use pagetop::prelude::*;
use crate::LOCALES_USER; use crate::LOCALES_USER;
use crate::REGISTER_PATH; use crate::REGISTER_PATH;
use crate::component::{PasswordConfirm, error_banner}; use crate::component::{PasswordConfirm, error_banner};
use crate::config::SETTINGS;
use crate::identity::{EMAIL_MAX_CHARS, USERNAME_MIN_CHARS, username_help, username_max_chars};
#[derive(AutoDefault, Clone, Debug)] #[derive(AutoDefault, Clone, Debug)]
pub struct RegisterForm { pub struct RegisterForm {
error: Option<Lc>, error: Option<Lc>,
username: String,
email: String,
} }
#[async_trait] #[async_trait]
@ -26,7 +30,11 @@ impl Component for RegisterForm {
.with_child( .with_child(
form::input::Field::text() form::input::Field::text()
.with_name("username") .with_name("username")
.with_label(Lc::t("field-username", &LOCALES_USER)) .with_value(&self.username)
.with_label(Lc::t("field-username-admin", &LOCALES_USER))
.with_help_text(username_help(SETTINGS.identity_policy))
.with_minlength(USERNAME_MIN_CHARS)
.with_maxlength(username_max_chars(SETTINGS.identity_policy))
.with_autocomplete(Some(form::Autocomplete::username())) .with_autocomplete(Some(form::Autocomplete::username()))
.with_autofocus(true) .with_autofocus(true)
.with_required(true), .with_required(true),
@ -34,7 +42,9 @@ impl Component for RegisterForm {
.with_child( .with_child(
form::input::Field::email() form::input::Field::email()
.with_name("email") .with_name("email")
.with_value(&self.email)
.with_label(Lc::t("field-email", &LOCALES_USER)) .with_label(Lc::t("field-email", &LOCALES_USER))
.with_maxlength(EMAIL_MAX_CHARS)
.with_autocomplete(Some(form::Autocomplete::email())) .with_autocomplete(Some(form::Autocomplete::email()))
.with_required(true), .with_required(true),
) )
@ -51,4 +61,16 @@ impl RegisterForm {
self.error = error.into(); self.error = error.into();
self self
} }
/// Rellena el nombre de usuario, p. ej. con el enviado si el registro falla.
pub fn with_username(mut self, username: impl Into<String>) -> Self {
self.username = username.into();
self
}
/// Rellena el email, p. ej. con el enviado si el registro falla.
pub fn with_email(mut self, email: impl Into<String>) -> Self {
self.email = email.into();
self
}
} }

View file

@ -5,6 +5,7 @@
//! ```toml //! ```toml
//! [user] //! [user]
//! allow_registration = false //! allow_registration = false
//! identity_policy = "unicode"
//! //!
//! [user.session] //! [user.session]
//! secure_cookie = true //! secure_cookie = true
@ -23,12 +24,15 @@
//! //!
//! Todas las opciones, con su valor por defecto, se documentan en [`UserSettings`] y sus //! Todas las opciones, con su valor por defecto, se documentan en [`UserSettings`] y sus
//! subsecciones ([`SessionSettings`], [`PasswordSettings`], [`SeedSettings`] y [`AdminSettings`]). //! subsecciones ([`SessionSettings`], [`PasswordSettings`], [`SeedSettings`] y [`AdminSettings`]).
//! Las reglas de los nombres de usuario y del email se explican en [`IdentityPolicy`].
//! //!
//! Consulta [`pagetop::config`] para ver cómo PageTop lee los archivos de configuración y aplica //! Consulta [`pagetop::config`] para ver cómo PageTop lee los archivos de configuración y aplica
//! los valores a los ajustes. //! los valores a los ajustes.
use pagetop::prelude::*; use pagetop::prelude::*;
use serde::Deserialize;
/// Ajustes de la sección `[user]`, cargados al arrancar la aplicación. /// Ajustes de la sección `[user]`, cargados al arrancar la aplicación.
pub static SETTINGS: LazySettings<UserSettings> = LazySettings::new(); pub static SETTINGS: LazySettings<UserSettings> = LazySettings::new();
@ -38,18 +42,28 @@ pub struct UserSettings {
/// Permite que los visitantes creen su propia cuenta. /// Permite que los visitantes creen su propia cuenta.
#[default = true] #[default = true]
pub allow_registration: bool, pub allow_registration: bool,
/// Las cuentas nuevas quedan pendientes (*"Pending"*) en lugar de activas hasta verificar el /// Las cuentas nuevas quedan pendientes (*"Pending"*) en lugar de activas hasta que su titular
/// correo. /// confirma su dirección desde el enlace del correo de verificación que se le envía al
/// registrarse.
#[default = false] #[default = false]
pub require_email_verification: bool, pub require_email_verification: bool,
/// Qué nombres de usuario se aceptan. Ver [`IdentityPolicy`].
pub identity_policy: IdentityPolicy,
/// Intentos fallidos de acceso antes de bloquear la cuenta. /// Intentos fallidos de acceso seguidos que bloquean temporalmente la cuenta.
///
/// Un fallo se suma a los anteriores si llega antes de
/// [`failed_login_window_secs`](Self::failed_login_window_secs) desde el último; si no, el
/// recuento empieza de nuevo. Un acceso correcto o una recuperación de contraseña lo ponen a
/// cero, y al bloquear también vuelve a cero, así que pasado el bloqueo se dispone otra vez de
/// todos los intentos. Con `0` no se bloquea nunca.
#[default = 5] #[default = 5]
pub max_failed_logins: i32, pub max_failed_logins: i32,
/// Ventana de recuento de intentos fallidos, en segundos. Reservada: todavía no tiene efecto. /// Segundos desde el último intento fallido en los que el siguiente se suma al recuento.
#[default = 900] #[default = 900]
pub failed_login_window_secs: i64, pub failed_login_window_secs: i64,
/// Duración del bloqueo de la cuenta, en segundos. /// Duración del bloqueo de la cuenta, en segundos. Durante el bloqueo se rechaza el acceso
/// aunque la contraseña sea correcta.
#[default = 600] #[default = 600]
pub locked_for_secs: i64, pub locked_for_secs: i64,
@ -71,6 +85,105 @@ pub struct UserSettings {
pub login_strict: bool, pub login_strict: bool,
} }
/// Política de identidad: qué nombres de usuario se aceptan al crear una cuenta o al cambiar su
/// nombre. Usado en [`UserSettings::identity_policy`].
///
/// Cada nivel admite todo lo del anterior y algo más:
///
/// | Valor | Caracteres | Longitud | Como en |
/// |---|---|---|---|
/// | `"strict"` (defecto) | Letras ASCII sin tildes, dígitos, `.`, `_`, `-` | 3 a 32 | Kanidm |
/// | `"unicode"` | Letras y dígitos de cualquier alfabeto, `.`, `_`, `-` | 3 a 32 | RFC 8265 |
/// | `"permissive"` | Los de `"unicode"`, espacios simples, `'` y `+` | 3 a 60 | Drupal |
///
/// # Reglas comunes
///
/// Con cualquier política:
///
/// - Se ignoran los espacios al principio y al final, y el texto se normaliza (Unicode NFKC): las
/// formas equivalentes de un mismo carácter, como `é` compuesta o con la tilde aparte, o las
/// letras de ancho completo (`Ana`), cuentan como la misma, y el nombre se guarda ya
/// normalizado (`Ana`).
/// - El nombre empieza por una letra o un dígito.
/// - **Nunca se admite `@`.** El email es un dato aparte y obligatorio, y también sirve para
/// iniciar sesión: sin `@`, un nombre de usuario nunca se confunde con el email de otra cuenta.
/// - El nombre se guarda con sus mayúsculas, pero **no se distinguen**: `Ana` y `ana` son el mismo
/// usuario al iniciar sesión, y no pueden existir los dos.
/// - **No se admiten nombres que se confunden a simple vista con otro existente**, según la tabla
/// de caracteres confusables de Unicode (UTS #39): si existe `maria`, no se puede crear
/// `rnaria`; si existe `admin`, tampoco `аdmin` con una `а` cirílica.
///
/// Con `"unicode"` y `"permissive"`, además, un nombre no puede mezclar alfabetos (`pаypal`, con
/// una `а` cirílica entre letras latinas), salvo las combinaciones habituales de una misma
/// escritura (como kanji y kana en japonés), ni usar caracteres que Unicode desaconseja en
/// identificadores (invisibles, obsoletos o de control). En `"permissive"` tampoco se admiten
/// dos espacios seguidos.
///
/// El email se valida igual con cualquier política: el formato que exige `pagetop-mail` para poder
/// enviarle correos, hasta 254 caracteres, y sin distinguir mayúsculas.
///
/// # Elegir una política
///
/// El riesgo no depende tanto de dónde se publica la aplicación como de **quién elige los
/// nombres**. Con el registro abierto (`allow_registration`), cualquiera escoge un nombre que verán
/// otros usuarios y que aparece en el saludo de sus correos en cuanto verifica su dirección. Si las
/// cuentas sólo las crean administradores, ese riesgo casi desaparece.
///
/// | Situación | Política |
/// |---|---|
/// | Aplicación en Internet con registro abierto | `"strict"` |
/// | Comunidad en Internet cuyos usuarios escriben su nombre en su alfabeto | `"unicode"` |
/// | Aplicación interna con cuentas creadas por administradores | `"strict"` o `"unicode"` |
/// | Importar cuentas de un sistema con espacios en los nombres (Drupal...) | `"permissive"` |
///
/// `"strict"` es la más segura y basta en la mayoría de las aplicaciones: los nombres con tildes o
/// en otros alfabetos tienen su sitio en el nombre visible del usuario (`display_name`).
/// `"unicode"` permite que el nombre de usuario se escriba en el idioma de cada persona, con la
/// misma protección contra nombres que se confunden. `"permissive"` no es aconsejable con el
/// registro abierto: los espacios permiten escribir frases («Soporte técnico», «Llama al 900...»)
/// que luego aparecen donde se muestra el nombre, también en el saludo de los correos.
///
/// # Cambiar de política
///
/// La política sólo decide qué nombres **nuevos** se aceptan: buscar y comparar usuarios funciona
/// igual con cualquiera, así que nadie pierde el acceso al cambiarla.
///
/// - **A una más abierta** (de `"strict"` a `"unicode"`, por ejemplo), las cuentas existentes no
/// cambian. Los nombres nuevos pueden usar más caracteres, y siguen sin poder confundirse con
/// ninguno de los existentes.
/// - **A una más estricta**, los nombres que ya no la cumplen (o que superan la nueva longitud
/// máxima) se conservan: sus titulares pueden iniciar sesión y guardar su perfil, incluso
/// cambiando sólo las mayúsculas de su nombre. Pero si alguien lo cambia, el propio usuario o un
/// administrador, el nuevo nombre debe cumplir la política. No hay renombrado automático: para
/// ajustar los nombres existentes, un administrador los cambia a mano.
/// - **El administrador inicial** ([`SeedSettings::admin_username`]) se comprueba en cada
/// arranque, aunque ya exista. Si deja de cumplir la política, la aplicación no arranca hasta
/// que se configure un nombre válido. Cambiar ese ajuste no renombra al administrador existente:
/// sólo se usa para crearlo cuando la base de datos está vacía. Con el valor por defecto,
/// `"admin"`, no ocurre con ninguna política.
///
/// # Referencias
///
/// - [UAX #15](https://www.unicode.org/reports/tr15/): formas de normalización (NFKC).
/// - [UAX #31](https://www.unicode.org/reports/tr31/): qué caracteres forman un identificador.
/// - [UTS #39](https://www.unicode.org/reports/tr39/): caracteres confusables, mezcla de alfabetos
/// y caracteres desaconsejados en identificadores.
/// - [RFC 8265](https://www.rfc-editor.org/rfc/rfc8265): nombres de usuario internacionales
/// (PRECIS), el modelo de `"unicode"`.
#[derive(AutoDefault, Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum IdentityPolicy {
/// Letras ASCII sin tildes, dígitos, `.`, `_` y `-`, de 3 a 32 caracteres.
#[default]
Strict,
/// Letras y dígitos de cualquier alfabeto, `.`, `_` y `-`, de 3 a 32 caracteres, sin mezclar
/// alfabetos.
Unicode,
/// Lo mismo que [`Unicode`](Self::Unicode), más espacios simples, `'` y `+`, de 3 a 60
/// caracteres.
Permissive,
}
/// Subsección **`[user.session]`** de la configuración. /// Subsección **`[user.session]`** de la configuración.
#[settings] #[settings]
pub struct SessionSettings { pub struct SessionSettings {
@ -112,11 +225,11 @@ pub struct SessionSettings {
/// Subsección **`[user.password]`** de la configuración. /// Subsección **`[user.password]`** de la configuración.
/// ///
/// Las contraseñas se cifran con Argon2id. /// Las contraseñas se cifran con Argon2id. Si cambia cualquiera de sus tres costes, cada contraseña
/// se vuelve a cifrar con los nuevos en el siguiente acceso de su usuario.
#[settings] #[settings]
pub struct PasswordSettings { pub struct PasswordSettings {
/// Coste de memoria de Argon2id, en KiB. Si cambia, las contraseñas se vuelven a cifrar en el /// Coste de memoria de Argon2id, en KiB.
/// siguiente acceso de cada usuario.
#[default = 19_456] #[default = 19_456]
pub argon2_m_cost: u32, pub argon2_m_cost: u32,
/// Coste de tiempo de Argon2id (número de iteraciones). /// Coste de tiempo de Argon2id (número de iteraciones).
@ -125,7 +238,7 @@ pub struct PasswordSettings {
/// Grado de paralelismo de Argon2id (número de hilos). /// Grado de paralelismo de Argon2id (número de hilos).
#[default = 1] #[default = 1]
pub argon2_p_cost: u32, pub argon2_p_cost: u32,
/// Longitud mínima de las contraseñas. /// Longitud mínima de las contraseñas, en caracteres.
#[default = 8] #[default = 8]
pub min_length: usize, pub min_length: usize,
} }
@ -135,10 +248,12 @@ pub struct PasswordSettings {
/// El primer administrador, que se crea si no existe ningún usuario. /// El primer administrador, que se crea si no existe ningún usuario.
#[settings] #[settings]
pub struct SeedSettings { pub struct SeedSettings {
/// Nombre de usuario del primer administrador. /// Nombre de usuario del primer administrador. Debe cumplir la política de identidad
/// configurada ([`IdentityPolicy`]); si no, la aplicación no arranca.
#[default = "admin"] #[default = "admin"]
pub admin_username: String, pub admin_username: String,
/// Correo electrónico del primer administrador. /// Correo electrónico del primer administrador. Si no es una dirección válida, la aplicación no
/// arranca.
#[default = "admin@example.com"] #[default = "admin@example.com"]
pub admin_email: String, pub admin_email: String,
/// Contraseña del primer administrador. Sin valor, se genera una aleatoria y se muestra una /// Contraseña del primer administrador. Sin valor, se genera una aleatoria y se muestra una

View file

@ -8,8 +8,10 @@ use pagetop::prelude::*;
use pagetop_seaorm::db::{ActiveValue, ColumnTrait, EntityTrait, QueryFilter, Set, dbconn}; use pagetop_seaorm::db::{ActiveValue, ColumnTrait, EntityTrait, QueryFilter, Set, dbconn};
use crate::account::UserStatus; use crate::account::UserStatus;
use crate::config::SETTINGS;
use crate::entity::{role, user, user_role}; use crate::entity::{role, user, user_role};
use crate::error::AuthError; use crate::error::AuthError;
use crate::identity;
use crate::password; use crate::password;
const ROLE_COUNT: usize = 25; const ROLE_COUNT: usize = 25;
@ -80,10 +82,11 @@ async fn create_demo_users(role_ids: &[i32]) -> Result<(), AuthError> {
let now = Utc::now(); let now = Utc::now();
for n in 1..=USER_COUNT { for n in 1..=USER_COUNT {
let new_user = user::ActiveModel { let username =
identity::username(&format!("demo_user_{n:02}"), SETTINGS.identity_policy, None)?;
let email = identity::email(&format!("demo_user_{n:02}@example.com"))?;
let mut new_user = user::ActiveModel {
id: ActiveValue::NotSet, id: ActiveValue::NotSet,
username: Set(format!("demo_user_{n:02}")),
email: Set(format!("demo_user_{n:02}@example.com")),
email_verified_at: Set(Some(now)), email_verified_at: Set(Some(now)),
password_hash: Set(hash.clone()), password_hash: Set(hash.clone()),
status: Set(UserStatus::Active.as_i16()), status: Set(UserStatus::Active.as_i16()),
@ -99,7 +102,10 @@ async fn create_demo_users(role_ids: &[i32]) -> Result<(), AuthError> {
is_admin: Set(false), is_admin: Set(false),
created_at: Set(now), created_at: Set(now),
updated_at: Set(now), updated_at: Set(now),
..Default::default()
}; };
username.set_on(&mut new_user);
email.set_on(&mut new_user);
let result = user::Entity::insert(new_user).exec(dbconn()).await?; let result = user::Entity::insert(new_user).exec(dbconn()).await?;
let user_id = result.last_insert_id; let user_id = result.last_insert_id;

View file

@ -5,10 +5,20 @@ use pagetop_seaorm::db::*;
pub struct Model { pub struct Model {
#[sea_orm(primary_key)] #[sea_orm(primary_key)]
pub id: i32, pub id: i32,
#[sea_orm(unique)] /// Nombre de usuario con sus mayúsculas, normalizado (NFKC) y sin espacios en los extremos.
pub username: String, pub username: String,
#[sea_orm(unique)] /// Email con sus mayúsculas, sin espacios en los extremos.
pub email: String, pub email: String,
/// Nombre de usuario para buscar sin distinguir mayúsculas (ver `identity.rs`).
#[sea_orm(unique)]
pub username_key: String,
/// *Hash* SHA-256 del esqueleto de confusión del nombre de usuario, único para que no haya dos
/// que se confundan.
#[sea_orm(unique)]
pub username_skeleton: String,
/// Email para buscar sin distinguir mayúsculas.
#[sea_orm(unique)]
pub email_key: String,
pub email_verified_at: Option<DateTimeUtc>, pub email_verified_at: Option<DateTimeUtc>,
pub password_hash: String, pub password_hash: String,
pub status: i16, pub status: i16,
@ -20,8 +30,13 @@ pub struct Model {
/// Texto libre "Sobre mí" que el propio usuario escribe en su perfil. /// Texto libre "Sobre mí" que el propio usuario escribe en su perfil.
pub about: Option<String>, pub about: Option<String>,
pub last_login_at: Option<DateTimeUtc>, pub last_login_at: Option<DateTimeUtc>,
/// Último acceso: al iniciar sesión y al prorrogar la sesión, con la precisión de
/// `user.session.write_interval_secs`.
pub last_access_at: Option<DateTimeUtc>, pub last_access_at: Option<DateTimeUtc>,
/// Intentos fallidos seguidos dentro de la ventana de recuento (`failed_login_window_secs`).
pub failed_login_count: i32, pub failed_login_count: i32,
/// Último intento fallido, para saber si el siguiente cae dentro de la misma ventana.
pub failed_login_at: Option<DateTimeUtc>,
pub locked_until: Option<DateTimeUtc>, pub locked_until: Option<DateTimeUtc>,
/// Acceso irrestricto al sistema, sin pasar por roles ni permisos. /// Acceso irrestricto al sistema, sin pasar por roles ni permisos.
pub is_admin: bool, pub is_admin: bool,

View file

@ -28,6 +28,19 @@ pub enum AuthError {
#[error("username is already taken")] #[error("username is already taken")]
UsernameTaken, UsernameTaken,
#[error("username does not meet the identity policy (user.identity_policy)")]
InvalidUsername,
#[error("invalid email address")]
InvalidEmail,
#[error("invalid setting \"{key}\"")]
InvalidSetting {
key: &'static str,
#[source]
source: Box<AuthError>,
},
#[error("email is already registered")] #[error("email is already registered")]
EmailTaken, EmailTaken,
@ -49,6 +62,9 @@ pub enum AuthError {
#[error("about text must be at most {0} characters")] #[error("about text must be at most {0} characters")]
AboutTooLong(usize), AboutTooLong(usize),
#[error("display name must be at most {0} characters")]
DisplayNameTooLong(usize),
#[error("user not found")] #[error("user not found")]
UserNotFound, UserNotFound,
@ -58,9 +74,14 @@ pub enum AuthError {
#[error("role machine name is already taken")] #[error("role machine name is already taken")]
RoleMachineNameTaken, RoleMachineNameTaken,
#[error("role machine name must contain only lowercase letters, digits and underscores")] #[error(
"role machine name must contain only lowercase letters, digits and underscores, up to 64"
)]
InvalidMachineName, InvalidMachineName,
#[error("role label must not be blank and must be at most {0} characters")]
InvalidRoleLabel(usize),
#[error("role is locked and cannot be modified or deleted")] #[error("role is locked and cannot be modified or deleted")]
RoleLocked, RoleLocked,

View file

@ -26,10 +26,12 @@ fn current_user_id(request: &HttpRequest) -> Option<i32> {
request.extension::<Account>().map(|a| a.id()) request.extension::<Account>().map(|a| a.id())
} }
// Redirección al formulario de inicio de sesión conservando `next` como URL de retorno. // Redirección al formulario de inicio de sesión con `next` como `waypoint`: la ruta a la que
// volver tras iniciar sesión.
fn login_redirect(request: HttpRequest, next: &'static str) -> Response { fn login_redirect(request: HttpRequest, next: &'static str) -> Response {
let cx = Context::new(request); let cx = Context::new(request);
Redirect::see_other(cx.route(LOGIN_PATH).with_param("next", next)).into_response() let waypoint = Waypoint::new(cx.route(next).to_string());
Redirect::see_other(waypoint.append_to(cx.route(LOGIN_PATH))).into_response()
} }
// **< profile_get >******************************************************************************** // **< profile_get >********************************************************************************
@ -277,6 +279,7 @@ pub(crate) async fn profile_edit_post(
language: util::non_blank(&form.language), language: util::non_blank(&form.language),
timezone: util::non_blank(&form.timezone), timezone: util::non_blank(&form.timezone),
theme: util::non_blank(&form.theme), theme: util::non_blank(&form.theme),
email_verified: false,
}, },
) )
.await; .await;

View file

@ -1,8 +1,8 @@
//! Handlers HTTP para el mantenimiento de usuarios, roles y permisos. //! Handlers HTTP para el mantenimiento de usuarios, roles y permisos.
//! //!
//! Accesibles sólo por URL directa (sin entradas de menú). Cada handler comprueba el permiso //! Las páginas de usuarios, roles y permisos se registran en el portal de `pagetop-admin` (ver
//! correspondiente con [`require_permission()`](pagetop::auth::require_permission) antes de //! `declare_admin_pages()`). Cada handler comprueba el permiso correspondiente con
//! construir la página. //! [`require_permission()`](pagetop::auth::require_permission) antes de construir la página.
pub(crate) mod permissions; pub(crate) mod permissions;
pub(crate) mod roles; pub(crate) mod roles;
@ -13,6 +13,7 @@ use pagetop_admin::component::AdminFrame;
use crate::LOCALES_USER; use crate::LOCALES_USER;
use crate::error::AuthError; use crate::error::AuthError;
use crate::service::role_admin::ROLE_MACHINE_NAME_MAX_CHARS;
// Envuelve el contenido de una página de administración en el frame de `pagetop-admin`: // Envuelve el contenido de una página de administración en el frame de `pagetop-admin`:
// breadcrumb, tareas y acciones locales registradas para la ruta actual en su `AdminRegistry`. // breadcrumb, tareas y acciones locales registradas para la ruta actual en su `AdminRegistry`.
@ -34,12 +35,21 @@ pub(crate) fn map_auth_error(err: &AuthError) -> Lc {
AuthError::AboutTooLong(n) => { AuthError::AboutTooLong(n) => {
Lc::t("error-about-too-long", &LOCALES_USER).with_arg("n", n.to_string()) Lc::t("error-about-too-long", &LOCALES_USER).with_arg("n", n.to_string())
} }
AuthError::DisplayNameTooLong(n) => {
Lc::t("error-display-name-too-long", &LOCALES_USER).with_arg("n", n.to_string())
}
AuthError::UsernameTaken => Lc::t("error-username-taken", &LOCALES_USER), AuthError::UsernameTaken => Lc::t("error-username-taken", &LOCALES_USER),
AuthError::InvalidUsername => Lc::t("error-invalid-username", &LOCALES_USER),
AuthError::InvalidEmail => Lc::t("error-invalid-email", &LOCALES_USER),
AuthError::EmailTaken => Lc::t("error-email-taken", &LOCALES_USER), AuthError::EmailTaken => Lc::t("error-email-taken", &LOCALES_USER),
AuthError::UserNotFound => Lc::t("error-user-not-found", &LOCALES_USER), AuthError::UserNotFound => Lc::t("error-user-not-found", &LOCALES_USER),
AuthError::RoleNotFound => Lc::t("error-role-not-found", &LOCALES_USER), AuthError::RoleNotFound => Lc::t("error-role-not-found", &LOCALES_USER),
AuthError::RoleMachineNameTaken => Lc::t("error-role-machine-name-taken", &LOCALES_USER), AuthError::RoleMachineNameTaken => Lc::t("error-role-machine-name-taken", &LOCALES_USER),
AuthError::InvalidMachineName => Lc::t("error-invalid-machine-name", &LOCALES_USER), AuthError::InvalidMachineName => Lc::t("error-invalid-machine-name", &LOCALES_USER)
.with_number("n", u32::from(ROLE_MACHINE_NAME_MAX_CHARS)),
AuthError::InvalidRoleLabel(n) => {
Lc::t("error-invalid-role-label", &LOCALES_USER).with_arg("n", n.to_string())
}
AuthError::RoleLocked => Lc::t("error-role-locked", &LOCALES_USER), AuthError::RoleLocked => Lc::t("error-role-locked", &LOCALES_USER),
AuthError::RoleInUse => Lc::t("error-role-in-use", &LOCALES_USER), AuthError::RoleInUse => Lc::t("error-role-in-use", &LOCALES_USER),
AuthError::LastAdministrator => Lc::t("error-last-administrator", &LOCALES_USER), AuthError::LastAdministrator => Lc::t("error-last-administrator", &LOCALES_USER),

View file

@ -412,7 +412,7 @@ pub(crate) async fn delete_post(
.with_per_page(page_result.per_page) .with_per_page(page_result.per_page)
.with_total(page_result.total) .with_total(page_result.total)
.with_message(message); .with_message(message);
let mut cx = Context::new(request); let mut cx = Context::admin(request);
Ok(HtmxResponse::new(table.render(&mut cx).await).into_response()) Ok(HtmxResponse::new(table.render(&mut cx).await).into_response())
} else { } else {
let cx = Context::new(request); let cx = Context::new(request);

View file

@ -327,6 +327,8 @@ async fn render_edit_page(
let can_toggle_admin = request let can_toggle_admin = request
.extension::<Account>() .extension::<Account>()
.is_some_and(|a| a.is_admin() && a.id() != id); .is_some_and(|a| a.is_admin() && a.id() != id);
// Bloquear y activar exige además `user:block_accounts` (ver `status_post`).
let can_change_status = has_permission(&request, &UserPermission::BlockAccounts);
let mut page = Page::admin(request); let mut page = Page::admin(request);
let back_href = waypoint.or(page.context().route(ADMIN_USERS_PATH)); let back_href = waypoint.or(page.context().route(ADMIN_USERS_PATH));
let title = Lc::t("title-admin-user-edit", &LOCALES_USER); let title = Lc::t("title-admin-user-edit", &LOCALES_USER);
@ -335,6 +337,7 @@ async fn render_edit_page(
status, status,
is_admin, is_admin,
can_toggle_admin, can_toggle_admin,
can_change_status,
&waypoint, &waypoint,
page.context(), page.context(),
); );
@ -355,8 +358,9 @@ async fn render_edit_page(
.into_response() .into_response()
} }
// Enlace a la pantalla de restablecer contraseña y botones de bloqueo/activación y de // Enlace a la pantalla de restablecer contraseña y botones de bloqueo/activación (sólo si
// concesión/revocación de acceso irrestricto (este último sólo si `can_toggle_admin`). El listado // `can_change_status`) y de concesión/revocación de acceso irrestricto (sólo si
// `can_toggle_admin`). El listado
// de origen (`waypoint`) se arrastra a todas ellas para que, al volver aquí, esta misma pantalla // de origen (`waypoint`) se arrastra a todas ellas para que, al volver aquí, esta misma pantalla
// siga sabiendo devolver al listado en el estado en que se dejó. // siga sabiendo devolver al listado en el estado en que se dejó.
// //
@ -372,12 +376,15 @@ fn edit_actions(
status: UserStatus, status: UserStatus,
target_is_admin: bool, target_is_admin: bool,
can_toggle_admin: bool, can_toggle_admin: bool,
can_change_status: bool,
waypoint: &Waypoint, waypoint: &Waypoint,
cx: &mut Context, cx: &mut Context,
) -> Flex { ) -> Flex {
// Una cuenta pendiente de verificar su email también se puede activar directamente, p. ej. si
// el correo de verificación no llegó.
let (next_status, label_key) = match status { let (next_status, label_key) = match status {
UserStatus::Blocked => ("active", "btn-activate"), UserStatus::Active => ("blocked", "btn-block"),
_ => ("blocked", "btn-block"), UserStatus::Blocked | UserStatus::Pending => ("active", "btn-activate"),
}; };
let (next_is_admin, admin_label_key, admin_confirm_key) = if target_is_admin { let (next_is_admin, admin_label_key, admin_confirm_key) = if target_is_admin {
("false", "btn-revoke-admin", "confirm-revoke-admin") ("false", "btn-revoke-admin", "confirm-revoke-admin")
@ -414,8 +421,10 @@ fn edit_actions(
.with_child( .with_child(
Button::anchor(Lc::t("btn-reset-password", &LOCALES_USER), password_href) Button::anchor(Lc::t("btn-reset-password", &LOCALES_USER), password_href)
.with_style(button::Style::Solid(Intent::Neutral)), .with_style(button::Style::Solid(Intent::Neutral)),
) );
.with_child(status_form); if can_change_status {
container = container.with_child(status_form);
}
if can_toggle_admin { if can_toggle_admin {
let admin_button = Button::submit(Lc::t(admin_label_key, &LOCALES_USER)) let admin_button = Button::submit(Lc::t(admin_label_key, &LOCALES_USER))
@ -490,6 +499,7 @@ pub(crate) async fn edit_post(
language: util::non_blank(&form.language), language: util::non_blank(&form.language),
timezone: util::non_blank(&form.timezone), timezone: util::non_blank(&form.timezone),
theme: util::non_blank(&form.theme), theme: util::non_blank(&form.theme),
email_verified: true,
}, },
) )
.await; .await;

View file

@ -10,9 +10,10 @@ use crate::component::{LoginForm, PasswordResetConfirmForm, PasswordResetForm, R
use crate::config::SETTINGS; use crate::config::SETTINGS;
use crate::error::AuthError; use crate::error::AuthError;
use crate::handlers::admin::map_auth_error; use crate::handlers::admin::map_auth_error;
use crate::mail::send_token_mail;
use crate::password; use crate::password;
use crate::session; use crate::session;
use crate::token::{TokenKind, consume_token, create_token}; use crate::token::{TokenKind, consume_token, create_token, is_valid_token};
use crate::{LOCALES_USER, LOGIN_PATH, PROFILE_PATH}; use crate::{LOCALES_USER, LOGIN_PATH, PROFILE_PATH};
// **< Tipos de formularios >*********************************************************************** // **< Tipos de formularios >***********************************************************************
@ -101,6 +102,7 @@ pub async fn login_post(
.with_title(Lc::t("title-login", &LOCALES_USER)) .with_title(Lc::t("title-login", &LOCALES_USER))
.with_child( .with_child(
LoginForm::new() LoginForm::new()
.with_username(form.username)
.with_error(Lc::t(error_key, &LOCALES_USER)) .with_error(Lc::t(error_key, &LOCALES_USER))
.with_waypoint(waypoint), .with_waypoint(waypoint),
) )
@ -172,24 +174,29 @@ pub async fn register_post(
) )
.await; .await;
match result { match result {
Ok(_user_id) => Redirect::see_other(cx.route(LOGIN_PATH)), Ok(user_id) if SETTINGS.require_email_verification => {
Err(err) => { send_verification_mail(&request, user_id).await;
let error_lc = match &err {
AuthError::PasswordTooShort(n) => {
Lc::t("error-password-too-short", &LOCALES_USER).with_arg("n", n.to_string())
}
AuthError::PasswordMismatch => Lc::t("error-password-mismatch", &LOCALES_USER),
AuthError::UsernameTaken => Lc::t("error-username-taken", &LOCALES_USER),
AuthError::EmailTaken => Lc::t("error-email-taken", &LOCALES_USER),
_ => Lc::t("error-internal", &LOCALES_USER),
};
Page::new(request) Page::new(request)
.with_title(Lc::t("title-register", &LOCALES_USER)) .with_title(Lc::t("title-register", &LOCALES_USER))
.with_child(RegisterForm::new().with_error(error_lc)) .with_child(Html::with(|cx| {
html! { p { (Lc::t("msg-verification-sent", &LOCALES_USER).using(cx)) } }
}))
.render() .render()
.await .await
.into_response() .into_response()
} }
Ok(_) => Redirect::see_other(cx.route(LOGIN_PATH)),
Err(err) => Page::new(request)
.with_title(Lc::t("title-register", &LOCALES_USER))
.with_child(
RegisterForm::new()
.with_username(form.username)
.with_email(form.email)
.with_error(map_auth_error(&err)),
)
.render()
.await
.into_response(),
} }
} }
@ -211,21 +218,36 @@ pub async fn password_reset_post(
request: HttpRequest, request: HttpRequest,
web::Form(form): web::Form<PasswordResetFormData>, web::Form(form): web::Form<PasswordResetFormData>,
) -> Result<Markup, ErrorPage> { ) -> Result<Markup, ErrorPage> {
// Respondemos igual exista o no el email para no revelar qué emails están registrados. // Respondemos igual exista o no el email para no revelar qué emails están registrados, también
{ // en el tiempo de respuesta: la búsqueda, el token y el correo se resuelven en segundo plano.
// Sólo a cuentas activas: una pendiente o bloqueada no podría iniciar sesión con la nueva
// contraseña.
let mail_request = request.clone();
tokio::spawn(async move {
use crate::account::UserStatus;
use crate::entity::user; use crate::entity::user;
use crate::identity::email_key;
use pagetop_seaorm::db::{ColumnTrait, EntityTrait, QueryFilter, dbconn}; use pagetop_seaorm::db::{ColumnTrait, EntityTrait, QueryFilter, dbconn};
if let Ok(Some(user_model)) = user::Entity::find() let found = user::Entity::find()
.filter(user::Column::Email.eq(&form.email)) .filter(user::Column::EmailKey.eq(email_key(&form.email)))
.filter(user::Column::Status.eq(UserStatus::Active.as_i16()))
.one(dbconn()) .one(dbconn())
.await .await;
{ let user_model = match found {
create_token(user_model.id, TokenKind::PasswordReset) Ok(Some(user_model)) => user_model,
.await Ok(None) => return,
.ok(); Err(err) => {
// TODO: enviar email con el token al usuario. trace::error!("Cannot look up account for password reset: {err}");
return;
} }
};
match create_token(user_model.id, TokenKind::PasswordReset).await {
Ok(token) => {
send_token_mail(&mail_request, TokenKind::PasswordReset, &user_model, &token);
} }
Err(err) => trace::error!("Cannot create password reset token: {err}"),
}
});
Page::new(request) Page::new(request)
.with_title(Lc::t("title-password-reset", &LOCALES_USER)) .with_title(Lc::t("title-password-reset", &LOCALES_USER))
.with_child(Html::with(|cx| { .with_child(Html::with(|cx| {
@ -242,23 +264,10 @@ pub async fn password_reset_confirm_get(
request: HttpRequest, request: HttpRequest,
web::Path((uid, token)): web::Path<(i32, String)>, web::Path((uid, token)): web::Path<(i32, String)>,
) -> Result<Markup, ErrorPage> { ) -> Result<Markup, ErrorPage> {
let valid = { if !is_valid_token(uid, &token, TokenKind::PasswordReset)
use crate::entity::user_token;
use crate::token::hash_token;
use pagetop_seaorm::db::{ColumnTrait, EntityTrait, QueryFilter, dbconn};
let hash = hash_token(&token);
let now = Utc::now();
user_token::Entity::find()
.filter(user_token::Column::TokenHash.eq(&hash))
.filter(user_token::Column::UserId.eq(uid))
.filter(user_token::Column::ConsumedAt.is_null())
.one(dbconn())
.await .await
.ok() .unwrap_or(false)
.flatten() {
.is_some_and(|r| r.expires_at > now)
};
if !valid {
return Err(ErrorPage::NotFound(Some(request))); return Err(ErrorPage::NotFound(Some(request)));
} }
Page::new(request) Page::new(request)
@ -271,36 +280,36 @@ pub async fn password_reset_confirm_get(
// **< password_reset_confirm_post >**************************************************************** // **< password_reset_confirm_post >****************************************************************
/// POST /user/password/reset/{uid}/{token} - Aplica la nueva contraseña. /// POST /user/password/reset/{uid}/{token} - Aplica la nueva contraseña.
///
/// La contraseña se valida antes de consumir el token: si no es válida, el mismo enlace sirve para
/// intentarlo de nuevo. Al aplicarla se cierran todas las sesiones del usuario y se levanta el
/// bloqueo temporal por intentos fallidos, porque quien abre el enlace ha demostrado ser el titular
/// de la dirección.
pub async fn password_reset_confirm_post( pub async fn password_reset_confirm_post(
request: HttpRequest, request: HttpRequest,
web::Path((_uid, token)): web::Path<(i32, String)>, web::Path((uid, token)): web::Path<(i32, String)>,
web::Form(form): web::Form<PasswordResetConfirmFormData>, web::Form(form): web::Form<PasswordResetConfirmFormData>,
) -> Response { ) -> Response {
let cx = Context::new(request.clone()); let cx = Context::new(request.clone());
if let Err(err) = password::passwords_match(&form.password, &form.confirm_password) {
return Page::new(request)
.with_title(Lc::t("title-new-password", &LOCALES_USER))
.with_child(PasswordResetConfirmForm::new().with_error(map_auth_error(&err)))
.render()
.await
.into_response();
}
let result = async { let result = async {
use crate::entity::user; use crate::entity::user;
use pagetop_seaorm::db::{ActiveModelTrait, Set, dbconn}; use pagetop_seaorm::db::{ActiveModelTrait, Set, dbconn};
let user_id = consume_token(&token, TokenKind::PasswordReset).await?; password::passwords_match(&form.password, &form.confirm_password)?;
password::validate_strength(&form.password)?; password::validate_strength(&form.password)?;
let hash = password::hash_password(&form.password)?; let hash = password::hash_password_async(&form.password).await?;
let now = Utc::now(); consume_token(uid, &token, TokenKind::PasswordReset).await?;
user::ActiveModel { user::ActiveModel {
id: Set(user_id), id: Set(uid),
password_hash: Set(hash), password_hash: Set(hash),
updated_at: Set(now), failed_login_count: Set(0),
failed_login_at: Set(None),
locked_until: Set(None),
updated_at: Set(Utc::now()),
..Default::default() ..Default::default()
} }
.update(dbconn()) .update(dbconn())
.await?; .await?;
session::destroy_user_sessions(user_id) session::destroy_user_sessions(uid)
.await .await
.map_err(AuthError::Database)?; .map_err(AuthError::Database)?;
Ok::<(), AuthError>(()) Ok::<(), AuthError>(())
@ -308,40 +317,86 @@ pub async fn password_reset_confirm_post(
.await; .await;
match result { match result {
Ok(()) => Redirect::see_other(cx.route(LOGIN_PATH)), Ok(()) => Redirect::see_other(cx.route(LOGIN_PATH)),
Err(_) => Page::new(request) Err(err) => {
let error = match err {
AuthError::InvalidToken => Lc::t("error-token-invalid", &LOCALES_USER),
err => map_auth_error(&err),
};
Page::new(request)
.with_title(Lc::t("title-new-password", &LOCALES_USER)) .with_title(Lc::t("title-new-password", &LOCALES_USER))
.with_child( .with_child(PasswordResetConfirmForm::new().with_error(error))
PasswordResetConfirmForm::new()
.with_error(Lc::t("error-token-invalid", &LOCALES_USER)),
)
.render() .render()
.await .await
.into_response(), .into_response()
}
} }
} }
// **< verify_email_get >*************************************************************************** // **< verify_email_get / verify_email_post >*******************************************************
/// GET /user/verify/{uid}/{token} - Confirma la dirección de email. /// GET /user/verify/{uid}/{token} - Pide confirmar la dirección de email con un botón.
///
/// Abrir el enlace no verifica nada: los servidores de correo y los antivirus abren por su cuenta
/// los enlaces de los correos para analizarlos, y así quedaría verificada una cuenta creada con la
/// dirección de otra persona sin que ésta haya hecho nada. Sólo el envío del formulario
/// ([`verify_email_post()`]) consume el token.
pub async fn verify_email_get( pub async fn verify_email_get(
request: HttpRequest, request: HttpRequest,
web::Path((_uid, token)): web::Path<(i32, String)>, web::Path((uid, token)): web::Path<(i32, String)>,
) -> Result<Markup, ErrorPage> {
if !is_valid_token(uid, &token, TokenKind::EmailVerification)
.await
.unwrap_or(false)
{
return Err(ErrorPage::NotFound(Some(request)));
}
// Sin `with_action()`: se envía a la propia URL, que incluye el `{uid}/{token}`.
let form = Form::new()
.with_id("user-verify-email-form")
.with_method(form::Method::Post)
.with_child(Html::with(|cx| {
html! { p { (Lc::t("msg-verify-email", &LOCALES_USER).using(cx)) } }
}))
.with_child(
Button::submit(Lc::t("btn-verify-email", &LOCALES_USER))
.with_style(button::Style::Solid(Intent::Primary)),
);
Page::new(request)
.with_title(Lc::t("title-verify-email", &LOCALES_USER))
.with_child(form)
.render()
.await
}
/// POST /user/verify/{uid}/{token} - Confirma la dirección de email.
///
/// Activa la cuenta si estaba pendiente de esta verificación; una cuenta bloqueada sigue bloqueada.
pub async fn verify_email_post(
request: HttpRequest,
web::Path((uid, token)): web::Path<(i32, String)>,
) -> Response { ) -> Response {
let cx = Context::new(request.clone()); let cx = Context::new(request.clone());
let result = async { let result = async {
use crate::account::UserStatus; use crate::account::UserStatus;
use crate::entity::user; use crate::entity::user;
use pagetop_seaorm::db::{ActiveModelTrait, Set, dbconn}; use pagetop_seaorm::db::query::Expr;
let user_id = consume_token(&token, TokenKind::EmailVerification).await?; use pagetop_seaorm::db::{ColumnTrait, EntityTrait, QueryFilter, dbconn};
consume_token(uid, &token, TokenKind::EmailVerification).await?;
let now = Utc::now(); let now = Utc::now();
user::ActiveModel { user::Entity::update_many()
id: Set(user_id), .col_expr(user::Column::EmailVerifiedAt, Expr::value(now))
email_verified_at: Set(Some(now)), .col_expr(user::Column::UpdatedAt, Expr::value(now))
status: Set(UserStatus::Active.as_i16()), .filter(user::Column::Id.eq(uid))
updated_at: Set(now), .exec(dbconn())
..Default::default() .await?;
} user::Entity::update_many()
.update(dbconn()) .col_expr(
user::Column::Status,
Expr::value(UserStatus::Active.as_i16()),
)
.filter(user::Column::Id.eq(uid))
.filter(user::Column::Status.eq(UserStatus::Pending.as_i16()))
.exec(dbconn())
.await?; .await?;
Ok::<(), AuthError>(()) Ok::<(), AuthError>(())
} }
@ -354,6 +409,30 @@ pub async fn verify_email_get(
// **< HELPERS >************************************************************************************ // **< HELPERS >************************************************************************************
// Envía el correo para verificar la dirección de la cuenta recién creada. Un fallo no impide el
// registro: la cuenta queda pendiente y un administrador puede activarla.
//
// La dirección todavía no está verificada: cualquiera puede registrarse con la de otra persona y
// hacer que le llegue este correo, que sale del dominio de la aplicación y con su diseño, así que
// pasa los filtros y resulta creíble. Por eso no incluye nada que elija quien se registra, ni
// siquiera el nombre de usuario: bastaría para colar un texto o un enlace engañoso (*phishing*).
async fn send_verification_mail(request: &HttpRequest, user_id: i32) {
use crate::entity::user;
use pagetop_seaorm::db::{EntityTrait, dbconn};
let user = match user::Entity::find_by_id(user_id).one(dbconn()).await {
Ok(Some(user)) => user,
Ok(None) => return,
Err(err) => {
trace::error!("Cannot load new user {user_id} to send verification email: {err}");
return;
}
};
match create_token(user_id, TokenKind::EmailVerification).await {
Ok(token) => send_token_mail(request, TokenKind::EmailVerification, &user, &token),
Err(err) => trace::error!("Cannot create email verification token: {err}"),
}
}
fn redirect_with_cookie(to: impl Into<RoutePath>, cookie: &str) -> Response { fn redirect_with_cookie(to: impl Into<RoutePath>, cookie: &str) -> Response {
( (
web::http::StatusCode::SEE_OTHER, web::http::StatusCode::SEE_OTHER,

View file

@ -0,0 +1,353 @@
//! Nombre de usuario y email que identifican una cuenta: normalización y validación.
//!
//! Las reglas públicas se documentan en `IdentityPolicy`. Aquí se separan dos cosas:
//!
//! - **Buscar y comparar**, igual con cualquier política: `*_key` (sin espacios en los extremos,
//! NFKC en el nombre de usuario y en minúsculas) y el esqueleto de confusión del nombre
//! (UTS #39), guardados en columnas propias con índice único. Así se puede cambiar de política
//! sin que dejen de encontrarse las cuentas existentes.
//!
//! Del esqueleto se guarda su *hash* SHA-256: sólo se compara por igualdad, y puede ser mucho
//! más largo que el nombre (cada sílaba coreana se descompone en hasta siete caracteres), así
//! que no cabría en una columna de longitud fija con índice único.
//! - **Aceptar un nombre nuevo**, lo único que depende de la política.
use pagetop::prelude::*;
use pagetop_mail::Mailbox;
use pagetop_seaorm::db::Set;
use unicode_ident::{is_xid_continue, is_xid_start};
use unicode_normalization::UnicodeNormalization;
use unicode_security::{GeneralSecurityProfile, MixedScript, skeleton};
use sha2::{Digest, Sha256};
use crate::LOCALES_USER;
use crate::config::IdentityPolicy;
use crate::entity::user;
use crate::error::AuthError;
// Longitud mínima del nombre de usuario, con cualquier política. `u16` porque también limita el
// campo del formulario (`minlength`), igual que las máximas de `username_max_chars()`.
pub(crate) const USERNAME_MIN_CHARS: u16 = 3;
// Longitud máxima de una dirección de correo, la que admite SMTP.
pub(crate) const EMAIL_MAX_CHARS: u16 = 254;
// Longitud máxima del nombre de usuario según la política. La de `Permissive` es la de Drupal.
pub(crate) fn username_max_chars(policy: IdentityPolicy) -> u16 {
match policy {
IdentityPolicy::Strict | IdentityPolicy::Unicode => 32,
IdentityPolicy::Permissive => 60,
}
}
// **< Username >***********************************************************************************
// Nombre de usuario listo para guardar: el valor tal como se escribió (normalizado), su clave de
// búsqueda y el *hash* de su esqueleto de confusión.
#[derive(Debug, Getters)]
pub(crate) struct Username {
value: String,
key: String,
skeleton: String,
}
impl Username {
// Guarda el nombre de usuario en el modelo.
pub(crate) fn set_on(self, model: &mut user::ActiveModel) {
model.username = Set(self.value);
model.username_key = Set(self.key);
model.username_skeleton = Set(self.skeleton);
}
}
// Normaliza y valida un nombre de usuario con la política dada.
//
// `current_key` es la clave del nombre actual de la cuenta, si se está editando: un nombre que no
// cambia (salvo en mayúsculas) no se valida de nuevo, para que una cuenta creada con una política
// más abierta pueda seguir guardando su perfil.
pub(crate) fn username(
raw: &str,
policy: IdentityPolicy,
current_key: Option<&str>,
) -> Result<Username, AuthError> {
let value = raw.trim().nfkc().collect::<String>();
let key = value.to_lowercase();
if current_key != Some(key.as_str()) && !accepts(&value, policy) {
return Err(AuthError::InvalidUsername);
}
let skeleton = skeleton_hash(&key);
Ok(Username {
value,
key,
skeleton,
})
}
// Clave para buscar una cuenta por nombre de usuario con lo que escribe el usuario, que no se
// valida: una entrada no válida simplemente no encuentra ninguna cuenta.
pub(crate) fn username_key(raw: &str) -> String {
raw.trim().nfkc().collect::<String>().to_lowercase()
}
// *Hash* SHA-256, en hexadecimal, del esqueleto de confusión (UTS #39) de la clave del nombre.
fn skeleton_hash(key: &str) -> String {
let digest = Sha256::digest(skeleton(key).collect::<String>().as_bytes());
let mut hex = String::with_capacity(64);
for byte in digest {
hex.push(char::from(b"0123456789abcdef"[usize::from(byte >> 4)]));
hex.push(char::from(b"0123456789abcdef"[usize::from(byte & 0x0f)]));
}
hex
}
// Si la política acepta el nombre, ya normalizado.
//
// Nunca se admite `@`: un nombre de usuario no puede coincidir con el email de otra cuenta, que
// también sirve para iniciar sesión. Con `Unicode` y `Permissive`, las letras y dígitos son las
// clases que definen los identificadores de Rust (XID, UAX #31), que incluyen las marcas
// combinables de escrituras como el devanagari; `identifier_allowed()` descarta los caracteres
// que UTS #39 desaconseja (invisibles, obsoletos...) y `is_single_script()` la mezcla de alfabetos.
fn accepts(name: &str, policy: IdentityPolicy) -> bool {
let symbols: &[char] = match policy {
IdentityPolicy::Strict | IdentityPolicy::Unicode => &['.', '_', '-'],
IdentityPolicy::Permissive => &['.', '_', '-', ' ', '\'', '+'],
};
let length = usize::from(USERNAME_MIN_CHARS)..=usize::from(username_max_chars(policy));
if !length.contains(&name.chars().count()) {
return false;
}
let Some(first) = name.chars().next() else {
return false;
};
match policy {
IdentityPolicy::Strict => {
first.is_ascii_alphanumeric()
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || symbols.contains(&c))
}
IdentityPolicy::Unicode | IdentityPolicy::Permissive => {
let letter_or_digit = |c: char| {
c.identifier_allowed()
&& (is_xid_start(c) || (is_xid_continue(c) && c.is_numeric()))
};
letter_or_digit(first)
&& name
.chars()
.all(|c| symbols.contains(&c) || (c.identifier_allowed() && is_xid_continue(c)))
&& name.is_single_script()
&& !name.contains(" ")
}
}
}
// **< Email >**************************************************************************************
// Email listo para guardar: el valor tal como se escribió y su clave de búsqueda.
#[derive(Debug, Getters)]
pub(crate) struct Email {
value: String,
key: String,
}
impl Email {
// Guarda el email en el modelo.
pub(crate) fn set_on(self, model: &mut user::ActiveModel) {
model.email = Set(self.value);
model.email_key = Set(self.key);
}
}
// Normaliza y valida un email, igual con cualquier política: el formato que exige `pagetop-mail`
// para poder enviarle correos. Se guarda tal como se escribe; la clave en minúsculas evita cuentas
// duplicadas por mayúsculas (la parte local las distingue según el estándar, pero ningún
// proveedor real lo aplica).
pub(crate) fn email(raw: &str) -> Result<Email, AuthError> {
let value = raw.trim().to_owned();
let key = email_key(&value);
// También la clave: en minúsculas, algunas letras ocupan dos caracteres (`İ` -> `i̇`).
let max = usize::from(EMAIL_MAX_CHARS);
if value.chars().count() > max
|| key.chars().count() > max
|| Mailbox::new(value.as_str()).validate().is_err()
{
return Err(AuthError::InvalidEmail);
}
Ok(Email { key, value })
}
// Clave para buscar una cuenta por email con lo que escribe el usuario, sin validarlo.
pub(crate) fn email_key(raw: &str) -> String {
raw.trim().to_lowercase()
}
// **< Textos >*************************************************************************************
// Reglas del nombre de usuario de la política, como texto de ayuda de los formularios.
pub(crate) fn username_help(policy: IdentityPolicy) -> Lc {
let key = match policy {
IdentityPolicy::Strict => "help-username-strict",
IdentityPolicy::Unicode => "help-username-unicode",
IdentityPolicy::Permissive => "help-username-permissive",
};
Lc::t(key, &LOCALES_USER)
.with_number("min", u32::from(USERNAME_MIN_CHARS))
.with_number("max", u32::from(username_max_chars(policy)))
}
#[cfg(test)]
mod tests {
use super::*;
fn accepted(raw: &str, policy: IdentityPolicy) -> bool {
username(raw, policy, None).is_ok()
}
fn skeleton_of(raw: &str) -> String {
username(raw, IdentityPolicy::Permissive, Some(&username_key(raw)))
.unwrap()
.skeleton
}
const ALWAYS_REJECTED: &[&str] = &[
"ab",
"_ana",
".ana",
"ana@example.com",
"ana@casa",
"<a>",
"a\u{200B}na", // Zero-width space.
"ana\u{202E}", // Right-to-left override.
];
#[pagetop::test]
async fn strict_accepts_only_ascii_identifiers() {
let name = username(" Ana.Perez_01 ", IdentityPolicy::Strict, None).unwrap();
assert_eq!(name.value, "Ana.Perez_01", "the value keeps its case");
assert_eq!(name.key, "ana.perez_01");
assert!(accepted("a-b", IdentityPolicy::Strict));
// Full-width letters are normalized to ASCII (NFKC).
assert_eq!(
username("Ana", IdentityPolicy::Strict, None)
.unwrap()
.value,
"Ana"
);
let too_long = "a".repeat(33);
for name in
ALWAYS_REJECTED
.iter()
.copied()
.chain(["peña", "аna", "ana perez", too_long.as_str()])
{
assert!(
!accepted(name, IdentityPolicy::Strict),
"{name:?} must be rejected"
);
}
}
#[pagetop::test]
async fn unicode_accepts_any_single_script() {
for name in [
"josé",
"peña",
"Müller",
"σοφία",
"Иван",
"山田太郎",
"山田やまだ",
"नमस्ते", // Devanagari, with combining vowel signs.
"محمد",
"ana_01",
] {
assert!(
accepted(name, IdentityPolicy::Unicode),
"{name:?} must be accepted"
);
}
// A combining accent is composed (NFKC): both spellings are the same user.
assert_eq!(username_key("jose\u{301}"), username_key("josé"));
let too_long = "a".repeat(33);
for name in ALWAYS_REJECTED.iter().copied().chain([
"pаypal",
"ana perez",
"O'Brien",
too_long.as_str(),
]) {
assert!(
!accepted(name, IdentityPolicy::Unicode),
"{name:?} must be rejected"
);
}
}
#[pagetop::test]
async fn permissive_adds_spaces_apostrophes_and_plus() {
for name in ["Ana Pérez", "O'Brien", "ana+test", "José María"] {
assert!(
accepted(name, IdentityPolicy::Permissive),
"{name:?} must be accepted"
);
}
let too_long = "a".repeat(61);
for name in
ALWAYS_REJECTED
.iter()
.copied()
.chain(["ana perez", "pаypal", too_long.as_str()])
{
assert!(
!accepted(name, IdentityPolicy::Permissive),
"{name:?} must be rejected"
);
}
}
#[pagetop::test]
async fn confusable_names_share_their_skeleton() {
assert_eq!(skeleton_of("admin"), skeleton_of("аdmin")); // Cyrillic "а".
assert_eq!(skeleton_of("maria"), skeleton_of("rnaria"));
assert_eq!(skeleton_of("Ana"), skeleton_of("ana"));
assert_ne!(skeleton_of("ana"), skeleton_of("eva"));
}
// Each Hangul syllable expands to up to seven characters in the skeleton: only its hash fits
// the column, whatever the name.
#[pagetop::test]
async fn longest_names_fit_their_columns() {
let name = username(&"꽦".repeat(60), IdentityPolicy::Permissive, None).unwrap();
assert_eq!(name.skeleton.len(), 64);
assert!(name.key.chars().count() <= 255);
}
#[pagetop::test]
async fn unchanged_names_skip_the_policy() {
let current = username_key("Ana Pérez");
assert!(username("ana pérez", IdentityPolicy::Strict, Some(&current)).is_ok());
assert!(username("Eva Pérez", IdentityPolicy::Strict, Some(&current)).is_err());
}
#[pagetop::test]
async fn emails_keep_their_case_and_compare_without_it() {
let email = email(" Ana@Example.COM ").unwrap();
assert_eq!(email.value, "Ana@Example.COM");
assert_eq!(email.key, "ana@example.com");
assert_eq!(email_key("ANA@example.com "), email.key);
let too_long = format!("{}@example.com", "a".repeat(250));
for invalid in [
"",
"ana",
"ana@",
"Ana <ana@example.com>",
too_long.as_str(),
] {
assert!(
matches!(super::email(invalid), Err(AuthError::InvalidEmail)),
"{invalid:?} must be rejected"
);
}
}
}

View file

@ -32,7 +32,7 @@ enum MyPermission {
impl Permission for MyPermission { impl Permission for MyPermission {
fn key(&self) -> CowStr { fn key(&self) -> CowStr {
match self { match self {
Self::SeeDashboard => "myapp.see_dashboard".into(), Self::SeeDashboard => "myapp:see_dashboard".into(),
} }
} }
} }
@ -59,6 +59,37 @@ async fn dashboard(request: HttpRequest) -> Result<Markup, ErrorPage> {
.render().await .render().await
} }
``` ```
## Nombres de usuario y email
Cada cuenta tiene un nombre de usuario y un email, obligatorios y únicos; se puede iniciar sesión
con cualquiera de los dos. Qué nombres de usuario se aceptan lo decide `identity_policy` en la
sección `[user]`:
```toml
[user]
identity_policy = "unicode" # "strict" (por defecto), "unicode" o "permissive".
```
Con cualquier política, un nombre de usuario nunca contiene `@`, no se distinguen mayúsculas (`Ana`
y `ana` son el mismo usuario) y no se admiten nombres que se confunden a simple vista con otro
existente (`rnaria` si existe `maria`, o `аdmin` con una `а` cirílica). Las reglas completas de
cada política, y las del email, están en [`IdentityPolicy`](config::IdentityPolicy).
## Correos
La recuperación de contraseña y, con `require_email_verification`, la verificación de las cuentas
nuevas envían un correo con un enlace de un solo uso mediante [`pagetop_mail`]. Configura el envío
en la sección `[mail]`, incluidos el remitente (`mail.from`), que estos correos no indican, y la
URL pública de los enlaces (`mail.base_url`): sin configurar, los correos se escriben en las trazas
en lugar de enviarse.
La recuperación de contraseña sólo se envía a cuentas activas. Mientras una dirección no está
verificada podría ser de otra persona, así que sus correos no incluyen nada que elija quien creó
la cuenta, ni el nombre de usuario ni el nombre visible. Una dirección queda verificada al
confirmarla desde el enlace del correo de verificación (abrirlo no basta: hay que pulsar un botón,
porque los servidores de correo abren los enlaces para analizarlos) o cuando la fija un
administrador, y deja de estarlo si el usuario la cambia en su perfil.
*/ */
use pagetop::prelude::*; use pagetop::prelude::*;
@ -76,6 +107,8 @@ pub(crate) mod auth;
pub(crate) mod demo; pub(crate) mod demo;
pub(crate) mod entity; pub(crate) mod entity;
pub(crate) mod handlers; pub(crate) mod handlers;
pub(crate) mod identity;
pub(crate) mod mail;
pub(crate) mod middleware; pub(crate) mod middleware;
pub(crate) mod migration; pub(crate) mod migration;
pub(crate) mod service; pub(crate) mod service;
@ -127,7 +160,8 @@ const PROFILE_PASSWORD_PATH: &str = "/user/password";
// Con el sufijo `/{uid}/{token}`: GET - muestra el formulario de nueva contraseña. // Con el sufijo `/{uid}/{token}`: GET - muestra el formulario de nueva contraseña.
// POST - la aplica. // POST - la aplica.
const PASSWORD_RESET_PATH: &str = "/user/password/reset"; const PASSWORD_RESET_PATH: &str = "/user/password/reset";
// Con el sufijo `/{uid}/{token}`: confirma la dirección de email del usuario. // Con el sufijo `/{uid}/{token}`: GET - pide confirmar la dirección de email del usuario.
// POST - la confirma.
const VERIFY_PATH: &str = "/user/verify"; const VERIFY_PATH: &str = "/user/verify";
// **< Rutas de administración (fijas) >************************************************************ // **< Rutas de administración (fijas) >************************************************************
@ -231,6 +265,7 @@ impl Extension for User {
&pagetop_admin::Admin, &pagetop_admin::Admin,
&pagetop_seaorm::SeaORM, &pagetop_seaorm::SeaORM,
&pagetop_htmx::Htmx, &pagetop_htmx::Htmx,
&pagetop_mail::Mail,
] ]
} }
@ -242,6 +277,8 @@ impl Extension for User {
DeclarePermissions::new(permission::declare_builtin_permissions), DeclarePermissions::new(permission::declare_builtin_permissions),
// Registra las páginas de usuarios, roles y permisos en el portal de pagetop-admin. // Registra las páginas de usuarios, roles y permisos en el portal de pagetop-admin.
DeclareAdminPages::new(declare_admin_pages), DeclareAdminPages::new(declare_admin_pages),
// Declara las vistas previas de los correos de recuperación y verificación.
pagetop_mail::DeclareMailPreviews::new(mail::declare_previews),
] ]
} }
@ -258,7 +295,7 @@ impl Extension for User {
// Los permisos de "anonymous" en memoria sobreviven a una nueva preparación en el mismo // Los permisos de "anonymous" en memoria sobreviven a una nueva preparación en el mismo
// proceso (las pruebas lo hacen), que puede usar otra base de datos. // proceso (las pruebas lo hacen), que puede usar otra base de datos.
session::invalidate_anonymous_permissions(); session::invalidate_anonymous_permissions();
auth::seed_initial_data().await; auth::seed_initial_data().await?;
#[cfg(feature = "demo-data")] #[cfg(feature = "demo-data")]
demo::seed_demo_data().await; demo::seed_demo_data().await;
Ok(()) Ok(())
@ -301,7 +338,7 @@ impl Extension for User {
) )
.route( .route(
&format!("{}/{{uid}}/{{token}}", VERIFY_PATH), &format!("{}/{{uid}}/{{token}}", VERIFY_PATH),
web::get(handlers::auth::verify_email_get), web::get(handlers::auth::verify_email_get).post(handlers::auth::verify_email_post),
) )
.route(ADMIN_USERS_PATH, web::get(handlers::admin::users::list_get)) .route(ADMIN_USERS_PATH, web::get(handlers::admin::users::list_get))
.route( .route(

View file

@ -11,6 +11,7 @@ title-login = Sign in
title-register = Create account title-register = Create account
title-password-reset = Reset password title-password-reset = Reset password
title-new-password = Set new password title-new-password = Set new password
title-verify-email = Confirm your email
title-profile = My profile title-profile = My profile
title-profile-edit = Edit my profile title-profile-edit = Edit my profile
title-profile-password = Change my password title-profile-password = Change my password
@ -32,6 +33,7 @@ btn-logout = Sign out
btn-register = Create account btn-register = Create account
btn-send-reset-link = Send reset link btn-send-reset-link = Send reset link
btn-set-password = Change password btn-set-password = Change password
btn-verify-email = Confirm my email
btn-edit-profile = Edit profile btn-edit-profile = Edit profile
link-register = Create an account link-register = Create an account
@ -51,6 +53,35 @@ msg-password-reset-sent =
If an account with that email exists, we have sent a reset link. If an account with that email exists, we have sent a reset link.
Please check your inbox. Please check your inbox.
msg-verify-email = Press the button to confirm your email address and activate your account.
msg-verification-sent =
We have sent you an email to confirm your address.
Open the link it contains and confirm your address to activate your account.
# **< Emails >**
mail-greeting = Hello { $username },
mail-greeting-plain = Hello,
mail-link-expires =
{ $hours ->
[one] The link expires in one hour.
*[other] The link expires in { $hours } hours.
}
mail-reset-subject = Reset your { $app } password
mail-reset-intro = We received a request to reset the password of your account. To choose a new one, open this link:
mail-reset-action = Choose a new password
mail-reset-ignore = If you did not request it, ignore this email: your password will not change.
mail-verify-subject = Confirm your email for { $app }
mail-verify-intro = Thank you for signing up. To activate your account, confirm your email address by opening this link:
mail-verify-action = Confirm my email
mail-verify-ignore = If you did not create an account, ignore this email.
mail-preview-reset = Password reset
mail-preview-verify = Email verification on sign-up
# **< Error messages >** # **< Error messages >**
error-invalid-credentials = Invalid username or password. error-invalid-credentials = Invalid username or password.
@ -63,7 +94,10 @@ error-invalid-timezone = Invalid timezone.
error-invalid-language = Invalid language. error-invalid-language = Invalid language.
error-invalid-theme = Invalid theme. error-invalid-theme = Invalid theme.
error-about-too-long = The "About me" text must be at most { $n } characters. error-about-too-long = The "About me" text must be at most { $n } characters.
error-username-taken = This username is already taken. error-display-name-too-long = The display name must be at most { $n } characters.
error-username-taken = This username is already taken or can be mistaken for an existing one.
error-invalid-username = The username is not valid: check the rules shown below the field.
error-invalid-email = The email address is not valid.
error-email-taken = This email address is already registered. error-email-taken = This email address is already registered.
error-token-invalid = This link is invalid or has expired. error-token-invalid = This link is invalid or has expired.
error-current-password = The current password is incorrect. error-current-password = The current password is incorrect.
@ -128,11 +162,27 @@ field-roles = Roles
field-is-admin = Administrator (unrestricted access) field-is-admin = Administrator (unrestricted access)
field-search-users = Search by username, email or name... field-search-users = Search by username, email or name...
help-username-strict =
{ $min } to { $max } characters: unaccented letters, digits, period, hyphen or underscore,
starting with a letter or digit. Case is ignored when signing in.
help-username-unicode =
{ $min } to { $max } characters: letters of any alphabet (without mixing them), digits, period,
hyphen or underscore, starting with a letter or digit. Case is ignored when signing in.
help-username-permissive =
{ $min } to { $max } characters: letters of any alphabet (without mixing them), digits, single
spaces, period, hyphen, underscore, apostrophe or "+", starting with a letter or digit. Case is
ignored when signing in.
help-password-min-length = At least { $n } characters.
help-machine-name-immutable = help-machine-name-immutable =
Lowercase letters, digits and underscores only. Cannot be changed after creation. Lowercase letters, digits and underscores only. Cannot be changed after creation.
help-admin-roles = help-admin-roles =
As an administrator they have every permission. These roles will apply if they stop being one. This is an administrator account with every permission. These roles will apply if it stops
being one.
# **< Admin: buttons and links >** # **< Admin: buttons and links >**
@ -167,7 +217,8 @@ empty-role-permissions = This role has no permissions.
error-role-not-found = Role not found. error-role-not-found = Role not found.
error-role-machine-name-taken = This machine name is already taken. error-role-machine-name-taken = This machine name is already taken.
error-invalid-machine-name = Machine name may only contain lowercase letters, digits and underscores. error-invalid-machine-name = Machine name may only contain lowercase letters, digits and underscores, up to { $n } characters.
error-invalid-role-label = The label must not be blank or longer than { $n } characters.
error-role-locked = This role is a system role and cannot be modified. error-role-locked = This role is a system role and cannot be modified.
error-role-in-use = This role has users assigned and cannot be deleted. error-role-in-use = This role has users assigned and cannot be deleted.
error-last-administrator = Cannot remove the last administrator. error-last-administrator = Cannot remove the last administrator.

View file

@ -11,6 +11,7 @@ title-login = Iniciar sesión
title-register = Crear cuenta title-register = Crear cuenta
title-password-reset = Recuperar contraseña title-password-reset = Recuperar contraseña
title-new-password = Establecer nueva contraseña title-new-password = Establecer nueva contraseña
title-verify-email = Confirmar tu correo
title-profile = Mi perfil title-profile = Mi perfil
title-profile-edit = Editar mi perfil title-profile-edit = Editar mi perfil
title-profile-password = Cambiar mi contraseña title-profile-password = Cambiar mi contraseña
@ -32,6 +33,7 @@ btn-logout = Cerrar sesión
btn-register = Crear cuenta btn-register = Crear cuenta
btn-send-reset-link = Enviar enlace btn-send-reset-link = Enviar enlace
btn-set-password = Cambiar contraseña btn-set-password = Cambiar contraseña
btn-verify-email = Confirmar mi correo
btn-edit-profile = Editar perfil btn-edit-profile = Editar perfil
link-register = Crear una cuenta link-register = Crear una cuenta
@ -51,6 +53,35 @@ msg-password-reset-sent =
Si existe una cuenta con ese email, hemos enviado un enlace de recuperación. Si existe una cuenta con ese email, hemos enviado un enlace de recuperación.
Revisa tu bandeja de entrada. Revisa tu bandeja de entrada.
msg-verify-email = Pulsa el botón para confirmar tu dirección de correo y activar tu cuenta.
msg-verification-sent =
Te hemos enviado un correo para confirmar tu dirección.
Abre el enlace que contiene y confirma tu dirección para activar tu cuenta.
# **< Correos >**
mail-greeting = Hola, { $username }:
mail-greeting-plain = Hola:
mail-link-expires =
{ $hours ->
[one] El enlace caduca en una hora.
*[other] El enlace caduca en { $hours } horas.
}
mail-reset-subject = Recupera tu contraseña de { $app }
mail-reset-intro = Hemos recibido una solicitud para restablecer la contraseña de tu cuenta. Para elegir una nueva, abre este enlace:
mail-reset-action = Elegir una nueva contraseña
mail-reset-ignore = Si no lo has solicitado tú, ignora este correo: tu contraseña no cambiará.
mail-verify-subject = Confirma tu correo en { $app }
mail-verify-intro = Gracias por registrarte. Para activar tu cuenta, confirma tu dirección de correo abriendo este enlace:
mail-verify-action = Confirmar mi correo
mail-verify-ignore = Si no has creado ninguna cuenta, ignora este correo.
mail-preview-reset = Recuperación de contraseña
mail-preview-verify = Verificación del correo al registrarse
# **< Mensajes de error >** # **< Mensajes de error >**
error-invalid-credentials = Usuario o contraseña incorrectos. error-invalid-credentials = Usuario o contraseña incorrectos.
@ -63,7 +94,10 @@ error-invalid-timezone = Zona horaria no válida.
error-invalid-language = Idioma no válido. error-invalid-language = Idioma no válido.
error-invalid-theme = Tema no válido. error-invalid-theme = Tema no válido.
error-about-too-long = El texto «Sobre mí» no puede superar { $n } caracteres. error-about-too-long = El texto «Sobre mí» no puede superar { $n } caracteres.
error-username-taken = Este nombre de usuario ya está en uso. error-display-name-too-long = El nombre visible no puede superar { $n } caracteres.
error-username-taken = Este nombre de usuario ya está en uso o se confunde con otro existente.
error-invalid-username = El nombre de usuario no es válido: revisa las reglas indicadas bajo el campo.
error-invalid-email = La dirección de correo no es válida.
error-email-taken = Esta dirección de email ya está registrada. error-email-taken = Esta dirección de email ya está registrada.
error-token-invalid = Este enlace no es válido o ha caducado. error-token-invalid = Este enlace no es válido o ha caducado.
error-current-password = La contraseña actual no es correcta. error-current-password = La contraseña actual no es correcta.
@ -128,11 +162,28 @@ field-roles = Roles
field-is-admin = Administrador (acceso irrestricto) field-is-admin = Administrador (acceso irrestricto)
field-search-users = Buscar por usuario, email o nombre... field-search-users = Buscar por usuario, email o nombre...
help-username-strict =
Entre { $min } y { $max } caracteres: letras sin tildes ni eñes, números, punto, guion o guion
bajo, empezando por una letra o un número. No se distinguen mayúsculas al iniciar sesión.
help-username-unicode =
Entre { $min } y { $max } caracteres: letras de cualquier alfabeto (sin mezclarlos), números,
punto, guion o guion bajo, empezando por una letra o un número. No se distinguen mayúsculas
al iniciar sesión.
help-username-permissive =
Entre { $min } y { $max } caracteres: letras de cualquier alfabeto (sin mezclarlos), números,
espacios simples, punto, guion, guion bajo, apóstrofo o «+», empezando por una letra o un
número. No se distinguen mayúsculas al iniciar sesión.
help-password-min-length = Al menos { $n } caracteres.
help-machine-name-immutable = help-machine-name-immutable =
Sólo minúsculas, dígitos y guiones bajos. No se puede cambiar tras crearlo. Sólo minúsculas, dígitos y guiones bajos. No se puede cambiar tras crearlo.
help-admin-roles = help-admin-roles =
Como administrador tiene todos los permisos. Estos roles se aplicarán si deja de serlo. Esta cuenta es de administrador y tiene todos los permisos. Estos roles se aplicarán si deja de
serlo.
# **< Administración: botones y enlaces >** # **< Administración: botones y enlaces >**
@ -167,7 +218,8 @@ empty-role-permissions = Este rol no tiene permisos.
error-role-not-found = Rol no encontrado. error-role-not-found = Rol no encontrado.
error-role-machine-name-taken = Este nombre técnico ya está en uso. error-role-machine-name-taken = Este nombre técnico ya está en uso.
error-invalid-machine-name = El nombre técnico sólo admite minúsculas, dígitos y guiones bajos. error-invalid-machine-name = El nombre técnico sólo admite minúsculas, dígitos y guiones bajos, hasta { $n } caracteres.
error-invalid-role-label = La etiqueta no puede quedar vacía ni superar { $n } caracteres.
error-role-locked = Este rol es de sistema y no se puede modificar. error-role-locked = Este rol es de sistema y no se puede modificar.
error-role-in-use = Este rol tiene usuarios asignados y no se puede eliminar. error-role-in-use = Este rol tiene usuarios asignados y no se puede eliminar.
error-last-administrator = No se puede quitar al último administrador. error-last-administrator = No se puede quitar al último administrador.

View file

@ -0,0 +1,210 @@
//! Correos con enlaces de un solo uso: recuperación de contraseña y verificación de email.
use pagetop::prelude::*;
use pagetop_mail::prelude::*;
use crate::config;
use crate::token::TokenKind;
use crate::{LOCALES_USER, PASSWORD_RESET_PATH, VERIFY_PATH};
// Estilo del enlace principal, con aspecto de botón.
const BUTTON_STYLE: &str = concat!(
"display: inline-block; padding: 10px 20px; border-radius: 4px; ",
"background-color: #2563eb; color: #ffffff; text-decoration: none; font-weight: 600;"
);
// Correo con el enlace que consume un token del usuario.
struct TokenMail {
kind: TokenKind,
// Nombre de usuario para el saludo, sólo si la dirección está verificada (ver `recipient()`).
username: Option<String>,
link: String,
}
impl TokenMail {
// Claves de los textos propios de cada tipo de token: asunto, introducción, texto del enlace y
// aviso para quien no lo haya solicitado.
fn keys(&self) -> [&'static str; 4] {
match self.kind {
TokenKind::PasswordReset => [
"mail-reset-subject",
"mail-reset-intro",
"mail-reset-action",
"mail-reset-ignore",
],
TokenKind::EmailVerification => [
"mail-verify-subject",
"mail-verify-intro",
"mail-verify-action",
"mail-verify-ignore",
],
}
}
fn expires(&self) -> Lc {
let hours = u32::try_from(self.kind.ttl_secs() / 3600).unwrap_or(u32::MAX);
Lc::t("mail-link-expires", &LOCALES_USER).with_number("hours", hours)
}
}
impl MailTemplate for TokenMail {
fn subject(&self, cx: &Context) -> String {
Lc::t(self.keys()[0], &LOCALES_USER)
.with_arg("app", &global::SETTINGS.app.name)
.lookup(cx)
.unwrap_or_default()
}
fn html(&self, cx: &Context) -> Option<Markup> {
let [_, intro, action, ignore] = self.keys();
let greeting = match &self.username {
// El nombre de usuario lo elige quien creó la cuenta: va con `with_arg()`, que lo
// escapa, nunca con `with_markup()`.
Some(username) => {
Lc::t("mail-greeting", &LOCALES_USER).with_arg("username", username.clone())
}
None => Lc::t("mail-greeting-plain", &LOCALES_USER),
};
Some(html! {
p { (greeting.using(cx)) }
p { (Lc::t(intro, &LOCALES_USER).using(cx)) }
p style="margin: 24px 0;" {
a href=(self.link) style=(BUTTON_STYLE) { (Lc::t(action, &LOCALES_USER).using(cx)) }
}
p { (self.expires().using(cx)) }
p style="color: #6b7280;" { (Lc::t(ignore, &LOCALES_USER).using(cx)) }
})
}
}
// Envía en segundo plano el correo con el enlace que consume `token`.
//
// El correo sale en el idioma propio del usuario si lo tiene (y se aplica), o en el de la petición
// en curso. Se envía en segundo plano para que el tiempo de respuesta no revele si existe la
// cuenta, y porque un fallo del servidor de correo no debe impedir completar la petición: se
// registra en las trazas.
pub(crate) fn send_token_mail(
request: &HttpRequest,
kind: TokenKind,
user: &crate::entity::user::Model,
token: &str,
) {
let mut cx = Context::new(request.clone());
if config::user_language_applies()
&& let Some(locale @ Locale::Resolved(_)) = user.language.as_deref().map(Locale::resolve)
{
cx.alter_langid(&locale);
}
let (username, to) = recipient(user);
token_email(&cx, kind, user.id, username, to, token).send_later();
}
// Destinatario del correo y nombre de usuario para el saludo.
//
// Mientras la dirección no esté verificada, el correo puede llegar a otra persona: cualquiera puede
// crear una cuenta con una dirección ajena, y con `require_email_verification = false` la cuenta
// queda activa y puede pedir la recuperación de contraseña. El correo sale del dominio de la
// aplicación y con su diseño, así que pasa los filtros y resulta creíble: no incluye nada que elija
// quien creó la cuenta, ni el nombre de usuario ni el nombre visible (tampoco en la cabecera `To`),
// porque bastaría para colar un texto o un enlace engañoso (*phishing*). Se puede iniciar sesión
// con el email, así que el nombre de usuario no hace falta para recuperar el acceso.
fn recipient(user: &crate::entity::user::Model) -> (Option<String>, Mailbox) {
if user.email_verified_at.is_none() {
return (None, Mailbox::new(user.email.as_str()));
}
let name =
util::non_blank(user.display_name.as_deref().unwrap_or_default()).unwrap_or(&user.username);
(
Some(user.username.clone()),
Mailbox::from((name, user.email.as_str())),
)
}
// Compone el correo con el enlace que consume `token` del usuario `user_id`.
fn token_email(
cx: &Context,
kind: TokenKind,
user_id: i32,
username: Option<String>,
to: Mailbox,
token: &str,
) -> Email {
let base = match kind {
TokenKind::PasswordReset => PASSWORD_RESET_PATH,
TokenKind::EmailVerification => VERIFY_PATH,
};
let path = util::join!(base, "/", user_id.to_string(), "/", token);
let template = TokenMail {
kind,
username,
link: absolute_url(cx.route(path)),
};
Email::from_template(&template, cx).with_to(to)
}
// **< Vistas previas >*****************************************************************************
// Declara las vistas previas de los correos de `pagetop-user`, con datos de ejemplo.
pub(crate) fn declare_previews(previews: &mut MailPreviews) {
previews.add(
"user.email_verification",
Lc::t("mail-preview-verify", &LOCALES_USER),
|cx| sample(cx, TokenKind::EmailVerification),
);
previews.add(
"user.password_reset",
Lc::t("mail-preview-reset", &LOCALES_USER),
|cx| sample(cx, TokenKind::PasswordReset),
);
}
// La verificación se envía a una dirección sin verificar (sin nombre); la recuperación, a la de una
// cuenta verificada (ver `recipient()`).
fn sample(cx: &Context, kind: TokenKind) -> Email {
let (username, to) = match kind {
TokenKind::EmailVerification => (None, Mailbox::new("ana@example.com")),
TokenKind::PasswordReset => (
Some("ana".to_owned()),
Mailbox::from(("Ana Pérez", "ana@example.com")),
),
};
token_email(cx, kind, 42, username, to, "EXAMPLE-TOKEN")
}
#[cfg(test)]
mod tests {
use super::*;
const USERNAME: &str = r#"<a href="https://evil.example">ana</a>"#;
fn html(username: Option<&str>) -> String {
let mail = TokenMail {
kind: TokenKind::PasswordReset,
username: username.map(str::to_owned),
link: "https://example.com/user/token".to_owned(),
};
mail.html(&Context::default()).unwrap().into_string()
}
// The username is chosen by whoever creates the account.
#[pagetop::test]
async fn username_cannot_inject_markup() {
let html = html(Some(USERNAME));
assert!(
!html.contains("evil.example\">"),
"username must be escaped: {html}"
);
assert!(html.contains("&lt;a href="));
}
// An unverified address may belong to someone else: nothing chosen by whoever created the
// account may appear in the email.
#[pagetop::test]
async fn unverified_address_gets_a_plain_greeting() {
let html = html(None);
assert!(
!html.contains("evil.example"),
"username must not appear: {html}"
);
}
}

View file

@ -9,8 +9,15 @@ impl MigrationTrait for Migration {
.create_table( .create_table(
table_auto(Users::Table) table_auto(Users::Table)
.col(pk_auto(Users::Id)) .col(pk_auto(Users::Id))
.col(string_len_uniq(Users::Username, 64)) // El nombre de usuario y el email con sus mayúsculas (ver `identity.rs`).
.col(string_len_uniq(Users::Email, 254)) .col(string_len(Users::Username, 64))
.col(string_len(Users::Email, 254))
// Formas para buscar y comparar sin distinguir mayúsculas, que pueden ser más
// largas que el original (en minúsculas, un carácter puede ocupar dos), y
// *hash* del esqueleto de confusión del nombre (ver `identity.rs`).
.col(string_len_uniq(Users::UsernameKey, 255))
.col(char_len_uniq(Users::UsernameSkeleton, 64))
.col(string_len_uniq(Users::EmailKey, 255))
.col(timestamp_null(Users::EmailVerifiedAt)) .col(timestamp_null(Users::EmailVerifiedAt))
.col(string(Users::PasswordHash)) .col(string(Users::PasswordHash))
// 0=Blocked, 1=Active, 2=Pending // 0=Blocked, 1=Active, 2=Pending
@ -24,6 +31,7 @@ impl MigrationTrait for Migration {
.col(timestamp_null(Users::LastLoginAt)) .col(timestamp_null(Users::LastLoginAt))
.col(timestamp_null(Users::LastAccessAt)) .col(timestamp_null(Users::LastAccessAt))
.col(integer(Users::FailedLoginCount).default(0)) .col(integer(Users::FailedLoginCount).default(0))
.col(timestamp_null(Users::FailedLoginAt))
.col(timestamp_null(Users::LockedUntil)) .col(timestamp_null(Users::LockedUntil))
// Acceso irrestricto al sistema, sin pasar por roles ni permisos. // Acceso irrestricto al sistema, sin pasar por roles ni permisos.
.col(boolean(Users::IsAdmin).default(false)) .col(boolean(Users::IsAdmin).default(false))
@ -45,6 +53,9 @@ pub enum Users {
Id, Id,
Username, Username,
Email, Email,
UsernameKey,
UsernameSkeleton,
EmailKey,
EmailVerifiedAt, EmailVerifiedAt,
PasswordHash, PasswordHash,
Status, Status,
@ -56,6 +67,7 @@ pub enum Users {
LastLoginAt, LastLoginAt,
LastAccessAt, LastAccessAt,
FailedLoginCount, FailedLoginCount,
FailedLoginAt,
LockedUntil, LockedUntil,
IsAdmin, IsAdmin,
} }

View file

@ -6,6 +6,8 @@ use argon2::{
}; };
use rand_core::OsRng; use rand_core::OsRng;
use std::sync::LazyLock;
use crate::config::SETTINGS; use crate::config::SETTINGS;
use crate::error::AuthError; use crate::error::AuthError;
@ -38,25 +40,51 @@ pub fn verify_password(plain: &str, phc: &str) -> bool {
.is_ok() .is_ok()
} }
/// Indica si el hash necesita actualizarse (parámetros de coste han cambiado). // Versiones de `hash_password()` y `verify_password()` para las peticiones: el cálculo se hace en
// el *pool* de hilos bloqueantes de Tokio. Con los costes por defecto tarda decenas de milisegundos,
// que retendrían un hilo del *runtime* asíncrono y retrasarían las demás peticiones (p. ej. durante
// un intento de fuerza bruta contra el inicio de sesión).
pub(crate) async fn hash_password_async(plain: &str) -> Result<String, AuthError> {
let plain = plain.to_owned();
tokio::task::spawn_blocking(move || hash_password(&plain))
.await
.map_err(|err| AuthError::PasswordHash(err.to_string()))?
}
pub(crate) async fn verify_password_async(plain: &str, phc: &str) -> bool {
let (plain, phc) = (plain.to_owned(), phc.to_owned());
tokio::task::spawn_blocking(move || verify_password(&plain, &phc))
.await
.unwrap_or(false)
}
// Verifica la contraseña contra un *hash* que no corresponde a ninguna cuenta. Cuando no existe la
// cuenta, iguala el tiempo de respuesta al de una contraseña errónea: si no, la diferencia
// revelaría qué cuentas existen.
pub(crate) async fn verify_password_without_account(plain: &str) {
static DUMMY_HASH: LazyLock<String> =
LazyLock::new(|| hash_password("pagetop-user-dummy-password").unwrap_or_default());
verify_password_async(plain, DUMMY_HASH.as_str()).await;
}
/// Indica si el hash necesita actualizarse: no es de Argon2id o se cifró con otros parámetros de
/// coste que los configurados.
pub fn needs_rehash(phc: &str) -> bool { pub fn needs_rehash(phc: &str) -> bool {
let Ok(parsed) = PasswordHash::new(phc) else { let Ok(parsed) = PasswordHash::new(phc) else {
return true; return true;
}; };
// Compara el coste de memoria con el configurado. let cost = |name: &str| parsed.params.get_decimal(name);
if let Some(m_cost) = parsed.params.get_str("m") { let password = &SETTINGS.password;
let current: u32 = m_cost.parse().unwrap_or(0); parsed.algorithm != argon2::Algorithm::Argon2id.ident()
if current != SETTINGS.password.argon2_m_cost { || cost("m") != Some(password.argon2_m_cost)
return true; || cost("t") != Some(password.argon2_t_cost)
} || cost("p") != Some(password.argon2_p_cost)
}
false
} }
/// Valida la longitud mínima y devuelve error si no se cumple. /// Valida la longitud mínima, en caracteres, y devuelve error si no se cumple.
pub fn validate_strength(plain: &str) -> Result<(), AuthError> { pub fn validate_strength(plain: &str) -> Result<(), AuthError> {
let min = SETTINGS.password.min_length; let min = SETTINGS.password.min_length;
if plain.len() < min { if plain.chars().count() < min {
Err(AuthError::PasswordTooShort(min)) Err(AuthError::PasswordTooShort(min))
} else { } else {
Ok(()) Ok(())

View file

@ -180,9 +180,14 @@ pub enum UserPermission {
AdminUsers, AdminUsers,
/// Acceder al mantenimiento de roles (listado, alta, edición, borrado). /// Acceder al mantenimiento de roles (listado, alta, edición, borrado).
AdminRoles, AdminRoles,
/// Acceder al listado de permisos y a la asignación de permisos a roles. /// Acceder al listado de permisos y, junto con `AdminRoles`, a la asignación de permisos a
/// roles.
///
/// Es el permiso más sensible del catálogo: con `AdminRoles`, quien lo tiene puede conceder
/// cualquier permiso al rol "authenticated", que tienen todas las cuentas, incluida la suya.
AdminPermissions, AdminPermissions,
/// Bloquear y desbloquear cuentas de usuario. /// Bloquear y activar cuentas de usuario, desde la edición del usuario; requiere también
/// `AdminUsers`.
BlockAccounts, BlockAccounts,
} }
@ -253,7 +258,7 @@ fn builtin_group_label(group: &str) -> Lc {
let key = match group { let key = match group {
GROUP_USERS => "group-users", GROUP_USERS => "group-users",
GROUP_ADMINISTRATION => "group-administration", GROUP_ADMINISTRATION => "group-administration",
_ => unreachable!("grupo de permisos integrado desconocido: {group}"), _ => unreachable!("unknown built-in permission group: {group}"),
}; };
Lc::t(key, &LOCALES_USER) Lc::t(key, &LOCALES_USER)
} }

View file

@ -168,19 +168,37 @@ pub(crate) struct NewRoleData<'a> {
pub weight: i32, pub weight: i32,
} }
/// Longitud máxima, en caracteres, del nombre técnico de un rol, la de su columna. `u16` porque
/// también limita el campo del formulario (`maxlength`), igual que [`ROLE_LABEL_MAX_CHARS`].
pub(crate) const ROLE_MACHINE_NAME_MAX_CHARS: u16 = 64;
/// Longitud máxima, en caracteres, de la etiqueta de un rol, la de su columna.
pub(crate) const ROLE_LABEL_MAX_CHARS: u16 = 128;
// Sólo minúsculas ASCII, dígitos y guiones bajos (ver el texto de ayuda del formulario, // Sólo minúsculas ASCII, dígitos y guiones bajos (ver el texto de ayuda del formulario,
// "help-machine-name-immutable"); el machine_name es inmutable tras la creación. // "help-machine-name-immutable"); el machine_name es inmutable tras la creación.
fn is_valid_machine_name(name: &str) -> bool { fn is_valid_machine_name(name: &str) -> bool {
!name.is_empty() (1..=usize::from(ROLE_MACHINE_NAME_MAX_CHARS)).contains(&name.len())
&& name && name
.bytes() .bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_') .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
} }
// Etiqueta sin espacios en los extremos; no puede quedar vacía ni superar la longitud máxima.
fn validate_label(label: &str) -> Result<&str, AuthError> {
let label = label.trim();
let max = usize::from(ROLE_LABEL_MAX_CHARS);
if label.is_empty() || label.chars().count() > max {
return Err(AuthError::InvalidRoleLabel(max));
}
Ok(label)
}
pub(crate) async fn create_role(data: NewRoleData<'_>) -> Result<i32, AuthError> { pub(crate) async fn create_role(data: NewRoleData<'_>) -> Result<i32, AuthError> {
if !is_valid_machine_name(data.machine_name) { if !is_valid_machine_name(data.machine_name) {
return Err(AuthError::InvalidMachineName); return Err(AuthError::InvalidMachineName);
} }
let label = validate_label(data.label)?;
if role::Entity::find() if role::Entity::find()
.filter(role::Column::MachineName.eq(data.machine_name)) .filter(role::Column::MachineName.eq(data.machine_name))
@ -195,7 +213,7 @@ pub(crate) async fn create_role(data: NewRoleData<'_>) -> Result<i32, AuthError>
let new_role = role::ActiveModel { let new_role = role::ActiveModel {
id: ActiveValue::NotSet, id: ActiveValue::NotSet,
machine_name: Set(data.machine_name.to_owned()), machine_name: Set(data.machine_name.to_owned()),
label: Set(data.label.to_owned()), label: Set(label.to_owned()),
description: Set(data.description.map(str::to_owned)), description: Set(data.description.map(str::to_owned)),
weight: Set(data.weight), weight: Set(data.weight),
locked: Set(false), locked: Set(false),
@ -219,11 +237,12 @@ pub(crate) async fn update_role(role_id: i32, data: RoleUpdateData<'_>) -> Resul
if role.locked { if role.locked {
return Err(AuthError::RoleLocked); return Err(AuthError::RoleLocked);
} }
let label = validate_label(data.label)?;
let now = Utc::now(); let now = Utc::now();
role::ActiveModel { role::ActiveModel {
id: Set(role_id), id: Set(role_id),
label: Set(data.label.to_owned()), label: Set(label.to_owned()),
description: Set(data.description.map(str::to_owned)), description: Set(data.description.map(str::to_owned)),
weight: Set(data.weight), weight: Set(data.weight),
updated_at: Set(now), updated_at: Set(now),
@ -272,7 +291,18 @@ pub(crate) async fn set_role_permissions(
} }
let now = Utc::now(); let now = Utc::now();
let keys = permission_keys.to_vec(); // Sin repetidos: una clave repetida en el formulario violaría la clave primaria.
let mut keys = permission_keys.to_vec();
keys.sort_unstable();
keys.dedup();
let rows: Vec<_> = keys
.into_iter()
.map(|key| role_permission::ActiveModel {
role_id: Set(role_id),
permission_key: Set(key),
granted_at: Set(now),
})
.collect();
dbconn() dbconn()
.transaction::<_, _, AuthError>(|txn| { .transaction::<_, _, AuthError>(|txn| {
Box::pin(async move { Box::pin(async move {
@ -280,13 +310,9 @@ pub(crate) async fn set_role_permissions(
.filter(role_permission::Column::RoleId.eq(role_id)) .filter(role_permission::Column::RoleId.eq(role_id))
.exec(txn) .exec(txn)
.await?; .await?;
for key in keys { if !rows.is_empty() {
role_permission::Entity::insert(role_permission::ActiveModel { role_permission::Entity::insert_many(rows)
role_id: Set(role_id), .exec_without_returning(txn)
permission_key: Set(key),
granted_at: Set(now),
})
.exec(txn)
.await?; .await?;
} }
Ok(()) Ok(())

View file

@ -3,6 +3,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use pagetop::prelude::*; use pagetop::prelude::*;
use pagetop_seaorm::db::query::{Expr, Func, LikeExpr};
use pagetop_seaorm::db::{ use pagetop_seaorm::db::{
ActiveModelTrait, ActiveValue, ColumnTrait, Condition, DatabaseTransaction, DbErr, EntityTrait, ActiveModelTrait, ActiveValue, ColumnTrait, Condition, DatabaseTransaction, DbErr, EntityTrait,
Order, Paginated, PaginatorTrait, QueryFilter, QueryOrder, Set, TransactionTrait, dbconn, Order, Paginated, PaginatorTrait, QueryFilter, QueryOrder, Set, TransactionTrait, dbconn,
@ -10,9 +11,10 @@ use pagetop_seaorm::db::{
}; };
use crate::account::UserStatus; use crate::account::UserStatus;
use crate::config::{user_language_applies, user_timezone_applies}; use crate::config::{SETTINGS, user_language_applies, user_timezone_applies};
use crate::entity::{role, user, user_role}; use crate::entity::{role, user, user_role};
use crate::error::AuthError; use crate::error::AuthError;
use crate::identity::{self, Email, Username};
use crate::password; use crate::password;
use crate::session; use crate::session;
@ -70,11 +72,23 @@ pub(crate) async fn list_users(
let mut select = user::Entity::find(); let mut select = user::Entity::find();
if let Some(q) = params.query.as_deref().and_then(util::non_blank) { if let Some(q) = params.query.as_deref().and_then(util::non_blank) {
// Sin distinguir mayúsculas: las claves ya están en minúsculas y el nombre visible se
// compara en minúsculas, igual en cualquier base de datos (con `LIKE`, PostgreSQL las
// distingue y SQLite o MySQL no).
select = select.filter( select = select.filter(
Condition::any() Condition::any()
.add(user::Column::Username.contains(q)) .add(
.add(user::Column::Email.contains(q)) Expr::col(user::Column::UsernameKey)
.add(user::Column::DisplayName.contains(q)), .like(contains_pattern(&identity::username_key(q))),
)
.add(
Expr::col(user::Column::EmailKey)
.like(contains_pattern(&identity::email_key(q))),
)
.add(
Expr::expr(Func::lower(Expr::col(user::Column::DisplayName)))
.like(contains_pattern(&q.to_lowercase())),
),
); );
} }
@ -84,8 +98,8 @@ pub(crate) async fn list_users(
Order::Asc Order::Asc
}; };
select = match params.sort { select = match params.sort {
UserSortField::Username => select.order_by(user::Column::Username, order), UserSortField::Username => select.order_by(user::Column::UsernameKey, order),
UserSortField::Email => select.order_by(user::Column::Email, order), UserSortField::Email => select.order_by(user::Column::EmailKey, order),
UserSortField::CreatedAt => select.order_by(user::Column::CreatedAt, order), UserSortField::CreatedAt => select.order_by(user::Column::CreatedAt, order),
}; };
@ -95,6 +109,22 @@ pub(crate) async fn list_users(
.await .await
} }
// Patrón `LIKE` que busca `text` en cualquier posición, con los comodines `%` y `_` escapados para
// que se busquen tal cual (p. ej. el `_` de `demo_user`). Se escapan con `!`, no con `\`, que
// MySQL interpreta también dentro de las cadenas.
fn contains_pattern(text: &str) -> LikeExpr {
let mut pattern = String::with_capacity(text.len() + 2);
pattern.push('%');
for c in text.chars() {
if matches!(c, '%' | '_' | '!') {
pattern.push('!');
}
pattern.push(c);
}
pattern.push('%');
LikeExpr::new(pattern).escape('!')
}
async fn user_items(users: Vec<user::Model>) -> Result<Vec<UserListItem>, AuthError> { async fn user_items(users: Vec<user::Model>) -> Result<Vec<UserListItem>, AuthError> {
let user_ids: Vec<i32> = users.iter().map(|u| u.id).collect(); let user_ids: Vec<i32> = users.iter().map(|u| u.id).collect();
let role_rows = user_role::Entity::find() let role_rows = user_role::Entity::find()
@ -176,6 +206,8 @@ pub(crate) struct NewUserData<'a> {
/// El usuario y sus roles se crean en una sola transacción: si falla cualquier inserción (p. ej. /// El usuario y sus roles se crean en una sola transacción: si falla cualquier inserción (p. ej.
/// porque se ha eliminado uno de los roles mientras tanto), no se crea nada. /// porque se ha eliminado uno de los roles mientras tanto), no se crea nada.
pub(crate) async fn create_user(data: NewUserData<'_>) -> Result<i32, AuthError> { pub(crate) async fn create_user(data: NewUserData<'_>) -> Result<i32, AuthError> {
let username = identity::username(data.username, SETTINGS.identity_policy, None)?;
let email = identity::email(data.email)?;
password::validate_strength(data.password)?; password::validate_strength(data.password)?;
password::passwords_match(data.password, data.confirm_password)?; password::passwords_match(data.password, data.confirm_password)?;
// El idioma y la zona horaria que no se aplican no se ofrecen en el formulario: se ignora lo // El idioma y la zona horaria que no se aplican no se ofrecen en el formulario: se ignora lo
@ -191,16 +223,15 @@ pub(crate) async fn create_user(data: NewUserData<'_>) -> Result<i32, AuthError>
None None
}; };
let theme = validate_theme(data.theme)?; let theme = validate_theme(data.theme)?;
ensure_username_available(data.username, None).await?; validate_display_name(data.display_name)?;
ensure_email_available(data.email, None).await?; ensure_username_available(&username, None).await?;
ensure_email_available(&email, None).await?;
let hash = password::hash_password(data.password)?; let hash = password::hash_password_async(data.password).await?;
let now = Utc::now(); let now = Utc::now();
let new_user = user::ActiveModel { let mut new_user = user::ActiveModel {
id: ActiveValue::NotSet, id: ActiveValue::NotSet,
username: Set(data.username.to_owned()),
email: Set(data.email.to_owned()),
email_verified_at: Set(Some(now)), email_verified_at: Set(Some(now)),
password_hash: Set(hash), password_hash: Set(hash),
status: Set(UserStatus::Active.as_i16()), status: Set(UserStatus::Active.as_i16()),
@ -216,7 +247,10 @@ pub(crate) async fn create_user(data: NewUserData<'_>) -> Result<i32, AuthError>
is_admin: Set(data.is_admin), is_admin: Set(data.is_admin),
created_at: Set(now), created_at: Set(now),
updated_at: Set(now), updated_at: Set(now),
..Default::default()
}; };
username.set_on(&mut new_user);
email.set_on(&mut new_user);
let role_ids = assignable_roles(data.initial_role_ids); let role_ids = assignable_roles(data.initial_role_ids);
dbconn() dbconn()
@ -240,6 +274,18 @@ pub(crate) async fn create_user(data: NewUserData<'_>) -> Result<i32, AuthError>
/// formulario (`maxlength`). /// formulario (`maxlength`).
pub(crate) const ABOUT_MAX_CHARS: u16 = 2000; pub(crate) const ABOUT_MAX_CHARS: u16 = 2000;
/// Longitud máxima, en caracteres, del nombre visible, la de su columna.
pub(crate) const DISPLAY_NAME_MAX_CHARS: u16 = 128;
// Comprueba que el nombre visible no supere la longitud de su columna.
fn validate_display_name(display_name: Option<&str>) -> Result<(), AuthError> {
let max = usize::from(DISPLAY_NAME_MAX_CHARS);
if display_name.is_some_and(|name| name.chars().count() > max) {
return Err(AuthError::DisplayNameTooLong(max));
}
Ok(())
}
pub(crate) struct UserUpdateData<'a> { pub(crate) struct UserUpdateData<'a> {
pub username: &'a str, pub username: &'a str,
pub email: &'a str, pub email: &'a str,
@ -248,9 +294,21 @@ pub(crate) struct UserUpdateData<'a> {
pub language: Option<&'a str>, pub language: Option<&'a str>,
pub timezone: Option<&'a str>, pub timezone: Option<&'a str>,
pub theme: Option<&'a str>, pub theme: Option<&'a str>,
/// Si un email nuevo se da por verificado: `true` cuando lo cambia un administrador, que da fe
/// de él igual que al dar de alta (ver [`create_user`]). Si lo cambia el propio usuario, queda
/// sin verificar hasta que se compruebe que la dirección es suya.
pub email_verified: bool,
} }
pub(crate) async fn update_user(user_id: i32, data: UserUpdateData<'_>) -> Result<(), AuthError> { pub(crate) async fn update_user(user_id: i32, data: UserUpdateData<'_>) -> Result<(), AuthError> {
// Un nombre que no cambia no se valida de nuevo con la política (ver `identity::username()`).
let current = find_user(user_id).await?;
let username = identity::username(
data.username,
SETTINGS.identity_policy,
Some(&current.username_key),
)?;
let email = identity::email(data.email)?;
// El idioma y la zona horaria que no se aplican tampoco se ofrecen en el formulario, así que no // El idioma y la zona horaria que no se aplican tampoco se ofrecen en el formulario, así que no
// llegan: se conserva lo guardado por si se vuelven a aplicar. // llegan: se conserva lo guardado por si se vuelven a aplicar.
let language = if user_language_applies() { let language = if user_language_applies() {
@ -261,7 +319,7 @@ pub(crate) async fn update_user(user_id: i32, data: UserUpdateData<'_>) -> Resul
let timezone = if user_timezone_applies() { let timezone = if user_timezone_applies() {
let timezone = match validate_timezone(data.timezone) { let timezone = match validate_timezone(data.timezone) {
Err(AuthError::InvalidTimezone) => { Err(AuthError::InvalidTimezone) => {
keep_current_timezone(user_id, data.timezone).await? keep_current_timezone(data.timezone, current.timezone.as_deref())?
} }
result => result?, result => result?,
}; };
@ -270,6 +328,7 @@ pub(crate) async fn update_user(user_id: i32, data: UserUpdateData<'_>) -> Resul
ActiveValue::NotSet ActiveValue::NotSet
}; };
let theme = validate_theme(data.theme)?; let theme = validate_theme(data.theme)?;
validate_display_name(data.display_name)?;
// El navegador envía los saltos de línea de un `<textarea>` como `\r\n`, pero `maxlength` puede // El navegador envía los saltos de línea de un `<textarea>` como `\r\n`, pero `maxlength` puede
// contarlos como un único carácter: se normalizan antes de medir para no rechazar un texto que // contarlos como un único carácter: se normalizan antes de medir para no rechazar un texto que
// el formulario sí admitió. // el formulario sí admitió.
@ -281,14 +340,12 @@ pub(crate) async fn update_user(user_id: i32, data: UserUpdateData<'_>) -> Resul
{ {
return Err(AuthError::AboutTooLong(max_about)); return Err(AuthError::AboutTooLong(max_about));
} }
ensure_username_available(data.username, Some(user_id)).await?; ensure_username_available(&username, Some(user_id)).await?;
ensure_email_available(data.email, Some(user_id)).await?; ensure_email_available(&email, Some(user_id)).await?;
let now = Utc::now(); let now = Utc::now();
user::ActiveModel { let mut model = user::ActiveModel {
id: Set(user_id), id: Set(user_id),
username: Set(data.username.to_owned()),
email: Set(data.email.to_owned()),
display_name: Set(data.display_name.map(str::to_owned)), display_name: Set(data.display_name.map(str::to_owned)),
about: Set(about), about: Set(about),
language, language,
@ -296,9 +353,13 @@ pub(crate) async fn update_user(user_id: i32, data: UserUpdateData<'_>) -> Resul
theme: Set(theme.map(str::to_owned)), theme: Set(theme.map(str::to_owned)),
updated_at: Set(now), updated_at: Set(now),
..Default::default() ..Default::default()
};
if *email.key() != current.email_key {
model.email_verified_at = Set(data.email_verified.then_some(now));
} }
.update(dbconn()) username.set_on(&mut model);
.await?; email.set_on(&mut model);
model.update(dbconn()).await?;
Ok(()) Ok(())
} }
@ -432,20 +493,23 @@ pub(crate) async fn set_user_admin(
// **< admin_reset_password >*********************************************************************** // **< admin_reset_password >***********************************************************************
/// Restablece la contraseña de un usuario como acción administrativa e invalida sus sesiones /// Restablece la contraseña de un usuario como acción administrativa, invalida sus sesiones
/// activas. /// activas y levanta el bloqueo temporal por intentos fallidos.
pub(crate) async fn admin_reset_password( pub(crate) async fn admin_reset_password(
user_id: i32, user_id: i32,
new_password: &str, new_password: &str,
) -> Result<(), AuthError> { ) -> Result<(), AuthError> {
find_user(user_id).await?; find_user(user_id).await?;
password::validate_strength(new_password)?; password::validate_strength(new_password)?;
let hash = password::hash_password(new_password)?; let hash = password::hash_password_async(new_password).await?;
let now = Utc::now(); let now = Utc::now();
user::ActiveModel { user::ActiveModel {
id: Set(user_id), id: Set(user_id),
password_hash: Set(hash), password_hash: Set(hash),
failed_login_count: Set(0),
failed_login_at: Set(None),
locked_until: Set(None),
updated_at: Set(now), updated_at: Set(now),
..Default::default() ..Default::default()
} }
@ -502,27 +566,28 @@ fn validate_timezone(timezone: Option<&str>) -> Result<Option<&str>, AuthError>
Ok(timezone) Ok(timezone)
} }
// Acepta una zona que ya no se ofrece si es la que el usuario tenía guardada: el selector la sigue // Acepta una zona que ya no se ofrece si es la que el usuario tenía guardada (`current`): el
// mostrando para que volver a guardar el formulario sin tocarla no la descarte. Sólo se consulta la // selector la sigue mostrando para que volver a guardar el formulario sin tocarla no la descarte.
// base de datos cuando la zona recibida no se ofrece. fn keep_current_timezone<'a>(
async fn keep_current_timezone( timezone: Option<&'a str>,
user_id: i32, current: Option<&str>,
timezone: Option<&str>, ) -> Result<Option<&'a str>, AuthError> {
) -> Result<Option<&str>, AuthError> {
let timezone = timezone.and_then(util::non_blank); let timezone = timezone.and_then(util::non_blank);
let current = find_user(user_id).await?.timezone; if timezone.is_some() && timezone == current {
if timezone.is_some() && timezone == current.as_deref() {
Ok(timezone) Ok(timezone)
} else { } else {
Err(AuthError::InvalidTimezone) Err(AuthError::InvalidTimezone)
} }
} }
async fn ensure_username_available( // Comprueba que no exista otra cuenta con el mismo nombre de usuario o con uno que se confunda con
username: &str, // él: los dos casos comparten el esqueleto.
pub(crate) async fn ensure_username_available(
username: &Username,
exclude_id: Option<i32>, exclude_id: Option<i32>,
) -> Result<(), AuthError> { ) -> Result<(), AuthError> {
let mut query = user::Entity::find().filter(user::Column::Username.eq(username)); let mut query =
user::Entity::find().filter(user::Column::UsernameSkeleton.eq(username.skeleton()));
if let Some(id) = exclude_id { if let Some(id) = exclude_id {
query = query.filter(user::Column::Id.ne(id)); query = query.filter(user::Column::Id.ne(id));
} }
@ -532,8 +597,12 @@ async fn ensure_username_available(
Ok(()) Ok(())
} }
async fn ensure_email_available(email: &str, exclude_id: Option<i32>) -> Result<(), AuthError> { // Comprueba que no exista otra cuenta con el mismo email, sin distinguir mayúsculas.
let mut query = user::Entity::find().filter(user::Column::Email.eq(email)); pub(crate) async fn ensure_email_available(
email: &Email,
exclude_id: Option<i32>,
) -> Result<(), AuthError> {
let mut query = user::Entity::find().filter(user::Column::EmailKey.eq(email.key()));
if let Some(id) = exclude_id { if let Some(id) = exclude_id {
query = query.filter(user::Column::Id.ne(id)); query = query.filter(user::Column::Id.ne(id));
} }

View file

@ -183,6 +183,15 @@ pub async fn load_user_from_session(sid: &str) -> (CurrentUser, Option<Account>,
if let Err(err) = result { if let Err(err) = result {
trace::warn!("session: failed to renew expiry: {err}"); trace::warn!("session: failed to renew expiry: {err}");
} }
// Último acceso del usuario, con la misma precisión que la prórroga de la sesión.
let result = user::Entity::update_many()
.col_expr(user::Column::LastAccessAt, Expr::value(now))
.filter(user::Column::Id.eq(sess.user_id))
.exec(dbconn())
.await;
if let Err(err) = result {
trace::warn!("session: failed to record last access: {err}");
}
} }
let language = user_model.language.take(); let language = user_model.language.take();
@ -222,10 +231,19 @@ fn renewed_expiry(
// **< create_session >***************************************************************************** // **< create_session >*****************************************************************************
/// Crea una nueva sesión en base de datos y devuelve el session ID. /// Crea una nueva sesión en base de datos y devuelve el session ID.
///
/// Borra antes las sesiones caducadas del usuario: las que se abandonan sin cerrar sesión no se
/// borran de otro modo, y así no se acumulan con cada inicio de sesión.
pub async fn create_session(user_id: i32, remember: bool) -> Result<String, DbErr> { pub async fn create_session(user_id: i32, remember: bool) -> Result<String, DbErr> {
let sid = generate_sid(); let sid = generate_sid();
let now = Utc::now(); let now = Utc::now();
session::Entity::delete_many()
.filter(session::Column::UserId.eq(user_id))
.filter(session::Column::ExpiresAt.lt(now))
.exec(dbconn())
.await?;
let new_session = session::ActiveModel { let new_session = session::ActiveModel {
sid: Set(sid.clone()), sid: Set(sid.clone()),
user_id: Set(user_id), user_id: Set(user_id),

View file

@ -2,10 +2,8 @@
//! email...). //! email...).
use pagetop::prelude::*; use pagetop::prelude::*;
use pagetop_seaorm::db::{ use pagetop_seaorm::db::query::Expr;
ActiveModelTrait, ActiveValue, ColumnTrait, EntityTrait, IntoActiveModel, QueryFilter, Set, use pagetop_seaorm::db::{ActiveValue, ColumnTrait, EntityTrait, QueryFilter, Set, dbconn};
dbconn,
};
use crate::entity::user_token; use crate::entity::user_token;
use crate::error::AuthError; use crate::error::AuthError;
@ -97,30 +95,42 @@ pub async fn create_token(user_id: i32, kind: TokenKind) -> Result<String, AuthE
Ok(token) Ok(token)
} }
// **< consume_token >****************************************************************************** // **< is_valid_token / consume_token >*************************************************************
/// Verifica que el token en claro sea válido (existe, no ha expirado y no ha sido consumido)
/// y lo marca como consumido. Devuelve el `user_id` asociado.
pub async fn consume_token(token: &str, kind: TokenKind) -> Result<i32, AuthError> {
let hash = hash_token(token);
let now = Utc::now();
/// Comprueba, sin consumirlo, que el token en claro sea válido para el usuario: existe, es del tipo
/// indicado, no ha caducado y no se ha consumido.
pub async fn is_valid_token(user_id: i32, token: &str, kind: TokenKind) -> Result<bool, AuthError> {
let row = user_token::Entity::find() let row = user_token::Entity::find()
.filter(user_token::Column::TokenHash.eq(&hash)) .filter(user_token::Column::TokenHash.eq(hash_token(token)))
.filter(user_token::Column::UserId.eq(user_id))
.filter(user_token::Column::Kind.eq(kind.as_str())) .filter(user_token::Column::Kind.eq(kind.as_str()))
.filter(user_token::Column::ConsumedAt.is_null())
.filter(user_token::Column::ExpiresAt.gt(Utc::now()))
.one(dbconn()) .one(dbconn())
.await? .await?;
.ok_or(AuthError::InvalidToken)?; Ok(row.is_some())
}
if row.consumed_at.is_some() || row.expires_at < now {
return Err(AuthError::InvalidToken); /// Consume el token en claro del usuario si es válido (ver [`is_valid_token()`]).
} ///
/// Falla con [`AuthError::InvalidToken`] si no lo es. Se marca como consumido en una sola
let user_id = row.user_id; /// sentencia condicionada a que siga sin consumir: dos peticiones simultáneas con el mismo enlace
let mut active = row.into_active_model(); /// no pueden usarlo las dos.
active.consumed_at = Set(Some(now)); pub async fn consume_token(user_id: i32, token: &str, kind: TokenKind) -> Result<(), AuthError> {
active.updated_at = Set(now); let now = Utc::now();
active.update(dbconn()).await?; let result = user_token::Entity::update_many()
.col_expr(user_token::Column::ConsumedAt, Expr::value(now))
Ok(user_id) .col_expr(user_token::Column::UpdatedAt, Expr::value(now))
.filter(user_token::Column::TokenHash.eq(hash_token(token)))
.filter(user_token::Column::UserId.eq(user_id))
.filter(user_token::Column::Kind.eq(kind.as_str()))
.filter(user_token::Column::ConsumedAt.is_null())
.filter(user_token::Column::ExpiresAt.gt(now))
.exec(dbconn())
.await?;
if result.rows_affected == 1 {
Ok(())
} else {
Err(AuthError::InvalidToken)
}
} }

View file

@ -188,14 +188,16 @@ impl CurrentUser {
/// impl Permission for MyPermission { /// impl Permission for MyPermission {
/// fn key(&self) -> CowStr { /// fn key(&self) -> CowStr {
/// match self { /// match self {
/// Self::EditPosts => "my_extension.edit_posts".into(), /// Self::EditPosts => "my_extension:edit_posts".into(),
/// Self::DeletePosts => "my_extension.delete_posts".into(), /// Self::DeletePosts => "my_extension:delete_posts".into(),
/// } /// }
/// } /// }
/// } /// }
/// ``` /// ```
pub trait Permission: Send + Sync { pub trait Permission: Send + Sync {
/// Clave única del permiso (p. ej. `"my_extension.edit_posts"`). /// Clave única del permiso. Por convención, el nombre de la extensión y el del permiso
/// separados por `:` (p. ej. `"my_extension:edit_posts"`), para que no coincida con la de otra
/// extensión.
fn key(&self) -> CowStr; fn key(&self) -> CowStr;
/// Descripción breve para humanos (p. ej. en una pantalla de asignación de permisos a roles). /// Descripción breve para humanos (p. ej. en una pantalla de asignación de permisos a roles).
@ -306,7 +308,7 @@ impl CheckPermission {
/// # #[derive(Clone, Copy, Debug)] /// # #[derive(Clone, Copy, Debug)]
/// # enum MyPermission { Edit } /// # enum MyPermission { Edit }
/// # impl Permission for MyPermission { /// # impl Permission for MyPermission {
/// # fn key(&self) -> CowStr { "myapp.edit".into() } /// # fn key(&self) -> CowStr { "myapp:edit".into() }
/// # } /// # }
/// async fn my_handler(request: HttpRequest) -> Result<Markup, ErrorPage> { /// async fn my_handler(request: HttpRequest) -> Result<Markup, ErrorPage> {
/// if !has_permission(&request, &MyPermission::Edit) { /// if !has_permission(&request, &MyPermission::Edit) {
@ -349,7 +351,7 @@ pub fn has_permission(request: &HttpRequest, perm: PermissionRef) -> bool {
/// # #[derive(Clone, Copy, Debug)] /// # #[derive(Clone, Copy, Debug)]
/// # enum MyPermission { Edit } /// # enum MyPermission { Edit }
/// # impl Permission for MyPermission { /// # impl Permission for MyPermission {
/// # fn key(&self) -> CowStr { "myapp.edit".into() } /// # fn key(&self) -> CowStr { "myapp:edit".into() }
/// # } /// # }
/// async fn my_handler(request: HttpRequest) -> Result<Markup, ErrorPage> { /// async fn my_handler(request: HttpRequest) -> Result<Markup, ErrorPage> {
/// // Comprueba si la petición está autorizada. /// // Comprueba si la petición está autorizada.

View file

@ -52,7 +52,7 @@ impl Waypoint {
/// Crea un valor explícito. /// Crea un valor explícito.
/// ///
/// Sólo acepta una ruta local que empiece por `/`, pero no por `//` ni `/\` que el navegador /// Sólo acepta una ruta local que empiece por `/`, pero no por `//` ni `/\` que el navegador
/// interpretaría como una URL *protocol-relative*. Una cadena vacía, una URL absoluta /// interpretaría como una URL *protocol-relative*, y sin caracteres de control. Una cadena vacía, una URL absoluta
/// (`https://...`), un esquema arbitrario (`javascript:...`) o cualquier otro valor que no /// (`https://...`), un esquema arbitrario (`javascript:...`) o cualquier otro valor que no
/// cumpla esa forma se trata igual que `None`. /// cumpla esa forma se trata igual que `None`.
/// ///
@ -64,12 +64,15 @@ impl Waypoint {
Self { Self {
waypoint: waypoint.into().filter(|d| { waypoint: waypoint.into().filter(|d| {
// Sólo acepta `/algo`. Rechaza cadenas vacías, esquemas (`https:`, `javascript:`) y // Sólo acepta `/algo`. Rechaza cadenas vacías, esquemas (`https:`, `javascript:`) y
// las URLs *protocol-relative* (`//evil.example`, `/\evil.example`). // las URLs *protocol-relative* (`//evil.example`, `/\evil.example`). También los
// caracteres de control: el navegador descarta tabuladores y saltos de línea de una
// URL, así que `/\t/evil.example` se convertiría en `//evil.example`.
let mut chars = d.chars(); let mut chars = d.chars();
match chars.next() { let local = match chars.next() {
Some('/') => !matches!(chars.next(), Some('/') | Some('\\')), Some('/') => !matches!(chars.next(), Some('/') | Some('\\')),
_ => false, _ => false,
} };
local && !d.chars().any(char::is_control)
}), }),
} }
} }

View file

@ -20,6 +20,10 @@ async fn waypoint_rejects_open_redirect_targets() {
"//evil.example", "//evil.example",
"/\\evil.example", "/\\evil.example",
"javascript:alert(1)", "javascript:alert(1)",
// Browsers strip tabs and newlines from URLs, turning these into `//evil.example`.
"/\t/evil.example",
"/\n/evil.example",
"/\r\n/evil.example",
] { ] {
let w = Waypoint::from(target.to_owned()); let w = Waypoint::from(target.to_owned());
assert_eq!(w.as_deref(), None, "expected {target:?} to be rejected"); assert_eq!(w.as_deref(), None, "expected {target:?} to be rejected");

View file

@ -67,6 +67,7 @@ case "$CRATE" in
--exclude-path "extensions/pagetop-aliner/**/*" --exclude-path "extensions/pagetop-aliner/**/*"
--exclude-path "extensions/pagetop-bootsier/**/*" --exclude-path "extensions/pagetop-bootsier/**/*"
--exclude-path "extensions/pagetop-htmx/**/*" --exclude-path "extensions/pagetop-htmx/**/*"
--exclude-path "extensions/pagetop-mail/**/*"
--exclude-path "extensions/pagetop-seaorm/**/*" --exclude-path "extensions/pagetop-seaorm/**/*"
--exclude-path "extensions/pagetop-user/**/*" --exclude-path "extensions/pagetop-user/**/*"
) )
@ -87,6 +88,10 @@ case "$CRATE" in
CHANGELOG_FILE="extensions/pagetop-htmx/CHANGELOG.md" CHANGELOG_FILE="extensions/pagetop-htmx/CHANGELOG.md"
PATH_FLAGS=(--include-path "extensions/pagetop-htmx/**/*") PATH_FLAGS=(--include-path "extensions/pagetop-htmx/**/*")
;; ;;
pagetop-mail)
CHANGELOG_FILE="extensions/pagetop-mail/CHANGELOG.md"
PATH_FLAGS=(--include-path "extensions/pagetop-mail/**/*")
;;
pagetop-seaorm) pagetop-seaorm)
CHANGELOG_FILE="extensions/pagetop-seaorm/CHANGELOG.md" CHANGELOG_FILE="extensions/pagetop-seaorm/CHANGELOG.md"
PATH_FLAGS=(--include-path "extensions/pagetop-seaorm/**/*") PATH_FLAGS=(--include-path "extensions/pagetop-seaorm/**/*")