Authentication and form for newsletter publishing

This commit is contained in:
Alphonse Paix
2025-09-01 15:47:27 +02:00
parent 6f6e6ab017
commit d47fba5cc9
16 changed files with 394 additions and 408 deletions

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)
}