Admin dashboard and sessions
This commit is contained in:
3
.cargo/config.toml
Normal file
3
.cargo/config.toml
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
[target.x86_64-unknown-linux-gnu]
|
||||||
|
linker = "clang"
|
||||||
|
rustflags = ["-C", "link-arg=-fuse-ld=/usr/bin/mold"]
|
||||||
166
Cargo.lock
generated
166
Cargo.lock
generated
@@ -66,6 +66,12 @@ version = "1.0.99"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b0674a1ddeecb70197781e945de4b3b8ffb61fa939a5597bcf48503737663100"
|
checksum = "b0674a1ddeecb70197781e945de4b3b8ffb61fa939a5597bcf48503737663100"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "arc-swap"
|
||||||
|
version = "1.7.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "69f7f8c3906b62b754cd5326047894316021dcfe5a194c8ea52bdd94934a3457"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "argon2"
|
name = "argon2"
|
||||||
version = "0.5.3"
|
version = "0.5.3"
|
||||||
@@ -133,6 +139,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "021e862c184ae977658b36c4500f7feac3221ca5da43e3f25bd04ab6c79a29b5"
|
checksum = "021e862c184ae977658b36c4500f7feac3221ca5da43e3f25bd04ab6c79a29b5"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"axum-core",
|
"axum-core",
|
||||||
|
"axum-macros",
|
||||||
"bytes",
|
"bytes",
|
||||||
"form_urlencoded",
|
"form_urlencoded",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
@@ -206,6 +213,17 @@ dependencies = [
|
|||||||
"tower-service",
|
"tower-service",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "axum-macros"
|
||||||
|
version = "0.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "604fde5e028fea851ce1d8570bbdc034bec850d157f7569d10f347d06808c05c"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "axum-messages"
|
name = "axum-messages"
|
||||||
version = "0.8.0"
|
version = "0.8.0"
|
||||||
@@ -300,6 +318,16 @@ version = "1.10.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
|
checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bytes-utils"
|
||||||
|
version = "0.1.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7dafe3a8757b027e2be6e4e5601ed563c55989fcf1546e933c66c8eb3a058d35"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"either",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cc"
|
name = "cc"
|
||||||
version = "1.2.33"
|
version = "1.2.33"
|
||||||
@@ -414,6 +442,12 @@ dependencies = [
|
|||||||
"version_check",
|
"version_check",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cookie-factory"
|
||||||
|
version = "0.3.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "396de984970346b0d9e93d1415082923c679e5ae5c3ee3dcbd104f5610af126b"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cookie_store"
|
name = "cookie_store"
|
||||||
version = "0.21.1"
|
version = "0.21.1"
|
||||||
@@ -462,6 +496,12 @@ version = "2.4.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5"
|
checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crc16"
|
||||||
|
version = "0.4.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "338089f42c427b86394a5ee60ff321da23a5c89c9d89514c829687b26359fcff"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "crossbeam-queue"
|
name = "crossbeam-queue"
|
||||||
version = "0.3.12"
|
version = "0.3.12"
|
||||||
@@ -697,6 +737,15 @@ dependencies = [
|
|||||||
"rand 0.9.2",
|
"rand 0.9.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "float-cmp"
|
||||||
|
version = "0.10.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b09cf3155332e944990140d967ff5eceb70df778b34f77d8075db46e4704e6d8"
|
||||||
|
dependencies = [
|
||||||
|
"num-traits",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "flume"
|
name = "flume"
|
||||||
version = "0.11.1"
|
version = "0.11.1"
|
||||||
@@ -729,6 +778,43 @@ dependencies = [
|
|||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fred"
|
||||||
|
version = "10.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3a7b2fd0f08b23315c13b6156f971aeedb6f75fb16a29ac1872d2eabccc1490e"
|
||||||
|
dependencies = [
|
||||||
|
"arc-swap",
|
||||||
|
"async-trait",
|
||||||
|
"bytes",
|
||||||
|
"bytes-utils",
|
||||||
|
"float-cmp",
|
||||||
|
"fred-macros",
|
||||||
|
"futures",
|
||||||
|
"log",
|
||||||
|
"parking_lot",
|
||||||
|
"rand 0.8.5",
|
||||||
|
"redis-protocol",
|
||||||
|
"semver",
|
||||||
|
"socket2 0.5.10",
|
||||||
|
"tokio",
|
||||||
|
"tokio-stream",
|
||||||
|
"tokio-util",
|
||||||
|
"url",
|
||||||
|
"urlencoding",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fred-macros"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1458c6e22d36d61507034d5afecc64f105c1d39712b7ac6ec3b352c423f715cc"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "futures"
|
name = "futures"
|
||||||
version = "0.3.31"
|
version = "0.3.31"
|
||||||
@@ -1421,6 +1507,12 @@ version = "0.3.17"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "minimal-lexical"
|
||||||
|
version = "0.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "miniz_oxide"
|
name = "miniz_oxide"
|
||||||
version = "0.8.9"
|
version = "0.8.9"
|
||||||
@@ -1441,6 +1533,16 @@ dependencies = [
|
|||||||
"windows-sys 0.59.0",
|
"windows-sys 0.59.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "nom"
|
||||||
|
version = "7.1.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
|
||||||
|
dependencies = [
|
||||||
|
"memchr",
|
||||||
|
"minimal-lexical",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "nu-ansi-term"
|
name = "nu-ansi-term"
|
||||||
version = "0.46.0"
|
version = "0.46.0"
|
||||||
@@ -1594,6 +1696,12 @@ dependencies = [
|
|||||||
"subtle",
|
"subtle",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "paste"
|
||||||
|
version = "1.0.15"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pathdiff"
|
name = "pathdiff"
|
||||||
version = "0.2.3"
|
version = "0.2.3"
|
||||||
@@ -1920,6 +2028,20 @@ dependencies = [
|
|||||||
"getrandom 0.3.3",
|
"getrandom 0.3.3",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "redis-protocol"
|
||||||
|
version = "6.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9cdba59219406899220fc4cdfd17a95191ba9c9afb719b5fa5a083d63109a9f1"
|
||||||
|
dependencies = [
|
||||||
|
"bytes",
|
||||||
|
"bytes-utils",
|
||||||
|
"cookie-factory",
|
||||||
|
"crc16",
|
||||||
|
"log",
|
||||||
|
"nom",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "redox_syscall"
|
name = "redox_syscall"
|
||||||
version = "0.5.17"
|
version = "0.5.17"
|
||||||
@@ -2027,6 +2149,28 @@ dependencies = [
|
|||||||
"windows-sys 0.52.0",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rmp"
|
||||||
|
version = "0.8.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "228ed7c16fa39782c3b3468e974aec2795e9089153cd08ee2e9aefb3613334c4"
|
||||||
|
dependencies = [
|
||||||
|
"byteorder",
|
||||||
|
"num-traits",
|
||||||
|
"paste",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rmp-serde"
|
||||||
|
version = "1.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "52e599a477cf9840e92f2cde9a7189e67b42c57532749bf90aea6ec10facd4db"
|
||||||
|
dependencies = [
|
||||||
|
"byteorder",
|
||||||
|
"rmp",
|
||||||
|
"serde",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ron"
|
name = "ron"
|
||||||
version = "0.8.1"
|
version = "0.8.1"
|
||||||
@@ -2145,6 +2289,12 @@ dependencies = [
|
|||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "semver"
|
||||||
|
version = "1.0.26"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "56e6fa9c48d24d85fb3de5ad847117517440f6beceb7798af16b4a87d616b8d0"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde"
|
name = "serde"
|
||||||
version = "1.0.219"
|
version = "1.0.219"
|
||||||
@@ -2925,6 +3075,20 @@ dependencies = [
|
|||||||
"tower-sessions-core",
|
"tower-sessions-core",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tower-sessions-redis-store"
|
||||||
|
version = "0.16.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8e15b774f3d46625a27a8ac1238ecd73c8bd50013244e2de004026e161aad728"
|
||||||
|
dependencies = [
|
||||||
|
"async-trait",
|
||||||
|
"fred",
|
||||||
|
"rmp-serde",
|
||||||
|
"thiserror",
|
||||||
|
"time",
|
||||||
|
"tower-sessions-core",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tracing"
|
name = "tracing"
|
||||||
version = "0.1.41"
|
version = "0.1.41"
|
||||||
@@ -3116,6 +3280,7 @@ checksum = "f33196643e165781c20a5ead5582283a7dacbb87855d867fbc2df3f81eddc1be"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"getrandom 0.3.3",
|
"getrandom 0.3.3",
|
||||||
"js-sys",
|
"js-sys",
|
||||||
|
"serde",
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -3659,6 +3824,7 @@ dependencies = [
|
|||||||
"tokio",
|
"tokio",
|
||||||
"tower-http",
|
"tower-http",
|
||||||
"tower-sessions",
|
"tower-sessions",
|
||||||
|
"tower-sessions-redis-store",
|
||||||
"tracing",
|
"tracing",
|
||||||
"tracing-bunyan-formatter",
|
"tracing-bunyan-formatter",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
|
|||||||
24
Cargo.toml
24
Cargo.toml
@@ -11,14 +11,10 @@ path = "src/lib.rs"
|
|||||||
path = "src/main.rs"
|
path = "src/main.rs"
|
||||||
name = "zero2prod"
|
name = "zero2prod"
|
||||||
|
|
||||||
[target.x86_64-unknown-linux-gnu]
|
|
||||||
linker = "clang"
|
|
||||||
rustflags = ["-C", "link-arg=-fuse-ld=/usr/bin/mold"]
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1.0.99"
|
anyhow = "1.0.99"
|
||||||
argon2 = { version = "0.5.3", features = ["std"] }
|
argon2 = { version = "0.5.3", features = ["std"] }
|
||||||
axum = "0.8.4"
|
axum = { version = "0.8.4", features = ["macros"] }
|
||||||
axum-extra = { version = "0.10.1", features = ["query", "cookie"] }
|
axum-extra = { version = "0.10.1", features = ["query", "cookie"] }
|
||||||
axum-messages = "0.8.0"
|
axum-messages = "0.8.0"
|
||||||
base64 = "0.22.1"
|
base64 = "0.22.1"
|
||||||
@@ -26,22 +22,34 @@ chrono = { version = "0.4.41", default-features = false, features = ["clock"] }
|
|||||||
config = "0.15.14"
|
config = "0.15.14"
|
||||||
htmlescape = "0.3.1"
|
htmlescape = "0.3.1"
|
||||||
rand = { version = "0.9.2", features = ["std_rng"] }
|
rand = { version = "0.9.2", features = ["std_rng"] }
|
||||||
reqwest = { version = "0.12.23", default-features = false, features = ["rustls-tls", "json", "cookies"] }
|
reqwest = { version = "0.12.23", default-features = false, features = [
|
||||||
|
"rustls-tls",
|
||||||
|
"json",
|
||||||
|
"cookies",
|
||||||
|
] }
|
||||||
secrecy = { version = "0.10.3", features = ["serde"] }
|
secrecy = { version = "0.10.3", features = ["serde"] }
|
||||||
serde = { version = "1.0.219", features = ["derive"] }
|
serde = { version = "1.0.219", features = ["derive"] }
|
||||||
serde-aux = "4.7.0"
|
serde-aux = "4.7.0"
|
||||||
sha3 = "0.10.8"
|
sha3 = "0.10.8"
|
||||||
sqlx = { version = "0.8.6", features = ["runtime-tokio-rustls", "macros", "postgres", "uuid", "chrono", "migrate"] }
|
sqlx = { version = "0.8.6", features = [
|
||||||
|
"runtime-tokio-rustls",
|
||||||
|
"macros",
|
||||||
|
"postgres",
|
||||||
|
"uuid",
|
||||||
|
"chrono",
|
||||||
|
"migrate",
|
||||||
|
] }
|
||||||
thiserror = "2.0.16"
|
thiserror = "2.0.16"
|
||||||
tokio = { version = "1.47.1", features = ["macros", "rt-multi-thread"] }
|
tokio = { version = "1.47.1", features = ["macros", "rt-multi-thread"] }
|
||||||
tower-http = { version = "0.6.6", features = ["trace"] }
|
tower-http = { version = "0.6.6", features = ["trace"] }
|
||||||
tower-sessions = "0.14.0"
|
tower-sessions = "0.14.0"
|
||||||
|
tower-sessions-redis-store = "0.16.0"
|
||||||
tracing = "0.1.41"
|
tracing = "0.1.41"
|
||||||
tracing-bunyan-formatter = "0.3.10"
|
tracing-bunyan-formatter = "0.3.10"
|
||||||
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
|
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
|
||||||
unicode-segmentation = "1.12.0"
|
unicode-segmentation = "1.12.0"
|
||||||
urlencoding = "2.1.3"
|
urlencoding = "2.1.3"
|
||||||
uuid = { version = "1.18.0", features = ["v4"] }
|
uuid = { version = "1.18.0", features = ["v4", "serde"] }
|
||||||
validator = { version = "0.20.0", features = ["derive"] }
|
validator = { version = "0.20.0", features = ["derive"] }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
|||||||
6
migrations/20250831121659_seed_user.sql
Normal file
6
migrations/20250831121659_seed_user.sql
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
INSERT INTO users (user_id, username, password_hash)
|
||||||
|
VALUES (
|
||||||
|
'd2492680-6e45-4179-b369-1439b8f22051',
|
||||||
|
'admin',
|
||||||
|
'$argon2id$v=19$m=19456,t=2,p=1$oWy180x7KxJYiTHzoN3sVw$vTgzvEqACiXjGalYUJHgb329Eb+s6wu5r+Cw8dHR5YE'
|
||||||
|
);
|
||||||
18
scripts/init_redis.sh
Executable file
18
scripts/init_redis.sh
Executable file
@@ -0,0 +1,18 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
set -x
|
||||||
|
set -eo pipefail
|
||||||
|
|
||||||
|
RUNNING_CONTAINER=$(docker ps --filter 'name=redis' --format '{{.ID}}')
|
||||||
|
if [[ -n $RUNNING_CONTAINER ]]; then
|
||||||
|
echo >&2 "A redis container is already running (${RUNNING_CONTAINER})."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
docker run \
|
||||||
|
-p "6379:6379" \
|
||||||
|
-d \
|
||||||
|
--name "redis_$(date '+%s')" \
|
||||||
|
redis
|
||||||
|
|
||||||
|
>&2 echo "Redis is ready to go!"
|
||||||
@@ -1,11 +1,13 @@
|
|||||||
|
use crate::telemetry::spawn_blocking_with_tracing;
|
||||||
use anyhow::Context;
|
use anyhow::Context;
|
||||||
use argon2::{Argon2, PasswordHash, PasswordVerifier};
|
use argon2::{
|
||||||
|
Algorithm, Argon2, Params, PasswordHash, PasswordHasher, PasswordVerifier, Version,
|
||||||
|
password_hash::{SaltString, rand_core::OsRng},
|
||||||
|
};
|
||||||
use secrecy::{ExposeSecret, SecretString};
|
use secrecy::{ExposeSecret, SecretString};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::telemetry::spawn_blocking_with_tracing;
|
|
||||||
|
|
||||||
pub struct Credentials {
|
pub struct Credentials {
|
||||||
pub username: String,
|
pub username: String,
|
||||||
pub password: SecretString,
|
pub password: SecretString,
|
||||||
@@ -19,6 +21,38 @@ pub enum AuthError {
|
|||||||
InvalidCredentials(#[source] anyhow::Error),
|
InvalidCredentials(#[source] anyhow::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(name = "Change password", skip(password, connection_pool))]
|
||||||
|
pub async fn change_password(
|
||||||
|
user_id: Uuid,
|
||||||
|
password: SecretString,
|
||||||
|
connection_pool: &PgPool,
|
||||||
|
) -> Result<(), anyhow::Error> {
|
||||||
|
let password_hash = spawn_blocking_with_tracing(move || compute_pasword_hash(password))
|
||||||
|
.await?
|
||||||
|
.context("Failed to hash password")?;
|
||||||
|
sqlx::query!(
|
||||||
|
"UPDATE users SET password_hash = $1 WHERE user_id = $2",
|
||||||
|
password_hash.expose_secret(),
|
||||||
|
user_id
|
||||||
|
)
|
||||||
|
.execute(connection_pool)
|
||||||
|
.await
|
||||||
|
.context("Failed to update user password in the database.")?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn compute_pasword_hash(password: SecretString) -> Result<SecretString, anyhow::Error> {
|
||||||
|
let salt = SaltString::generate(&mut OsRng);
|
||||||
|
let password_hash = Argon2::new(
|
||||||
|
Algorithm::Argon2id,
|
||||||
|
Version::V0x13,
|
||||||
|
Params::new(1500, 2, 1, None).unwrap(),
|
||||||
|
)
|
||||||
|
.hash_password(password.expose_secret().as_bytes(), &salt)?
|
||||||
|
.to_string();
|
||||||
|
Ok(SecretString::from(password_hash))
|
||||||
|
}
|
||||||
|
|
||||||
#[tracing::instrument(
|
#[tracing::instrument(
|
||||||
name = "Validate credentials",
|
name = "Validate credentials",
|
||||||
skip(username, password, connection_pool)
|
skip(username, password, connection_pool)
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ pub struct Settings {
|
|||||||
pub application: ApplicationSettings,
|
pub application: ApplicationSettings,
|
||||||
pub database: DatabaseSettings,
|
pub database: DatabaseSettings,
|
||||||
pub email_client: EmailClientSettings,
|
pub email_client: EmailClientSettings,
|
||||||
|
pub redis_uri: SecretString,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
|
|||||||
@@ -3,5 +3,6 @@ pub mod configuration;
|
|||||||
pub mod domain;
|
pub mod domain;
|
||||||
pub mod email_client;
|
pub mod email_client;
|
||||||
pub mod routes;
|
pub mod routes;
|
||||||
|
pub mod session_state;
|
||||||
pub mod startup;
|
pub mod startup;
|
||||||
pub mod telemetry;
|
pub mod telemetry;
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
mod admin;
|
||||||
mod health_check;
|
mod health_check;
|
||||||
mod home;
|
mod home;
|
||||||
mod login;
|
mod login;
|
||||||
@@ -5,6 +6,7 @@ mod newsletters;
|
|||||||
mod subscriptions;
|
mod subscriptions;
|
||||||
mod subscriptions_confirm;
|
mod subscriptions_confirm;
|
||||||
|
|
||||||
|
pub use admin::*;
|
||||||
pub use health_check::*;
|
pub use health_check::*;
|
||||||
pub use home::*;
|
pub use home::*;
|
||||||
pub use login::*;
|
pub use login::*;
|
||||||
|
|||||||
159
src/routes/admin.rs
Normal file
159
src/routes/admin.rs
Normal file
@@ -0,0 +1,159 @@
|
|||||||
|
use crate::{
|
||||||
|
authentication::{self, Credentials, validate_credentials},
|
||||||
|
routes::error_chain_fmt,
|
||||||
|
session_state::TypedSession,
|
||||||
|
startup::AppState,
|
||||||
|
};
|
||||||
|
use axum::{
|
||||||
|
Extension, Form, Json,
|
||||||
|
extract::{Request, State},
|
||||||
|
middleware::Next,
|
||||||
|
response::{Html, IntoResponse, Redirect, Response},
|
||||||
|
};
|
||||||
|
use axum_messages::Messages;
|
||||||
|
use reqwest::StatusCode;
|
||||||
|
use secrecy::{ExposeSecret, SecretString};
|
||||||
|
use std::fmt::Write;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[derive(thiserror::Error)]
|
||||||
|
pub enum AdminError {
|
||||||
|
#[error("Something went wrong.")]
|
||||||
|
UnexpectedError(#[from] anyhow::Error),
|
||||||
|
#[error("You must be logged in to access the admin dashboard.")]
|
||||||
|
NotAuthenticated,
|
||||||
|
#[error("Updating password failed.")]
|
||||||
|
ChangePassword,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for AdminError {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
error_chain_fmt(self, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoResponse for AdminError {
|
||||||
|
fn into_response(self) -> Response {
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
struct ErrorResponse<'a> {
|
||||||
|
message: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::error!("{:?}", self);
|
||||||
|
|
||||||
|
match &self {
|
||||||
|
AdminError::UnexpectedError(_) => (
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
Json(ErrorResponse {
|
||||||
|
message: "An internal server error occured.",
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.into_response(),
|
||||||
|
AdminError::NotAuthenticated => Redirect::to("/login").into_response(),
|
||||||
|
AdminError::ChangePassword => Redirect::to("/admin/password").into_response(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn require_auth(
|
||||||
|
session: TypedSession,
|
||||||
|
mut request: Request,
|
||||||
|
next: Next,
|
||||||
|
) -> Result<Response, AdminError> {
|
||||||
|
let user_id = session
|
||||||
|
.get_user_id()
|
||||||
|
.await
|
||||||
|
.map_err(|e| AdminError::UnexpectedError(e.into()))?
|
||||||
|
.ok_or(AdminError::NotAuthenticated)?;
|
||||||
|
let username = session
|
||||||
|
.get_username()
|
||||||
|
.await
|
||||||
|
.map_err(|e| AdminError::UnexpectedError(e.into()))?
|
||||||
|
.ok_or(AdminError::UnexpectedError(anyhow::anyhow!(
|
||||||
|
"Could not find username in session."
|
||||||
|
)))?;
|
||||||
|
|
||||||
|
request
|
||||||
|
.extensions_mut()
|
||||||
|
.insert(AuthenticatedUser { user_id, username });
|
||||||
|
|
||||||
|
Ok(next.run(request).await)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct AuthenticatedUser {
|
||||||
|
user_id: Uuid,
|
||||||
|
username: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn admin_dashboard(
|
||||||
|
Extension(AuthenticatedUser { username, .. }): Extension<AuthenticatedUser>,
|
||||||
|
) -> Result<Response, AdminError> {
|
||||||
|
Ok(Html(format!(include_str!("admin/dashboard.html"), username)).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
pub struct PasswordFormData {
|
||||||
|
pub current_password: SecretString,
|
||||||
|
pub new_password: SecretString,
|
||||||
|
pub new_password_check: SecretString,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn change_password_form(messages: Messages) -> Result<Response, AdminError> {
|
||||||
|
let mut error_html = String::new();
|
||||||
|
for message in messages {
|
||||||
|
writeln!(error_html, "<p><i>{}</i></p>", message).unwrap();
|
||||||
|
}
|
||||||
|
Ok(Html(format!(
|
||||||
|
include_str!("admin/change_password_form.html"),
|
||||||
|
error_html
|
||||||
|
))
|
||||||
|
.into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn change_password(
|
||||||
|
Extension(AuthenticatedUser { user_id, username }): Extension<AuthenticatedUser>,
|
||||||
|
State(AppState {
|
||||||
|
connection_pool, ..
|
||||||
|
}): State<AppState>,
|
||||||
|
messages: Messages,
|
||||||
|
Form(form): Form<PasswordFormData>,
|
||||||
|
) -> Result<Response, AdminError> {
|
||||||
|
let credentials = Credentials {
|
||||||
|
username,
|
||||||
|
password: form.current_password,
|
||||||
|
};
|
||||||
|
if form.new_password.expose_secret() != form.new_password_check.expose_secret() {
|
||||||
|
messages.error("You entered two different passwords - the field values must match.");
|
||||||
|
Err(AdminError::ChangePassword)
|
||||||
|
} else if validate_credentials(credentials, &connection_pool)
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
messages.error("The current password is incorrect.");
|
||||||
|
Err(AdminError::ChangePassword)
|
||||||
|
} else if let Err(e) = verify_password(form.new_password.expose_secret()) {
|
||||||
|
messages.error(e);
|
||||||
|
Err(AdminError::ChangePassword)
|
||||||
|
} else {
|
||||||
|
authentication::change_password(user_id, form.new_password, &connection_pool)
|
||||||
|
.await
|
||||||
|
.map_err(|_| AdminError::ChangePassword)?;
|
||||||
|
messages.success("Your password has been changed.");
|
||||||
|
Ok(Redirect::to("/admin/password").into_response())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tracing::instrument(name = "Logging out", skip(messages, session))]
|
||||||
|
pub async fn logout(messages: Messages, session: TypedSession) -> Result<Response, AdminError> {
|
||||||
|
session.clear().await;
|
||||||
|
messages.success("You have successfully logged out.");
|
||||||
|
Ok(Redirect::to("/login").into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_password(password: &str) -> Result<(), String> {
|
||||||
|
if password.len() < 12 || password.len() > 128 {
|
||||||
|
return Err("The password must contain between 12 and 128 characters.".into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
26
src/routes/admin/change_password_form.html
Normal file
26
src/routes/admin/change_password_form.html
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width" />
|
||||||
|
<title>Change password</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<form action="/admin/password" method="post">
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
name="current_password"
|
||||||
|
placeholder="Current password"
|
||||||
|
/>
|
||||||
|
<input type="password" name="new_password" placeholder="New password" />
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
name="new_password_check"
|
||||||
|
placeholder="Confirm new password"
|
||||||
|
/>
|
||||||
|
<button type="submit">Change password</button>
|
||||||
|
</form>
|
||||||
|
{}
|
||||||
|
<p><a href="/admin/dashboard">Back</a></p>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
20
src/routes/admin/dashboard.html
Normal file
20
src/routes/admin/dashboard.html
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width" />
|
||||||
|
<title>Admin dashboard</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<p>Welcome {}!</p>
|
||||||
|
<p>Available actions:</p>
|
||||||
|
<ol>
|
||||||
|
<li><a href="/admin/password">Change password</a></li>
|
||||||
|
<li>
|
||||||
|
<form name="logoutForm" action="/admin/logout" method="post">
|
||||||
|
<input type="submit" value="Logout" />
|
||||||
|
</form>
|
||||||
|
</li>
|
||||||
|
</ol>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<meta name="viewport" content="width=device-width" />
|
<meta name="viewport" content="width=device-width" />
|
||||||
<head>
|
|
||||||
<title>Home</title>
|
<title>Home</title>
|
||||||
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<p>Welcome to our newsletter!</p>
|
<p>Welcome to our newsletter!</p>
|
||||||
|
<p><a href="/login">Login</a></p>
|
||||||
</body>
|
</body>
|
||||||
</head>
|
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
authentication::{AuthError, Credentials, validate_credentials},
|
authentication::{AuthError, Credentials, validate_credentials},
|
||||||
routes::error_chain_fmt,
|
routes::error_chain_fmt,
|
||||||
|
session_state::TypedSession,
|
||||||
startup::AppState,
|
startup::AppState,
|
||||||
};
|
};
|
||||||
use axum::{
|
use axum::{
|
||||||
@@ -63,11 +64,8 @@ pub async fn get_login(messages: Messages) -> impl IntoResponse {
|
|||||||
Html(format!(include_str!("login/login.html"), error_html))
|
Html(format!(include_str!("login/login.html"), error_html))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(
|
|
||||||
skip(connection_pool, form),
|
|
||||||
fields(username=tracing::field::Empty, user_id=tracing::field::Empty)
|
|
||||||
)]
|
|
||||||
pub async fn post_login(
|
pub async fn post_login(
|
||||||
|
session: TypedSession,
|
||||||
messages: Messages,
|
messages: Messages,
|
||||||
State(AppState {
|
State(AppState {
|
||||||
connection_pool, ..
|
connection_pool, ..
|
||||||
@@ -75,20 +73,37 @@ pub async fn post_login(
|
|||||||
Form(form): Form<LoginFormData>,
|
Form(form): Form<LoginFormData>,
|
||||||
) -> Result<Redirect, LoginError> {
|
) -> Result<Redirect, LoginError> {
|
||||||
let credentials = Credentials {
|
let credentials = Credentials {
|
||||||
username: form.username,
|
username: form.username.clone(),
|
||||||
password: form.password,
|
password: form.password,
|
||||||
};
|
};
|
||||||
tracing::Span::current().record("username", tracing::field::display(&credentials.username));
|
tracing::Span::current().record("username", tracing::field::display(&credentials.username));
|
||||||
let user_id = validate_credentials(credentials, &connection_pool)
|
match validate_credentials(credentials, &connection_pool).await {
|
||||||
.await
|
Err(e) => {
|
||||||
.map_err(|e| match e {
|
let e = match e {
|
||||||
AuthError::UnexpectedError(_) => LoginError::UnexpectedError(e.into()),
|
AuthError::UnexpectedError(_) => LoginError::UnexpectedError(e.into()),
|
||||||
AuthError::InvalidCredentials(_) => {
|
AuthError::InvalidCredentials(_) => {
|
||||||
let e = LoginError::AuthError(e.into());
|
let e = LoginError::AuthError(e.into());
|
||||||
messages.error(e.to_string());
|
messages.error(e.to_string());
|
||||||
e
|
e
|
||||||
}
|
}
|
||||||
})?;
|
};
|
||||||
|
Err(e)
|
||||||
|
}
|
||||||
|
Ok(user_id) => {
|
||||||
tracing::Span::current().record("user_id", tracing::field::display(&user_id));
|
tracing::Span::current().record("user_id", tracing::field::display(&user_id));
|
||||||
Ok(Redirect::to("/"))
|
session
|
||||||
|
.renew()
|
||||||
|
.await
|
||||||
|
.map_err(|e| LoginError::UnexpectedError(e.into()))?;
|
||||||
|
session
|
||||||
|
.insert_user_id(user_id)
|
||||||
|
.await
|
||||||
|
.map_err(|e| LoginError::UnexpectedError(e.into()))?;
|
||||||
|
session
|
||||||
|
.insert_username(form.username)
|
||||||
|
.await
|
||||||
|
.map_err(|e| LoginError::UnexpectedError(e.into()))?;
|
||||||
|
Ok(Redirect::to("/admin/dashboard"))
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<meta name="viewport" content="width=device-width" />
|
<meta name="viewport" content="width=device-width" />
|
||||||
<head>
|
|
||||||
<title>Login</title>
|
<title>Login</title>
|
||||||
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<form action="/login" method="post">
|
<form action="/login" method="post">
|
||||||
<input type="text" name="username" placeholder="Username" />
|
<input type="text" name="username" placeholder="Username" />
|
||||||
@@ -12,5 +13,4 @@
|
|||||||
</form>
|
</form>
|
||||||
{}
|
{}
|
||||||
</body>
|
</body>
|
||||||
</head>
|
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -87,7 +87,7 @@ pub async fn subscribe(
|
|||||||
base_url,
|
base_url,
|
||||||
..
|
..
|
||||||
}): State<AppState>,
|
}): State<AppState>,
|
||||||
Form(form): Form<FormData>,
|
Form(form): Form<SubscriptionFormData>,
|
||||||
) -> Result<Response, SubscribeError> {
|
) -> Result<Response, SubscribeError> {
|
||||||
let mut transaction = connection_pool
|
let mut transaction = connection_pool
|
||||||
.begin()
|
.begin()
|
||||||
@@ -195,15 +195,15 @@ Click <a href=\"{}\">here</a> to confirm your subscription.",
|
|||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub struct FormData {
|
pub struct SubscriptionFormData {
|
||||||
name: String,
|
name: String,
|
||||||
email: String,
|
email: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<FormData> for NewSubscriber {
|
impl TryFrom<SubscriptionFormData> for NewSubscriber {
|
||||||
type Error = String;
|
type Error = String;
|
||||||
|
|
||||||
fn try_from(value: FormData) -> Result<Self, Self::Error> {
|
fn try_from(value: SubscriptionFormData) -> Result<Self, Self::Error> {
|
||||||
let name = SubscriberName::parse(value.name)?;
|
let name = SubscriberName::parse(value.name)?;
|
||||||
let email = SubscriberEmail::parse(value.email)?;
|
let email = SubscriberEmail::parse(value.email)?;
|
||||||
Ok(Self { name, email })
|
Ok(Self { name, email })
|
||||||
|
|||||||
53
src/session_state.rs
Normal file
53
src/session_state.rs
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
use axum::{extract::FromRequestParts, http::request::Parts};
|
||||||
|
use std::result;
|
||||||
|
use tower_sessions::{Session, session::Error};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
pub struct TypedSession(Session);
|
||||||
|
|
||||||
|
type Result<T> = result::Result<T, Error>;
|
||||||
|
|
||||||
|
impl TypedSession {
|
||||||
|
const USER_ID_KEY: &'static str = "user_id";
|
||||||
|
const USERNAME_KEY: &'static str = "username";
|
||||||
|
|
||||||
|
pub async fn renew(&self) -> Result<()> {
|
||||||
|
self.0.cycle_id().await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn insert_user_id(&self, user_id: Uuid) -> Result<()> {
|
||||||
|
self.0.insert(Self::USER_ID_KEY, user_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_user_id(&self) -> Result<Option<Uuid>> {
|
||||||
|
self.0.get(Self::USER_ID_KEY).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn insert_username(&self, username: String) -> Result<()> {
|
||||||
|
self.0.insert(Self::USERNAME_KEY, username).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_username(&self) -> Result<Option<String>> {
|
||||||
|
self.0.get(Self::USERNAME_KEY).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn clear(&self) {
|
||||||
|
self.0.clear().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S> FromRequestParts<S> for TypedSession
|
||||||
|
where
|
||||||
|
S: Sync + Send,
|
||||||
|
{
|
||||||
|
type Rejection = <Session as FromRequestParts<S>>::Rejection;
|
||||||
|
|
||||||
|
async fn from_request_parts(
|
||||||
|
parts: &mut Parts,
|
||||||
|
state: &S,
|
||||||
|
) -> result::Result<Self, Self::Rejection> {
|
||||||
|
Session::from_request_parts(parts, state)
|
||||||
|
.await
|
||||||
|
.map(TypedSession)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,15 +3,20 @@ use axum::{
|
|||||||
Router,
|
Router,
|
||||||
extract::MatchedPath,
|
extract::MatchedPath,
|
||||||
http::Request,
|
http::Request,
|
||||||
|
middleware,
|
||||||
routing::{get, post},
|
routing::{get, post},
|
||||||
};
|
};
|
||||||
use axum_messages::MessagesManagerLayer;
|
use axum_messages::MessagesManagerLayer;
|
||||||
use secrecy::SecretString;
|
use secrecy::{ExposeSecret, SecretString};
|
||||||
use sqlx::{PgPool, postgres::PgPoolOptions};
|
use sqlx::{PgPool, postgres::PgPoolOptions};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tokio::net::TcpListener;
|
use tokio::net::TcpListener;
|
||||||
use tower_http::trace::TraceLayer;
|
use tower_http::trace::TraceLayer;
|
||||||
use tower_sessions::{MemoryStore, SessionManagerLayer};
|
use tower_sessions::SessionManagerLayer;
|
||||||
|
use tower_sessions_redis_store::{
|
||||||
|
RedisStore,
|
||||||
|
fred::prelude::{ClientLike, Config, Pool},
|
||||||
|
};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
pub struct Application {
|
pub struct Application {
|
||||||
@@ -37,11 +42,24 @@ impl Application {
|
|||||||
let connection_pool =
|
let connection_pool =
|
||||||
PgPoolOptions::new().connect_lazy_with(configuration.database.with_db());
|
PgPoolOptions::new().connect_lazy_with(configuration.database.with_db());
|
||||||
let email_client = EmailClient::new(configuration.email_client);
|
let email_client = EmailClient::new(configuration.email_client);
|
||||||
|
let pool = Pool::new(
|
||||||
|
Config::from_url(configuration.redis_uri.expose_secret())
|
||||||
|
.expect("Failed to parse Redis URL string"),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
6,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
pool.connect();
|
||||||
|
pool.wait_for_connect().await.unwrap();
|
||||||
|
let redis_store = RedisStore::new(pool);
|
||||||
let router = app(
|
let router = app(
|
||||||
connection_pool,
|
connection_pool,
|
||||||
email_client,
|
email_client,
|
||||||
configuration.application.base_url,
|
configuration.application.base_url,
|
||||||
configuration.application.hmac_secret,
|
configuration.application.hmac_secret,
|
||||||
|
redis_store,
|
||||||
);
|
);
|
||||||
Ok(Self { listener, router })
|
Ok(Self { listener, router })
|
||||||
}
|
}
|
||||||
@@ -61,6 +79,7 @@ pub fn app(
|
|||||||
email_client: EmailClient,
|
email_client: EmailClient,
|
||||||
base_url: String,
|
base_url: String,
|
||||||
hmac_secret: SecretString,
|
hmac_secret: SecretString,
|
||||||
|
redis_store: RedisStore<Pool>,
|
||||||
) -> Router {
|
) -> Router {
|
||||||
let app_state = AppState {
|
let app_state = AppState {
|
||||||
connection_pool,
|
connection_pool,
|
||||||
@@ -68,6 +87,11 @@ pub fn app(
|
|||||||
base_url,
|
base_url,
|
||||||
hmac_secret,
|
hmac_secret,
|
||||||
};
|
};
|
||||||
|
let admin_routes = Router::new()
|
||||||
|
.route("/dashboard", get(admin_dashboard))
|
||||||
|
.route("/password", get(change_password_form).post(change_password))
|
||||||
|
.route("/logout", post(logout))
|
||||||
|
.layer(middleware::from_fn(require_auth));
|
||||||
Router::new()
|
Router::new()
|
||||||
.route("/", get(home))
|
.route("/", get(home))
|
||||||
.route("/login", get(get_login).post(post_login))
|
.route("/login", get(get_login).post(post_login))
|
||||||
@@ -75,6 +99,7 @@ pub fn app(
|
|||||||
.route("/subscriptions", post(subscribe))
|
.route("/subscriptions", post(subscribe))
|
||||||
.route("/subscriptions/confirm", get(confirm))
|
.route("/subscriptions/confirm", get(confirm))
|
||||||
.route("/newsletters", post(publish_newsletter))
|
.route("/newsletters", post(publish_newsletter))
|
||||||
|
.nest("/admin", admin_routes)
|
||||||
.layer(
|
.layer(
|
||||||
TraceLayer::new_for_http().make_span_with(|request: &Request<_>| {
|
TraceLayer::new_for_http().make_span_with(|request: &Request<_>| {
|
||||||
let matched_path = request
|
let matched_path = request
|
||||||
@@ -93,6 +118,6 @@ pub fn app(
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.layer(MessagesManagerLayer)
|
.layer(MessagesManagerLayer)
|
||||||
.layer(SessionManagerLayer::new(MemoryStore::default()))
|
.layer(SessionManagerLayer::new(redis_store).with_secure(false))
|
||||||
.with_state(app_state)
|
.with_state(app_state)
|
||||||
}
|
}
|
||||||
|
|||||||
34
tests/api/admin_dashboard.rs
Normal file
34
tests/api/admin_dashboard.rs
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
use crate::helpers::{TestApp, assert_is_redirect_to};
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn you_must_be_logged_in_to_access_the_admin_dashboard() {
|
||||||
|
let app = TestApp::spawn().await;
|
||||||
|
|
||||||
|
let response = app.get_admin_dashboard().await;
|
||||||
|
|
||||||
|
assert_is_redirect_to(&response, "/login");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn logout_clears_session_state() {
|
||||||
|
let app = TestApp::spawn().await;
|
||||||
|
|
||||||
|
let login_body = serde_json::json!({
|
||||||
|
"username": &app.test_user.username,
|
||||||
|
"password": &app.test_user.password,
|
||||||
|
});
|
||||||
|
let response = app.post_login(&login_body).await;
|
||||||
|
assert_is_redirect_to(&response, "/admin/dashboard");
|
||||||
|
|
||||||
|
let html_page = app.get_admin_dashboard_html().await;
|
||||||
|
assert!(html_page.contains(&format!("Welcome {}", app.test_user.username)));
|
||||||
|
|
||||||
|
let response = app.post_logout().await;
|
||||||
|
assert_is_redirect_to(&response, "/login");
|
||||||
|
|
||||||
|
let html_page = app.get_login_html().await;
|
||||||
|
assert!(html_page.contains("You have successfully logged out"));
|
||||||
|
|
||||||
|
let response = app.get_admin_dashboard().await;
|
||||||
|
assert_is_redirect_to(&response, "/login");
|
||||||
|
}
|
||||||
115
tests/api/change_password.rs
Normal file
115
tests/api/change_password.rs
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::helpers::{TestApp, assert_is_redirect_to};
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn you_must_be_logged_in_to_see_the_change_password_form() {
|
||||||
|
let app = TestApp::spawn().await;
|
||||||
|
|
||||||
|
let response = app.get_change_password().await;
|
||||||
|
|
||||||
|
assert_is_redirect_to(&response, "/login");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn you_must_be_logged_in_to_change_your_password() {
|
||||||
|
let app = TestApp::spawn().await;
|
||||||
|
|
||||||
|
let new_password = Uuid::new_v4().to_string();
|
||||||
|
let response = app
|
||||||
|
.post_change_password(&serde_json::json!({
|
||||||
|
"current_password": Uuid::new_v4().to_string(),
|
||||||
|
"new_password": new_password,
|
||||||
|
"new_password_check": new_password,
|
||||||
|
}))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
assert_is_redirect_to(&response, "/login");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn new_password_fields_must_match() {
|
||||||
|
let app = TestApp::spawn().await;
|
||||||
|
|
||||||
|
app.post_login(&serde_json::json!({
|
||||||
|
"username": app.test_user.username,
|
||||||
|
"password": app.test_user.password,
|
||||||
|
}))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let new_password = Uuid::new_v4().to_string();
|
||||||
|
let another_new_password = Uuid::new_v4().to_string();
|
||||||
|
let response = app
|
||||||
|
.post_change_password(&serde_json::json!({
|
||||||
|
"current_password": app.test_user.password,
|
||||||
|
"new_password": new_password,
|
||||||
|
"new_password_check": another_new_password,
|
||||||
|
}))
|
||||||
|
.await;
|
||||||
|
assert_is_redirect_to(&response, "/admin/password");
|
||||||
|
|
||||||
|
let html_page = app.get_change_password_html().await;
|
||||||
|
assert!(html_page.contains("You entered two different passwords"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn current_password_is_invalid() {
|
||||||
|
let app = TestApp::spawn().await;
|
||||||
|
|
||||||
|
app.post_login(&serde_json::json!({
|
||||||
|
"username": app.test_user.username,
|
||||||
|
"password": app.test_user.password,
|
||||||
|
}))
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let new_password = Uuid::new_v4().to_string();
|
||||||
|
let response = app
|
||||||
|
.post_change_password(&serde_json::json!({
|
||||||
|
"current_password": Uuid::new_v4().to_string(),
|
||||||
|
"new_password": new_password,
|
||||||
|
"new_password_check": new_password,
|
||||||
|
}))
|
||||||
|
.await;
|
||||||
|
assert_is_redirect_to(&response, "/admin/password");
|
||||||
|
|
||||||
|
let html_page = app.get_change_password_html().await;
|
||||||
|
assert!(html_page.contains("The current password is incorrect"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn changing_password_works() {
|
||||||
|
let app = TestApp::spawn().await;
|
||||||
|
|
||||||
|
let login_body = &serde_json::json!({
|
||||||
|
"username": app.test_user.username,
|
||||||
|
"password": app.test_user.password,
|
||||||
|
});
|
||||||
|
let response = app.post_login(login_body).await;
|
||||||
|
assert_is_redirect_to(&response, "/admin/dashboard");
|
||||||
|
|
||||||
|
let new_password = Uuid::new_v4().to_string();
|
||||||
|
let response = app
|
||||||
|
.post_change_password(&serde_json::json!({
|
||||||
|
"current_password": app.test_user.password,
|
||||||
|
"new_password": new_password,
|
||||||
|
"new_password_check": new_password,
|
||||||
|
}))
|
||||||
|
.await;
|
||||||
|
assert_is_redirect_to(&response, "/admin/password");
|
||||||
|
|
||||||
|
let html_page = app.get_change_password_html().await;
|
||||||
|
assert!(html_page.contains("Your password has been changed"));
|
||||||
|
|
||||||
|
let response = app.post_logout().await;
|
||||||
|
assert_is_redirect_to(&response, "/login");
|
||||||
|
|
||||||
|
let html_page = app.get_login_html().await;
|
||||||
|
assert!(html_page.contains("You have successfully logged out"));
|
||||||
|
|
||||||
|
let login_body = &serde_json::json!({
|
||||||
|
"username": app.test_user.username,
|
||||||
|
"password": new_password,
|
||||||
|
});
|
||||||
|
let response = app.post_login(login_body).await;
|
||||||
|
assert_is_redirect_to(&response, "/admin/dashboard");
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
use argon2::{
|
use argon2::{
|
||||||
Argon2, PasswordHasher,
|
Algorithm, Argon2, Params, PasswordHasher, Version,
|
||||||
password_hash::{SaltString, rand_core::OsRng},
|
password_hash::{SaltString, rand_core::OsRng},
|
||||||
};
|
};
|
||||||
use linkify::LinkFinder;
|
use linkify::LinkFinder;
|
||||||
@@ -43,7 +43,11 @@ impl TestUser {
|
|||||||
|
|
||||||
pub async fn store(&self, connection_pool: &PgPool) {
|
pub async fn store(&self, connection_pool: &PgPool) {
|
||||||
let salt = SaltString::generate(&mut OsRng);
|
let salt = SaltString::generate(&mut OsRng);
|
||||||
let password_hash = Argon2::default()
|
let password_hash = Argon2::new(
|
||||||
|
Algorithm::Argon2id,
|
||||||
|
Version::V0x13,
|
||||||
|
Params::new(1500, 2, 1, None).unwrap(),
|
||||||
|
)
|
||||||
.hash_password(self.password.as_bytes(), &salt)
|
.hash_password(self.password.as_bytes(), &salt)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.to_string();
|
.to_string();
|
||||||
@@ -144,6 +148,30 @@ impl TestApp {
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn get_admin_dashboard(&self) -> reqwest::Response {
|
||||||
|
self.api_client
|
||||||
|
.get(format!("{}/admin/dashboard", &self.address))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.expect("Failed to execute request")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_admin_dashboard_html(&self) -> String {
|
||||||
|
self.get_admin_dashboard().await.text().await.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_change_password(&self) -> reqwest::Response {
|
||||||
|
self.api_client
|
||||||
|
.get(format!("{}/admin/password", &self.address))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.expect("Failed to execute request")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_change_password_html(&self) -> String {
|
||||||
|
self.get_change_password().await.text().await.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn post_subscriptions(&self, body: String) -> reqwest::Response {
|
pub async fn post_subscriptions(&self, body: String) -> reqwest::Response {
|
||||||
self.api_client
|
self.api_client
|
||||||
.post(format!("{}/subscriptions", self.address))
|
.post(format!("{}/subscriptions", self.address))
|
||||||
@@ -173,7 +201,27 @@ impl TestApp {
|
|||||||
.form(body)
|
.form(body)
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.expect("Failed to execute request")
|
.expect("failed to execute request")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn post_logout(&self) -> reqwest::Response {
|
||||||
|
self.api_client
|
||||||
|
.post(format!("{}/admin/logout", self.address))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.expect("failed to execute request")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn post_change_password<Body>(&self, body: &Body) -> reqwest::Response
|
||||||
|
where
|
||||||
|
Body: serde::Serialize,
|
||||||
|
{
|
||||||
|
self.api_client
|
||||||
|
.post(format!("{}/admin/password", self.address))
|
||||||
|
.form(body)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.expect("failed to execute request")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,3 +20,19 @@ async fn an_error_flash_message_is_set_on_failure() {
|
|||||||
let login_page_html = app.get_login_html().await;
|
let login_page_html = app.get_login_html().await;
|
||||||
assert!(!login_page_html.contains("Authentication failed"));
|
assert!(!login_page_html.contains("Authentication failed"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn login_redirects_to_admin_dashboard_after_login_success() {
|
||||||
|
let app = TestApp::spawn().await;
|
||||||
|
|
||||||
|
let login_body = serde_json::json!({
|
||||||
|
"username": &app.test_user.username,
|
||||||
|
"password": &app.test_user.password
|
||||||
|
});
|
||||||
|
|
||||||
|
let response = app.post_login(&login_body).await;
|
||||||
|
assert_is_redirect_to(&response, "/admin/dashboard");
|
||||||
|
|
||||||
|
let html_page = app.get_admin_dashboard_html().await;
|
||||||
|
assert!(html_page.contains(&format!("Welcome {}", app.test_user.username)));
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
mod admin_dashboard;
|
||||||
|
mod change_password;
|
||||||
mod health_check;
|
mod health_check;
|
||||||
mod helpers;
|
mod helpers;
|
||||||
mod login;
|
mod login;
|
||||||
|
|||||||
Reference in New Issue
Block a user