Admin dashboard and sessions

This commit is contained in:
Alphonse Paix
2025-09-01 03:08:43 +02:00
parent 3dce578ba0
commit d96a401d99
24 changed files with 810 additions and 56 deletions

View File

@@ -1,11 +1,13 @@
use crate::telemetry::spawn_blocking_with_tracing;
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 sqlx::PgPool;
use uuid::Uuid;
use crate::telemetry::spawn_blocking_with_tracing;
pub struct Credentials {
pub username: String,
pub password: SecretString,
@@ -19,6 +21,38 @@ pub enum AuthError {
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(
name = "Validate credentials",
skip(username, password, connection_pool)

View File

@@ -60,6 +60,7 @@ pub struct Settings {
pub application: ApplicationSettings,
pub database: DatabaseSettings,
pub email_client: EmailClientSettings,
pub redis_uri: SecretString,
}
#[derive(Deserialize)]

View File

@@ -3,5 +3,6 @@ pub mod configuration;
pub mod domain;
pub mod email_client;
pub mod routes;
pub mod session_state;
pub mod startup;
pub mod telemetry;

View File

@@ -1,3 +1,4 @@
mod admin;
mod health_check;
mod home;
mod login;
@@ -5,6 +6,7 @@ mod newsletters;
mod subscriptions;
mod subscriptions_confirm;
pub use admin::*;
pub use health_check::*;
pub use home::*;
pub use login::*;

159
src/routes/admin.rs Normal file
View 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(())
}

View 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>

View 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>

View File

@@ -1,11 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Home</title>
<body>
<p>Welcome to our newsletter!</p>
</body>
</head>
<body>
<p>Welcome to our newsletter!</p>
<p><a href="/login">Login</a></p>
</body>
</html>

View File

@@ -1,6 +1,7 @@
use crate::{
authentication::{AuthError, Credentials, validate_credentials},
routes::error_chain_fmt,
session_state::TypedSession,
startup::AppState,
};
use axum::{
@@ -63,11 +64,8 @@ pub async fn get_login(messages: Messages) -> impl IntoResponse {
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(
session: TypedSession,
messages: Messages,
State(AppState {
connection_pool, ..
@@ -75,20 +73,37 @@ pub async fn post_login(
Form(form): Form<LoginFormData>,
) -> Result<Redirect, LoginError> {
let credentials = Credentials {
username: form.username,
username: form.username.clone(),
password: form.password,
};
tracing::Span::current().record("username", tracing::field::display(&credentials.username));
let user_id = validate_credentials(credentials, &connection_pool)
.await
.map_err(|e| match e {
AuthError::UnexpectedError(_) => LoginError::UnexpectedError(e.into()),
AuthError::InvalidCredentials(_) => {
let e = LoginError::AuthError(e.into());
messages.error(e.to_string());
e
}
})?;
tracing::Span::current().record("user_id", tracing::field::display(&user_id));
Ok(Redirect::to("/"))
match validate_credentials(credentials, &connection_pool).await {
Err(e) => {
let e = match e {
AuthError::UnexpectedError(_) => LoginError::UnexpectedError(e.into()),
AuthError::InvalidCredentials(_) => {
let e = LoginError::AuthError(e.into());
messages.error(e.to_string());
e
}
};
Err(e)
}
Ok(user_id) => {
tracing::Span::current().record("user_id", tracing::field::display(&user_id));
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"))
}
}
}

View File

@@ -1,16 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Login</title>
<body>
<form action="/login" method="post">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<button type="submit">Login</button>
</form>
{}
</body>
</head>
<body>
<form action="/login" method="post">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<button type="submit">Login</button>
</form>
{}
</body>
</html>

View File

@@ -87,7 +87,7 @@ pub async fn subscribe(
base_url,
..
}): State<AppState>,
Form(form): Form<FormData>,
Form(form): Form<SubscriptionFormData>,
) -> Result<Response, SubscribeError> {
let mut transaction = connection_pool
.begin()
@@ -195,15 +195,15 @@ Click <a href=\"{}\">here</a> to confirm your subscription.",
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct FormData {
pub struct SubscriptionFormData {
name: String,
email: String,
}
impl TryFrom<FormData> for NewSubscriber {
impl TryFrom<SubscriptionFormData> for NewSubscriber {
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 email = SubscriberEmail::parse(value.email)?;
Ok(Self { name, email })

53
src/session_state.rs Normal file
View 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)
}
}

View File

@@ -3,15 +3,20 @@ use axum::{
Router,
extract::MatchedPath,
http::Request,
middleware,
routing::{get, post},
};
use axum_messages::MessagesManagerLayer;
use secrecy::SecretString;
use secrecy::{ExposeSecret, SecretString};
use sqlx::{PgPool, postgres::PgPoolOptions};
use std::sync::Arc;
use tokio::net::TcpListener;
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;
pub struct Application {
@@ -37,11 +42,24 @@ impl Application {
let connection_pool =
PgPoolOptions::new().connect_lazy_with(configuration.database.with_db());
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(
connection_pool,
email_client,
configuration.application.base_url,
configuration.application.hmac_secret,
redis_store,
);
Ok(Self { listener, router })
}
@@ -61,6 +79,7 @@ pub fn app(
email_client: EmailClient,
base_url: String,
hmac_secret: SecretString,
redis_store: RedisStore<Pool>,
) -> Router {
let app_state = AppState {
connection_pool,
@@ -68,6 +87,11 @@ pub fn app(
base_url,
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()
.route("/", get(home))
.route("/login", get(get_login).post(post_login))
@@ -75,6 +99,7 @@ pub fn app(
.route("/subscriptions", post(subscribe))
.route("/subscriptions/confirm", get(confirm))
.route("/newsletters", post(publish_newsletter))
.nest("/admin", admin_routes)
.layer(
TraceLayer::new_for_http().make_span_with(|request: &Request<_>| {
let matched_path = request
@@ -93,6 +118,6 @@ pub fn app(
}),
)
.layer(MessagesManagerLayer)
.layer(SessionManagerLayer::new(MemoryStore::default()))
.layer(SessionManagerLayer::new(redis_store).with_secure(false))
.with_state(app_state)
}