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