Authentication and form for newsletter publishing

This commit is contained in:
Alphonse Paix
2025-09-01 15:47:27 +02:00
parent d96a401d99
commit 9a184b93ac
17 changed files with 399 additions and 410 deletions

View File

@@ -1,29 +1,28 @@
use crate::{
authentication::{self, Credentials, validate_credentials},
routes::error_chain_fmt,
session_state::TypedSession,
startup::AppState,
};
pub mod change_password;
pub mod dashboard;
pub mod newsletters;
use crate::{routes::error_chain_fmt, session_state::TypedSession};
use axum::{
Extension, Form, Json,
extract::{Request, State},
middleware::Next,
response::{Html, IntoResponse, Redirect, Response},
Json,
response::{IntoResponse, Redirect, Response},
};
use axum_messages::Messages;
pub use change_password::*;
pub use dashboard::*;
pub use newsletters::*;
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.")]
#[error("Trying to access admin dashboard without authentication.")]
NotAuthenticated,
#[error("Updating password failed.")]
ChangePassword,
#[error("Could not publish newsletter.")]
Publish,
}
impl std::fmt::Debug for AdminError {
@@ -51,109 +50,14 @@ impl IntoResponse for AdminError {
.into_response(),
AdminError::NotAuthenticated => Redirect::to("/login").into_response(),
AdminError::ChangePassword => Redirect::to("/admin/password").into_response(),
AdminError::Publish => Redirect::to("/admin/newsletters").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,72 @@
use crate::{
authentication::{self, AuthenticatedUser, Credentials, validate_credentials},
routes::AdminError,
startup::AppState,
};
use axum::{
Extension, Form,
extract::State,
response::{Html, IntoResponse, Redirect, Response},
};
use axum_messages::Messages;
use secrecy::{ExposeSecret, SecretString};
use std::fmt::Write;
#[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!("html/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())
}
}
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,11 @@
use crate::authentication::AuthenticatedUser;
use axum::{
Extension,
response::{Html, IntoResponse, Response},
};
pub async fn admin_dashboard(
Extension(AuthenticatedUser { username, .. }): Extension<AuthenticatedUser>,
) -> Response {
Html(format!(include_str!("html/dashboard.html"), username)).into_response()
}

View File

@@ -10,6 +10,7 @@
<p>Available actions:</p>
<ol>
<li><a href="/admin/password">Change password</a></li>
<li><a href="/admin/newsletters">Send a newsletter</a></li>
<li>
<form name="logoutForm" action="/admin/logout" method="post">
<input type="submit" value="Logout" />

View File

@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Send a newsletter</title>
</head>
<body>
<form action="/admin/newsletters" method="post">
<input type="text" name="title" placeholder="Subject" />
<input type="text" name="html" placeholder="Content (HTML)" />
<input type="text" name="text" placeholder="Content (text)" />
<button type="submit">Send</button>
</form>
{}
<p><a href="/admin/dashboard">Back</a></p>
</body>
</html>

View File

@@ -0,0 +1,108 @@
use crate::{domain::SubscriberEmail, routes::AdminError, startup::AppState};
use anyhow::Context;
use axum::{
Form,
extract::State,
response::{Html, IntoResponse, Redirect, Response},
};
use axum_messages::Messages;
use sqlx::PgPool;
use std::fmt::Write;
#[derive(serde::Deserialize)]
pub struct BodyData {
title: String,
html: String,
text: String,
}
pub async fn publish_form(messages: Messages) -> Response {
let mut error_html = String::new();
for message in messages {
writeln!(error_html, "<p><i>{}</i></p>", message).unwrap();
}
Html(format!(
include_str!("html/send_newsletter_form.html"),
error_html
))
.into_response()
}
#[tracing::instrument(
name = "Publishing a newsletter",
skip(connection_pool, email_client, form)
)]
pub async fn publish(
State(AppState {
connection_pool,
email_client,
..
}): State<AppState>,
messages: Messages,
Form(form): Form<BodyData>,
) -> Result<Response, AdminError> {
if let Err(e) = validate_form(&form) {
messages.error(e);
return Err(AdminError::Publish);
}
let subscribers = get_confirmed_subscribers(&connection_pool).await?;
for subscriber in subscribers {
match subscriber {
Ok(ConfirmedSubscriber { name, email }) => {
let title = format!("{}, we have news for you! {}", name, form.title);
email_client
.send_email(&email, &title, &form.html, &form.text)
.await
.with_context(|| {
format!("Failed to send newsletter issue to {}", email.as_ref())
})?;
}
Err(e) => {
tracing::warn!(
"Skipping a confirmed subscriber. Their stored contact details are invalid: {}",
e
)
}
}
}
messages.success(format!(
"The newsletter issue '{}' has been published!",
form.title,
));
Ok(Redirect::to("/admin/newsletters").into_response())
}
fn validate_form(form: &BodyData) -> Result<(), &'static str> {
if form.title.is_empty() {
return Err("The title was empty");
}
if form.html.is_empty() || form.text.is_empty() {
return Err("The content was empty.");
}
Ok(())
}
struct ConfirmedSubscriber {
name: String,
email: SubscriberEmail,
}
#[tracing::instrument(name = "Get confirmed subscribers", skip(connection_pool))]
async fn get_confirmed_subscribers(
connection_pool: &PgPool,
) -> Result<Vec<Result<ConfirmedSubscriber, anyhow::Error>>, anyhow::Error> {
let rows = sqlx::query!("SELECT name, email FROM subscriptions WHERE status = 'confirmed'")
.fetch_all(connection_pool)
.await?;
let confirmed_subscribers = rows
.into_iter()
.map(|r| match SubscriberEmail::parse(r.email) {
Ok(email) => Ok(ConfirmedSubscriber {
name: r.name,
email,
}),
Err(e) => Err(anyhow::anyhow!(e)),
})
.collect();
Ok(confirmed_subscribers)
}

View File

@@ -86,6 +86,7 @@ pub async fn post_login(
messages.error(e.to_string());
e
}
AuthError::NotAuthenticated => unreachable!(),
};
Err(e)
}

View File

@@ -1,176 +0,0 @@
use crate::{
authentication::{AuthError, Credentials, validate_credentials},
domain::SubscriberEmail,
routes::error_chain_fmt,
startup::AppState,
};
use anyhow::Context;
use axum::{
Json,
extract::State,
http::{HeaderMap, HeaderValue},
response::{IntoResponse, Response},
};
use base64::Engine;
use reqwest::{StatusCode, header};
use secrecy::SecretString;
use sqlx::PgPool;
#[derive(thiserror::Error)]
pub enum PublishError {
#[error(transparent)]
UnexpectedError(#[from] anyhow::Error),
#[error("Authentication failed.")]
AuthError(#[source] anyhow::Error),
}
impl std::fmt::Debug for PublishError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
error_chain_fmt(self, f)
}
}
impl IntoResponse for PublishError {
fn into_response(self) -> Response {
#[derive(serde::Serialize)]
struct ErrorResponse<'a> {
message: &'a str,
}
tracing::error!("{:?}", self);
let mut authenticate_header_value = None;
let status = match self {
PublishError::UnexpectedError(_) => StatusCode::INTERNAL_SERVER_ERROR,
PublishError::AuthError(_) => {
authenticate_header_value =
Some(HeaderValue::from_str(r#"Basic realm="publish""#).unwrap());
StatusCode::UNAUTHORIZED
}
};
let message = "An internal server error occured.";
let mut response = (status, Json(ErrorResponse { message })).into_response();
if let Some(header_value) = authenticate_header_value {
response
.headers_mut()
.insert(header::WWW_AUTHENTICATE, header_value);
}
response
}
}
#[derive(serde::Deserialize)]
pub struct BodyData {
title: String,
content: Content,
}
#[derive(serde::Deserialize)]
pub struct Content {
html: String,
text: String,
}
#[tracing::instrument(
name = "Publishing a newsletter",
skip(headers, connection_pool, email_client, body),
fields(username=tracing::field::Empty, user_id=tracing::field::Empty)
)]
pub async fn publish_newsletter(
headers: HeaderMap,
State(AppState {
connection_pool,
email_client,
..
}): State<AppState>,
body: Json<BodyData>,
) -> Result<Response, PublishError> {
let credentials = basic_authentication(&headers).map_err(PublishError::AuthError)?;
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(_) => PublishError::UnexpectedError(e.into()),
AuthError::InvalidCredentials(_) => PublishError::AuthError(e.into()),
})?;
tracing::Span::current().record("user_id", tracing::field::display(&user_id));
let subscribers = get_confirmed_subscribers(&connection_pool).await?;
for subscriber in subscribers {
match subscriber {
Ok(ConfirmedSubscriber { email, .. }) => {
email_client
.send_email(&email, &body.title, &body.content.html, &body.content.text)
.await
.with_context(|| {
format!("Failed to send newsletter issue to {}", email.as_ref())
})?;
}
Err(e) => {
tracing::warn!(
"Skipping a confirmed subscriber. Their stored contact details are invalid: {}",
e
)
}
}
}
Ok(StatusCode::OK.into_response())
}
fn basic_authentication(headers: &HeaderMap) -> Result<Credentials, anyhow::Error> {
let header_value = headers
.get("Authorization")
.context("The 'Authorization' header was missing.")?
.to_str()
.context("The 'Authorization' header was not a valid UTF8 string.")?;
let base64encoded_segment = header_value
.strip_prefix("Basic ")
.context("The authorization scheme was not 'Basic'.")?;
let decoded_bytes = base64::engine::general_purpose::STANDARD
.decode(base64encoded_segment)
.context("Failed to base64-decode 'Basic' credentials.")?;
let decoded_credentials = String::from_utf8(decoded_bytes)
.context("The decoded credential string is not valid UTF-8.")?;
let mut credentials = decoded_credentials.splitn(2, ':');
let username = credentials
.next()
.context("A username must be provided in 'Basic' auth.")?
.to_string();
let password = credentials
.next()
.context("A password must be provided in 'Basic' auth.")?
.to_string();
Ok(Credentials {
username,
password: SecretString::from(password),
})
}
#[allow(dead_code)]
struct ConfirmedSubscriber {
name: String,
email: SubscriberEmail,
}
#[tracing::instrument(name = "Get confirmed subscribers", skip(connection_pool))]
async fn get_confirmed_subscribers(
connection_pool: &PgPool,
) -> Result<Vec<Result<ConfirmedSubscriber, anyhow::Error>>, anyhow::Error> {
let rows = sqlx::query!("SELECT name, email FROM subscriptions WHERE status = 'confirmed'")
.fetch_all(connection_pool)
.await?;
let confirmed_subscribers = rows
.into_iter()
.map(|r| match SubscriberEmail::parse(r.email) {
Ok(email) => Ok(ConfirmedSubscriber {
name: r.name,
email,
}),
Err(e) => Err(anyhow::anyhow!(e)),
})
.collect();
Ok(confirmed_subscribers)
}