Authentication and form for newsletter publishing
This commit is contained in:
@@ -1,9 +1,12 @@
|
|||||||
use crate::telemetry::spawn_blocking_with_tracing;
|
use crate::{
|
||||||
|
routes::AdminError, session_state::TypedSession, telemetry::spawn_blocking_with_tracing,
|
||||||
|
};
|
||||||
use anyhow::Context;
|
use anyhow::Context;
|
||||||
use argon2::{
|
use argon2::{
|
||||||
Algorithm, Argon2, Params, PasswordHash, PasswordHasher, PasswordVerifier, Version,
|
Algorithm, Argon2, Params, PasswordHash, PasswordHasher, PasswordVerifier, Version,
|
||||||
password_hash::{SaltString, rand_core::OsRng},
|
password_hash::{SaltString, rand_core::OsRng},
|
||||||
};
|
};
|
||||||
|
use axum::{extract::Request, middleware::Next, response::Response};
|
||||||
use secrecy::{ExposeSecret, SecretString};
|
use secrecy::{ExposeSecret, SecretString};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
@@ -19,6 +22,8 @@ pub enum AuthError {
|
|||||||
UnexpectedError(#[from] anyhow::Error),
|
UnexpectedError(#[from] anyhow::Error),
|
||||||
#[error("Invalid credentials.")]
|
#[error("Invalid credentials.")]
|
||||||
InvalidCredentials(#[source] anyhow::Error),
|
InvalidCredentials(#[source] anyhow::Error),
|
||||||
|
#[error("Not authenticated.")]
|
||||||
|
NotAuthenticated,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(name = "Change password", skip(password, connection_pool))]
|
#[tracing::instrument(name = "Change password", skip(password, connection_pool))]
|
||||||
@@ -125,3 +130,34 @@ async fn get_stored_credentials(
|
|||||||
.map(|row| (row.user_id, SecretString::from(row.password_hash)));
|
.map(|row| (row.user_id, SecretString::from(row.password_hash)));
|
||||||
Ok(row)
|
Ok(row)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
pub user_id: Uuid,
|
||||||
|
pub username: String,
|
||||||
|
}
|
||||||
|
|||||||
@@ -69,7 +69,6 @@ pub struct ApplicationSettings {
|
|||||||
pub port: u16,
|
pub port: u16,
|
||||||
pub host: String,
|
pub host: String,
|
||||||
pub base_url: String,
|
pub base_url: String,
|
||||||
pub hmac_secret: SecretString,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ mod admin;
|
|||||||
mod health_check;
|
mod health_check;
|
||||||
mod home;
|
mod home;
|
||||||
mod login;
|
mod login;
|
||||||
mod newsletters;
|
|
||||||
mod subscriptions;
|
mod subscriptions;
|
||||||
mod subscriptions_confirm;
|
mod subscriptions_confirm;
|
||||||
|
|
||||||
@@ -10,6 +9,5 @@ pub use admin::*;
|
|||||||
pub use health_check::*;
|
pub use health_check::*;
|
||||||
pub use home::*;
|
pub use home::*;
|
||||||
pub use login::*;
|
pub use login::*;
|
||||||
pub use newsletters::*;
|
|
||||||
pub use subscriptions::*;
|
pub use subscriptions::*;
|
||||||
pub use subscriptions_confirm::*;
|
pub use subscriptions_confirm::*;
|
||||||
|
|||||||
@@ -1,29 +1,28 @@
|
|||||||
use crate::{
|
pub mod change_password;
|
||||||
authentication::{self, Credentials, validate_credentials},
|
pub mod dashboard;
|
||||||
routes::error_chain_fmt,
|
pub mod newsletters;
|
||||||
session_state::TypedSession,
|
|
||||||
startup::AppState,
|
use crate::{routes::error_chain_fmt, session_state::TypedSession};
|
||||||
};
|
|
||||||
use axum::{
|
use axum::{
|
||||||
Extension, Form, Json,
|
Json,
|
||||||
extract::{Request, State},
|
response::{IntoResponse, Redirect, Response},
|
||||||
middleware::Next,
|
|
||||||
response::{Html, IntoResponse, Redirect, Response},
|
|
||||||
};
|
};
|
||||||
use axum_messages::Messages;
|
use axum_messages::Messages;
|
||||||
|
pub use change_password::*;
|
||||||
|
pub use dashboard::*;
|
||||||
|
pub use newsletters::*;
|
||||||
use reqwest::StatusCode;
|
use reqwest::StatusCode;
|
||||||
use secrecy::{ExposeSecret, SecretString};
|
|
||||||
use std::fmt::Write;
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
#[derive(thiserror::Error)]
|
#[derive(thiserror::Error)]
|
||||||
pub enum AdminError {
|
pub enum AdminError {
|
||||||
#[error("Something went wrong.")]
|
#[error("Something went wrong.")]
|
||||||
UnexpectedError(#[from] anyhow::Error),
|
UnexpectedError(#[from] anyhow::Error),
|
||||||
#[error("You must be logged in to access the admin dashboard.")]
|
#[error("Trying to access admin dashboard without authentication.")]
|
||||||
NotAuthenticated,
|
NotAuthenticated,
|
||||||
#[error("Updating password failed.")]
|
#[error("Updating password failed.")]
|
||||||
ChangePassword,
|
ChangePassword,
|
||||||
|
#[error("Could not publish newsletter.")]
|
||||||
|
Publish,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Debug for AdminError {
|
impl std::fmt::Debug for AdminError {
|
||||||
@@ -51,109 +50,14 @@ impl IntoResponse for AdminError {
|
|||||||
.into_response(),
|
.into_response(),
|
||||||
AdminError::NotAuthenticated => Redirect::to("/login").into_response(),
|
AdminError::NotAuthenticated => Redirect::to("/login").into_response(),
|
||||||
AdminError::ChangePassword => Redirect::to("/admin/password").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))]
|
#[tracing::instrument(name = "Logging out", skip(messages, session))]
|
||||||
pub async fn logout(messages: Messages, session: TypedSession) -> Result<Response, AdminError> {
|
pub async fn logout(messages: Messages, session: TypedSession) -> Result<Response, AdminError> {
|
||||||
session.clear().await;
|
session.clear().await;
|
||||||
messages.success("You have successfully logged out.");
|
messages.success("You have successfully logged out.");
|
||||||
Ok(Redirect::to("/login").into_response())
|
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(())
|
|
||||||
}
|
|
||||||
|
|||||||
72
src/routes/admin/change_password.rs
Normal file
72
src/routes/admin/change_password.rs
Normal 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(())
|
||||||
|
}
|
||||||
11
src/routes/admin/dashboard.rs
Normal file
11
src/routes/admin/dashboard.rs
Normal 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()
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@
|
|||||||
<p>Available actions:</p>
|
<p>Available actions:</p>
|
||||||
<ol>
|
<ol>
|
||||||
<li><a href="/admin/password">Change password</a></li>
|
<li><a href="/admin/password">Change password</a></li>
|
||||||
|
<li><a href="/admin/newsletters">Send a newsletter</a></li>
|
||||||
<li>
|
<li>
|
||||||
<form name="logoutForm" action="/admin/logout" method="post">
|
<form name="logoutForm" action="/admin/logout" method="post">
|
||||||
<input type="submit" value="Logout" />
|
<input type="submit" value="Logout" />
|
||||||
18
src/routes/admin/html/send_newsletter_form.html
Normal file
18
src/routes/admin/html/send_newsletter_form.html
Normal 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>
|
||||||
108
src/routes/admin/newsletters.rs
Normal file
108
src/routes/admin/newsletters.rs
Normal 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)
|
||||||
|
}
|
||||||
@@ -86,6 +86,7 @@ pub async fn post_login(
|
|||||||
messages.error(e.to_string());
|
messages.error(e.to_string());
|
||||||
e
|
e
|
||||||
}
|
}
|
||||||
|
AuthError::NotAuthenticated => unreachable!(),
|
||||||
};
|
};
|
||||||
Err(e)
|
Err(e)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
use crate::{configuration::Settings, email_client::EmailClient, routes::*};
|
use crate::{
|
||||||
|
authentication::require_auth, configuration::Settings, email_client::EmailClient, routes::*,
|
||||||
|
};
|
||||||
use axum::{
|
use axum::{
|
||||||
Router,
|
Router,
|
||||||
extract::MatchedPath,
|
extract::MatchedPath,
|
||||||
@@ -7,7 +9,7 @@ use axum::{
|
|||||||
routing::{get, post},
|
routing::{get, post},
|
||||||
};
|
};
|
||||||
use axum_messages::MessagesManagerLayer;
|
use axum_messages::MessagesManagerLayer;
|
||||||
use secrecy::{ExposeSecret, SecretString};
|
use secrecy::ExposeSecret;
|
||||||
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;
|
||||||
@@ -29,7 +31,6 @@ pub struct AppState {
|
|||||||
pub connection_pool: PgPool,
|
pub connection_pool: PgPool,
|
||||||
pub email_client: Arc<EmailClient>,
|
pub email_client: Arc<EmailClient>,
|
||||||
pub base_url: String,
|
pub base_url: String,
|
||||||
pub hmac_secret: SecretString,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Application {
|
impl Application {
|
||||||
@@ -58,7 +59,6 @@ impl Application {
|
|||||||
connection_pool,
|
connection_pool,
|
||||||
email_client,
|
email_client,
|
||||||
configuration.application.base_url,
|
configuration.application.base_url,
|
||||||
configuration.application.hmac_secret,
|
|
||||||
redis_store,
|
redis_store,
|
||||||
);
|
);
|
||||||
Ok(Self { listener, router })
|
Ok(Self { listener, router })
|
||||||
@@ -78,18 +78,17 @@ pub fn app(
|
|||||||
connection_pool: PgPool,
|
connection_pool: PgPool,
|
||||||
email_client: EmailClient,
|
email_client: EmailClient,
|
||||||
base_url: String,
|
base_url: String,
|
||||||
hmac_secret: SecretString,
|
|
||||||
redis_store: RedisStore<Pool>,
|
redis_store: RedisStore<Pool>,
|
||||||
) -> Router {
|
) -> Router {
|
||||||
let app_state = AppState {
|
let app_state = AppState {
|
||||||
connection_pool,
|
connection_pool,
|
||||||
email_client: Arc::new(email_client),
|
email_client: Arc::new(email_client),
|
||||||
base_url,
|
base_url,
|
||||||
hmac_secret,
|
|
||||||
};
|
};
|
||||||
let admin_routes = Router::new()
|
let admin_routes = Router::new()
|
||||||
.route("/dashboard", get(admin_dashboard))
|
.route("/dashboard", get(admin_dashboard))
|
||||||
.route("/password", get(change_password_form).post(change_password))
|
.route("/password", get(change_password_form).post(change_password))
|
||||||
|
.route("/newsletters", get(publish_form).post(publish))
|
||||||
.route("/logout", post(logout))
|
.route("/logout", post(logout))
|
||||||
.layer(middleware::from_fn(require_auth));
|
.layer(middleware::from_fn(require_auth));
|
||||||
Router::new()
|
Router::new()
|
||||||
@@ -98,7 +97,6 @@ pub fn app(
|
|||||||
.route("/health_check", get(health_check))
|
.route("/health_check", get(health_check))
|
||||||
.route("/subscriptions", post(subscribe))
|
.route("/subscriptions", post(subscribe))
|
||||||
.route("/subscriptions/confirm", get(confirm))
|
.route("/subscriptions/confirm", get(confirm))
|
||||||
.route("/newsletters", post(publish_newsletter))
|
|
||||||
.nest("/admin", admin_routes)
|
.nest("/admin", admin_routes)
|
||||||
.layer(
|
.layer(
|
||||||
TraceLayer::new_for_http().make_span_with(|request: &Request<_>| {
|
TraceLayer::new_for_http().make_span_with(|request: &Request<_>| {
|
||||||
|
|||||||
@@ -182,11 +182,25 @@ impl TestApp {
|
|||||||
.expect("Failed to execute request")
|
.expect("Failed to execute request")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn post_newsletters(&self, body: serde_json::Value) -> reqwest::Response {
|
pub async fn get_newsletter_form(&self) -> reqwest::Response {
|
||||||
reqwest::Client::new()
|
self.api_client
|
||||||
.post(format!("{}/newsletters", self.address))
|
.get(format!("{}/admin/password", &self.address))
|
||||||
.json(&body)
|
.send()
|
||||||
.basic_auth(&self.test_user.username, Some(&self.test_user.password))
|
.await
|
||||||
|
.expect("Failed to execute request")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_newsletter_form_html(&self) -> String {
|
||||||
|
self.get_newsletter_form().await.text().await.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn post_newsletters<Body>(&self, body: &Body) -> reqwest::Response
|
||||||
|
where
|
||||||
|
Body: serde::Serialize,
|
||||||
|
{
|
||||||
|
self.api_client
|
||||||
|
.post(format!("{}/admin/newsletters", self.address))
|
||||||
|
.form(body)
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.expect("Failed to execute request")
|
.expect("Failed to execute request")
|
||||||
|
|||||||
@@ -16,9 +16,6 @@ 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"));
|
||||||
|
|
||||||
let login_page_html = app.get_login_html().await;
|
|
||||||
assert!(!login_page_html.contains("Authentication failed"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
use crate::helpers::{ConfirmationLinks, TestApp};
|
use crate::helpers::{ConfirmationLinks, TestApp, assert_is_redirect_to};
|
||||||
use uuid::Uuid;
|
|
||||||
use wiremock::{
|
use wiremock::{
|
||||||
Mock, ResponseTemplate,
|
Mock, ResponseTemplate,
|
||||||
matchers::{any, method, path},
|
matchers::{any, method, path},
|
||||||
@@ -10,97 +9,43 @@ async fn newsletters_are_not_delivered_to_unconfirmed_subscribers() {
|
|||||||
let app = TestApp::spawn().await;
|
let app = TestApp::spawn().await;
|
||||||
create_unconfirmed_subscriber(&app).await;
|
create_unconfirmed_subscriber(&app).await;
|
||||||
|
|
||||||
|
let login_body = serde_json::json!({
|
||||||
|
"username": app.test_user.username,
|
||||||
|
"password": app.test_user.password
|
||||||
|
});
|
||||||
|
app.post_login(&login_body).await;
|
||||||
|
|
||||||
Mock::given(any())
|
Mock::given(any())
|
||||||
.respond_with(ResponseTemplate::new(200))
|
.respond_with(ResponseTemplate::new(200))
|
||||||
.expect(0)
|
.expect(0)
|
||||||
.mount(&app.email_server)
|
.mount(&app.email_server)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
let newsletter_request_body = serde_json::json!({"title": "Newsletter title", "content": { "text": "Newsletter body as plain text", "html": "<p>Newsletter body as HTML</p>"}});
|
let newsletter_request_body = serde_json::json!({
|
||||||
let response = app.post_newsletters(newsletter_request_body).await;
|
"title": "Newsletter title",
|
||||||
|
"text": "Newsletter body as plain text",
|
||||||
assert_eq!(response.status().as_u16(), 200);
|
"html": "<p>Newsletter body as HTML</p>"
|
||||||
|
});
|
||||||
|
app.post_newsletters(&newsletter_request_body).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn request_missing_authorization_are_rejected() {
|
async fn requests_without_authentication_are_redirected() {
|
||||||
let app = TestApp::spawn().await;
|
let app = TestApp::spawn().await;
|
||||||
|
|
||||||
|
Mock::given(any())
|
||||||
|
.respond_with(ResponseTemplate::new(200))
|
||||||
|
.expect(0)
|
||||||
|
.mount(&app.email_server)
|
||||||
|
.await;
|
||||||
|
|
||||||
let newsletter_request_body = serde_json::json!({
|
let newsletter_request_body = serde_json::json!({
|
||||||
"title": "Newsletter title",
|
"title": "Newsletter title",
|
||||||
"content": {
|
"text": "Newsletter body as plain text",
|
||||||
"text": "Newsletter body as plain text",
|
"html": "<p>Newsletter body as HTML</p>"
|
||||||
"html": "<p>Newsletter body as HTML</p>"
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
let response = reqwest::Client::new()
|
let response = app.post_newsletters(&newsletter_request_body).await;
|
||||||
.post(format!("{}/newsletters", &app.address))
|
assert_is_redirect_to(&response, "/login");
|
||||||
.json(&newsletter_request_body)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.expect("Failed to execute request");
|
|
||||||
|
|
||||||
assert_eq!(response.status().as_u16(), 401);
|
|
||||||
assert_eq!(
|
|
||||||
response.headers()["WWW-Authenticate"],
|
|
||||||
r#"Basic realm="publish""#
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn non_existing_user_is_rejected() {
|
|
||||||
let app = TestApp::spawn().await;
|
|
||||||
|
|
||||||
let newsletter_request_body = serde_json::json!({
|
|
||||||
"title": "Newsletter title",
|
|
||||||
"content": {
|
|
||||||
"text": "Newsletter body as plain text",
|
|
||||||
"html": "<p>Newsletter body as HTML</p>"
|
|
||||||
}
|
|
||||||
});
|
|
||||||
let username = Uuid::new_v4().to_string();
|
|
||||||
let password = Uuid::new_v4().to_string();
|
|
||||||
let response = reqwest::Client::new()
|
|
||||||
.post(format!("{}/newsletters", &app.address))
|
|
||||||
.json(&newsletter_request_body)
|
|
||||||
.basic_auth(username, Some(password))
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.expect("Failed to execute request");
|
|
||||||
|
|
||||||
assert_eq!(response.status().as_u16(), 401);
|
|
||||||
assert_eq!(
|
|
||||||
response.headers()["WWW-Authenticate"],
|
|
||||||
r#"Basic realm="publish""#
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn invalid_password_is_rejected() {
|
|
||||||
let app = TestApp::spawn().await;
|
|
||||||
|
|
||||||
let newsletter_request_body = serde_json::json!({
|
|
||||||
"title": "Newsletter title",
|
|
||||||
"content": {
|
|
||||||
"text": "Newsletter body as plain text",
|
|
||||||
"html": "<p>Newsletter body as HTML</p>"
|
|
||||||
}
|
|
||||||
});
|
|
||||||
let username = app.test_user.username;
|
|
||||||
let password = Uuid::new_v4().to_string();
|
|
||||||
let response = reqwest::Client::new()
|
|
||||||
.post(format!("{}/newsletters", &app.address))
|
|
||||||
.json(&newsletter_request_body)
|
|
||||||
.basic_auth(username, Some(password))
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.expect("Failed to execute request");
|
|
||||||
|
|
||||||
assert_eq!(response.status().as_u16(), 401);
|
|
||||||
assert_eq!(
|
|
||||||
response.headers()["WWW-Authenticate"],
|
|
||||||
r#"Basic realm="publish""#
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -108,56 +53,116 @@ async fn newsletters_are_delivered_to_confirmed_subscribers() {
|
|||||||
let app = TestApp::spawn().await;
|
let app = TestApp::spawn().await;
|
||||||
create_confirmed_subscriber(&app).await;
|
create_confirmed_subscriber(&app).await;
|
||||||
|
|
||||||
|
let login_body = serde_json::json!({
|
||||||
|
"username": app.test_user.username,
|
||||||
|
"password": app.test_user.password
|
||||||
|
});
|
||||||
|
app.post_login(&login_body).await;
|
||||||
|
|
||||||
Mock::given(any())
|
Mock::given(any())
|
||||||
.respond_with(ResponseTemplate::new(200))
|
.respond_with(ResponseTemplate::new(200))
|
||||||
.expect(1)
|
.expect(1)
|
||||||
.mount(&app.email_server)
|
.mount(&app.email_server)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
|
let newsletter_title = "Newsletter title";
|
||||||
let newsletter_request_body = serde_json::json!({
|
let newsletter_request_body = serde_json::json!({
|
||||||
"title": "Newsletter title",
|
"title": newsletter_title,
|
||||||
"content": {
|
"text": "Newsletter body as plain text",
|
||||||
"text": "Newsletter body as plain text",
|
"html": "<p>Newsletter body as HTML</p>"
|
||||||
"html": "<p>Newsletter body as HTML</p>"
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
let response = app.post_newsletters(newsletter_request_body).await;
|
|
||||||
|
|
||||||
assert_eq!(response.status().as_u16(), 200);
|
let response = app.post_newsletters(&newsletter_request_body).await;
|
||||||
|
assert_is_redirect_to(&response, "/admin/newsletters");
|
||||||
|
|
||||||
|
let html_page = app.get_newsletter_form_html().await;
|
||||||
|
assert!(html_page.contains(&format!(
|
||||||
|
"The newsletter issue '{}' has been published",
|
||||||
|
newsletter_title
|
||||||
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn newsletters_returns_422_for_invalid_data() {
|
async fn form_shows_error_for_invalid_data() {
|
||||||
let app = TestApp::spawn().await;
|
let app = TestApp::spawn().await;
|
||||||
|
|
||||||
|
let login_body = serde_json::json!({
|
||||||
|
"username": app.test_user.username,
|
||||||
|
"password": app.test_user.password
|
||||||
|
});
|
||||||
|
app.post_login(&login_body).await;
|
||||||
|
|
||||||
|
Mock::given(any())
|
||||||
|
.respond_with(ResponseTemplate::new(200))
|
||||||
|
.expect(0)
|
||||||
|
.mount(&app.email_server)
|
||||||
|
.await;
|
||||||
|
|
||||||
let test_cases = [
|
let test_cases = [
|
||||||
(
|
(
|
||||||
serde_json::json!({
|
serde_json::json!({
|
||||||
"content": {
|
"title": "",
|
||||||
"text": "Newsletter body as plain text",
|
"text": "Newsletter body as plain text",
|
||||||
"html": "<p>Newsletter body as HTML</p>"
|
"html": "<p>Newsletter body as HTML</p>"
|
||||||
}
|
}),
|
||||||
}),
|
"The title was empty",
|
||||||
"missing the title",
|
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
serde_json::json!({ "title": "Newsletter" }),
|
serde_json::json!({ "title": "Newsletter", "text": "", "html": "" }),
|
||||||
"missing the title",
|
"The content was empty",
|
||||||
),
|
),
|
||||||
];
|
];
|
||||||
|
|
||||||
for (invalid_body, error_message) in test_cases {
|
for (invalid_body, error_message) in test_cases {
|
||||||
let response = app.post_newsletters(invalid_body).await;
|
app.post_newsletters(&invalid_body).await;
|
||||||
|
let html_page = app.get_newsletter_form_html().await;
|
||||||
assert_eq!(
|
assert!(html_page.contains(error_message));
|
||||||
response.status().as_u16(),
|
|
||||||
422,
|
|
||||||
"The API did not fail with 422 Unprocessable Entity when the payload was {}.",
|
|
||||||
error_message
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn newsletter_creation_is_idempotent() {
|
||||||
|
let app = TestApp::spawn().await;
|
||||||
|
create_confirmed_subscriber(&app).await;
|
||||||
|
|
||||||
|
let login_body = serde_json::json!({
|
||||||
|
"username": app.test_user.username,
|
||||||
|
"password": app.test_user.password
|
||||||
|
});
|
||||||
|
app.post_login(&login_body).await;
|
||||||
|
|
||||||
|
Mock::given(any())
|
||||||
|
.respond_with(ResponseTemplate::new(200))
|
||||||
|
.expect(1)
|
||||||
|
.mount(&app.email_server)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let newsletter_title = "Newsletter title";
|
||||||
|
let newsletter_request_body = serde_json::json!({
|
||||||
|
"title": newsletter_title,
|
||||||
|
"text": "Newsletter body as plain text",
|
||||||
|
"html": "<p>Newsletter body as HTML</p>"
|
||||||
|
});
|
||||||
|
|
||||||
|
let response = app.post_newsletters(&newsletter_request_body).await;
|
||||||
|
assert_is_redirect_to(&response, "/admin/newsletters");
|
||||||
|
|
||||||
|
let html_page = app.get_newsletter_form_html().await;
|
||||||
|
assert!(html_page.contains(&format!(
|
||||||
|
"The newsletter issue '{}' has been published",
|
||||||
|
newsletter_title
|
||||||
|
)));
|
||||||
|
|
||||||
|
let response = app.post_newsletters(&newsletter_request_body).await;
|
||||||
|
assert_is_redirect_to(&response, "/admin/newsletters");
|
||||||
|
|
||||||
|
let html_page = app.get_newsletter_form_html().await;
|
||||||
|
assert!(html_page.contains(&format!(
|
||||||
|
"The newsletter issue '{}' has been published",
|
||||||
|
newsletter_title
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
async fn create_unconfirmed_subscriber(app: &TestApp) -> ConfirmationLinks {
|
async fn create_unconfirmed_subscriber(app: &TestApp) -> ConfirmationLinks {
|
||||||
let body = "name=Alphonse&email=alphonse.paix%40outlook.com";
|
let body = "name=Alphonse&email=alphonse.paix%40outlook.com";
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user