Register form and confirmation messages

This commit is contained in:
Alphonse Paix
2025-09-04 23:39:53 +02:00
parent f8dee295cd
commit a4104ca1b2
15 changed files with 169 additions and 53 deletions

View File

@@ -8,3 +8,10 @@ sudo apt install pkg-config
sudo apt install libssl-dev sudo apt install libssl-dev
cargo install sqlx-cli --no-default-features --features rustls,postgres cargo install sqlx-cli --no-default-features --features rustls,postgres
``` ```
## TODO
- Register form on homepage
- Success message displayed to new subscriber who confirmed his account
- Worker to remove idempotency key from database
- List of subscribers (confirmed and unconfirmed) on admin dashboard

View File

@@ -1,14 +1,6 @@
application: application:
port: 8000 port: 8000
database: database:
host: "127.0.0.1"
port: 5432
username: "postgres"
password: "password"
database_name: "newsletter" database_name: "newsletter"
email_client: email_client:
base_url: "http://127.0.0.1"
sender_email: "sender@example.com"
authorization_token: "my-secret-token"
timeout_milliseconds: 10000 timeout_milliseconds: 10000
redis_uri: "redis://127.0.0.1:6379"

View File

@@ -2,4 +2,13 @@ application:
host: "127.0.0.1" host: "127.0.0.1"
base_url: "http://127.0.0.1:8000" base_url: "http://127.0.0.1:8000"
database: database:
host: "127.0.0.1"
port: 5432
username: "postgres"
password: "password"
require_ssl: false require_ssl: false
email_client:
base_url: "https://api.mailersend.com"
sender_email: "MS_PTrumQ@test-r6ke4n1mmzvgon12.mlsender.net"
authorization_token: "secret-token"
redis_uri: "redis://127.0.0.1:6379"

View File

@@ -2,6 +2,7 @@ mod admin;
mod health_check; mod health_check;
mod home; mod home;
mod login; mod login;
mod register;
mod subscriptions; mod subscriptions;
mod subscriptions_confirm; mod subscriptions_confirm;
@@ -9,5 +10,6 @@ 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 register::*;
pub use subscriptions::*; pub use subscriptions::*;
pub use subscriptions_confirm::*; pub use subscriptions_confirm::*;

View File

@@ -7,6 +7,9 @@
</head> </head>
<body> <body>
<p>Welcome to our newsletter!</p> <p>Welcome to our newsletter!</p>
<p><a href="/login">Login</a></p> <ol>
<li><a href="/login">Admin login</a></li>
<li><a href="/register">Register</a></li>
</ol>
</body> </body>
</html> </html>

11
src/routes/register.rs Normal file
View File

@@ -0,0 +1,11 @@
use axum::response::{Html, IntoResponse, Response};
use axum_messages::Messages;
use std::fmt::Write;
pub async fn register(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!("register/register.html"), error_html)).into_response()
}

View File

@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Account confirmed</title>
</head>
<body>
<p>Your account has been confirmed. Welcome!</p>
</body>
</html>

View File

@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Register</title>
</head>
<body>
<form action="/subscriptions" method="post">
<input type="text" name="name" placeholder="Name" />
<input type="text" name="email" placeholder="Email address" />
<input
type="text"
name="email_check"
placeholder="Confirm email address"
/>
<button type="Register">Register</button>
</form>
{}
<p><a href="/">Back</a></p>
</body>
</html>

View File

@@ -8,8 +8,9 @@ use axum::{
Form, Json, Form, Json,
extract::State, extract::State,
http::StatusCode, http::StatusCode,
response::{IntoResponse, Response}, response::{IntoResponse, Redirect, Response},
}; };
use axum_messages::Messages;
use chrono::Utc; use chrono::Utc;
use rand::{Rng, distr::Alphanumeric}; use rand::{Rng, distr::Alphanumeric};
use serde::Deserialize; use serde::Deserialize;
@@ -63,12 +64,16 @@ impl IntoResponse for SubscribeError {
tracing::error!("{:?}", self); tracing::error!("{:?}", self);
let status = match self { match self {
SubscribeError::UnexpectedError(_) => StatusCode::INTERNAL_SERVER_ERROR, SubscribeError::UnexpectedError(_) => (
SubscribeError::ValidationError(_) => StatusCode::BAD_REQUEST, StatusCode::INTERNAL_SERVER_ERROR,
}; Json(ErrorResponse {
let message = "An internal server error occured."; message: "An internal server error occured.",
(status, Json(ErrorResponse { message })).into_response() }),
)
.into_response(),
SubscribeError::ValidationError(_) => Redirect::to("/register").into_response(),
}
} }
} }
@@ -81,6 +86,7 @@ impl IntoResponse for SubscribeError {
) )
)] )]
pub async fn subscribe( pub async fn subscribe(
messages: Messages,
State(AppState { State(AppState {
connection_pool, connection_pool,
email_client, email_client,
@@ -89,11 +95,17 @@ pub async fn subscribe(
}): State<AppState>, }): State<AppState>,
Form(form): Form<SubscriptionFormData>, Form(form): Form<SubscriptionFormData>,
) -> Result<Response, SubscribeError> { ) -> Result<Response, SubscribeError> {
let new_subscriber = match form.try_into() {
Ok(new_sub) => new_sub,
Err(e) => {
messages.error(&e);
return Err(SubscribeError::ValidationError(e));
}
};
let mut transaction = connection_pool let mut transaction = connection_pool
.begin() .begin()
.await .await
.context("Failed to acquire a Postgres connection from the pool.")?; .context("Failed to acquire a Postgres connection from the pool.")?;
let new_subscriber = form.try_into().map_err(SubscribeError::ValidationError)?;
let subscriber_id = insert_subscriber(&mut transaction, &new_subscriber) let subscriber_id = insert_subscriber(&mut transaction, &new_subscriber)
.await .await
.context("Failed to insert new subscriber in the database.")?; .context("Failed to insert new subscriber in the database.")?;
@@ -113,7 +125,8 @@ pub async fn subscribe(
.commit() .commit()
.await .await
.context("Failed to commit the database transaction to store a new subscriber.")?; .context("Failed to commit the database transaction to store a new subscriber.")?;
Ok(StatusCode::OK.into_response()) messages.success("A confirmation email has been sent.");
Ok(Redirect::to("/register").into_response())
} }
#[tracing::instrument( #[tracing::instrument(
@@ -198,6 +211,7 @@ Click <a href=\"{}\">here</a> to confirm your subscription.",
pub struct SubscriptionFormData { pub struct SubscriptionFormData {
name: String, name: String,
email: String, email: String,
email_check: String,
} }
impl TryFrom<SubscriptionFormData> for NewSubscriber { impl TryFrom<SubscriptionFormData> for NewSubscriber {
@@ -205,6 +219,9 @@ impl TryFrom<SubscriptionFormData> for NewSubscriber {
fn try_from(value: SubscriptionFormData) -> Result<Self, Self::Error> { fn try_from(value: SubscriptionFormData) -> Result<Self, Self::Error> {
let name = SubscriberName::parse(value.name)?; let name = SubscriberName::parse(value.name)?;
if value.email != value.email_check {
return Err("Email addresses don't match.".into());
}
let email = SubscriberEmail::parse(value.email)?; let email = SubscriberEmail::parse(value.email)?;
Ok(Self { name, email }) Ok(Self { name, email })
} }

View File

@@ -2,7 +2,7 @@ use crate::startup::AppState;
use axum::{ use axum::{
extract::{Query, State}, extract::{Query, State},
http::StatusCode, http::StatusCode,
response::IntoResponse, response::{Html, IntoResponse, Response},
}; };
use serde::Deserialize; use serde::Deserialize;
use sqlx::PgPool; use sqlx::PgPool;
@@ -14,23 +14,23 @@ pub async fn confirm(
connection_pool, .. connection_pool, ..
}): State<AppState>, }): State<AppState>,
Query(params): Query<Params>, Query(params): Query<Params>,
) -> impl IntoResponse { ) -> Response {
let Ok(subscriber_id) = let Ok(subscriber_id) =
get_subscriber_id_from_token(&connection_pool, &params.subscription_token).await get_subscriber_id_from_token(&connection_pool, &params.subscription_token).await
else { else {
return StatusCode::INTERNAL_SERVER_ERROR; return StatusCode::INTERNAL_SERVER_ERROR.into_response();
}; };
if let Some(subscriber_id) = subscriber_id { if let Some(subscriber_id) = subscriber_id {
if confirm_subscriber(&connection_pool, &subscriber_id) if confirm_subscriber(&connection_pool, &subscriber_id)
.await .await
.is_err() .is_err()
{ {
StatusCode::INTERNAL_SERVER_ERROR StatusCode::INTERNAL_SERVER_ERROR.into_response()
} else { } else {
StatusCode::OK Html(include_str!("register/confirm.html")).into_response()
} }
} else { } else {
StatusCode::UNAUTHORIZED StatusCode::UNAUTHORIZED.into_response()
} }
} }

View File

@@ -96,6 +96,7 @@ pub fn app(
.layer(middleware::from_fn(require_auth)); .layer(middleware::from_fn(require_auth));
Router::new() Router::new()
.route("/", get(home)) .route("/", get(home))
.route("/register", get(register))
.route("/login", get(get_login).post(post_login)) .route("/login", get(get_login).post(post_login))
.route("/health_check", get(health_check)) .route("/health_check", get(health_check))
.route("/subscriptions", post(subscribe)) .route("/subscriptions", post(subscribe))

View File

@@ -177,6 +177,17 @@ impl TestApp {
self.get_admin_dashboard().await.text().await.unwrap() self.get_admin_dashboard().await.text().await.unwrap()
} }
pub async fn get_register_html(&self) -> String {
self.api_client
.get(format!("{}/register", &self.address))
.send()
.await
.expect("Failed to execute request")
.text()
.await
.unwrap()
}
pub async fn get_change_password(&self) -> reqwest::Response { pub async fn get_change_password(&self) -> reqwest::Response {
self.api_client self.api_client
.get(format!("{}/admin/password", &self.address)) .get(format!("{}/admin/password", &self.address))

View File

@@ -199,7 +199,8 @@ async fn create_unconfirmed_subscriber(app: &TestApp) -> ConfirmationLinks {
let email: String = SafeEmail().fake(); let email: String = SafeEmail().fake();
let body = serde_urlencoded::to_string(serde_json::json!({ let body = serde_urlencoded::to_string(serde_json::json!({
"name": name, "name": name,
"email": email "email": email,
"email_check": email
})) }))
.unwrap(); .unwrap();

View File

@@ -1,11 +1,11 @@
use crate::helpers::TestApp; use crate::helpers::{TestApp, assert_is_redirect_to};
use wiremock::{ use wiremock::{
Mock, ResponseTemplate, Mock, ResponseTemplate,
matchers::{method, path}, matchers::{method, path},
}; };
#[tokio::test] #[tokio::test]
async fn subscribe_returns_a_200_for_valid_form_data() { async fn subscribe_displays_a_confirmation_message_for_valid_form_data() {
let app = TestApp::spawn().await; let app = TestApp::spawn().await;
Mock::given(path("/v1/email")) Mock::given(path("/v1/email"))
@@ -14,10 +14,13 @@ async fn subscribe_returns_a_200_for_valid_form_data() {
.mount(&app.email_server) .mount(&app.email_server)
.await; .await;
let body = "name=Alphonse&email=alphonse.paix%40outlook.com"; let email = "alphonse.paix@outlook.com";
let response = app.post_subscriptions(body.into()).await; let body = format!("name=Alphonse&email={0}&email_check={0}", email);
let response = app.post_subscriptions(body).await;
assert_eq!(200, response.status().as_u16()); assert_is_redirect_to(&response, "/register");
let page_html = app.get_register_html().await;
assert!(page_html.contains("A confirmation email has been sent"));
} }
#[tokio::test] #[tokio::test]
@@ -30,10 +33,13 @@ async fn subscribe_persists_the_new_subscriber() {
.mount(&app.email_server) .mount(&app.email_server)
.await; .await;
let body = "name=Alphonse&email=alphonse.paix%40outlook.com"; let email = "alphonse.paix@outlook.com";
let response = app.post_subscriptions(body.into()).await; let body = format!("name=Alphonse&email={0}&email_check={0}", email);
let response = app.post_subscriptions(body).await;
assert_eq!(200, response.status().as_u16()); assert_is_redirect_to(&response, "/register");
let page_html = app.get_register_html().await;
assert!(page_html.contains("A confirmation email has been sent"));
let saved = sqlx::query!("SELECT email, name, status FROM subscriptions") let saved = sqlx::query!("SELECT email, name, status FROM subscriptions")
.fetch_one(&app.connection_pool) .fetch_one(&app.connection_pool)
@@ -67,21 +73,32 @@ async fn subscribe_returns_a_422_when_data_is_missing() {
} }
#[tokio::test] #[tokio::test]
async fn subscribe_returns_a_400_when_fields_are_present_but_invalid() { async fn subscribe_shows_an_error_message_when_fields_are_present_but_invalid() {
let app = TestApp::spawn().await; let app = TestApp::spawn().await;
let test_cases = [ let test_cases = [
("name=&email=alphonse.paix%40outlook.com", "empty name"), ("name=&email=alphonse.paix%40outlook.com", "an empty name"),
("name=Alphonse&email=", "empty email"), ("name=Alphonse&email=&email_check=", "an empty email"),
("name=Alphonse&email=not-an-email", "invalid email"), (
"name=Alphonse&email=not-an-email&email_check=not-an_email",
"an invalid email",
),
(
"name=Alphonse&email=alphonse.paix@outlook.com&email_check=alphonse.paix@outlook.fr",
"two different email addresses",
),
]; ];
for (body, description) in test_cases { for (body, description) in test_cases {
let response = app.post_subscriptions(body.into()).await; let response_text = app
.post_subscriptions(body.into())
.await
.text()
.await
.unwrap();
assert_eq!( assert!(
400, !response_text.contains("Your account has been confirmed"),
response.status().as_u16(), "the API did not displayed an error message when the payload had an {}.",
"the API did not fail with 400 Bad Request when the payload had an {}.",
description description
); );
} }
@@ -91,7 +108,8 @@ async fn subscribe_returns_a_400_when_fields_are_present_but_invalid() {
async fn subscribe_sends_a_confirmation_email_for_valid_data() { async fn subscribe_sends_a_confirmation_email_for_valid_data() {
let app = TestApp::spawn().await; let app = TestApp::spawn().await;
let body = "name=Alphonse&email=alphonse.paix%40outlook.com"; let email = "alphonse.paix@outlook.com";
let body = format!("name=Alphonse&email={0}&email_check={0}", email);
Mock::given(path("v1/email")) Mock::given(path("v1/email"))
.and(method("POST")) .and(method("POST"))
@@ -100,14 +118,15 @@ async fn subscribe_sends_a_confirmation_email_for_valid_data() {
.mount(&app.email_server) .mount(&app.email_server)
.await; .await;
app.post_subscriptions(body.into()).await; app.post_subscriptions(body).await;
} }
#[tokio::test] #[tokio::test]
async fn subscribe_sends_a_confirmation_email_with_a_link() { async fn subscribe_sends_a_confirmation_email_with_a_link() {
let app = TestApp::spawn().await; let app = TestApp::spawn().await;
let body = "name=Alphonse&email=alphonse.paix%40outlook.com"; let email = "alphonse.paix@outlook.com";
let body = format!("name=Alphonse&email={0}&email_check={0}", email);
Mock::given(path("v1/email")) Mock::given(path("v1/email"))
.and(method("POST")) .and(method("POST"))
@@ -116,7 +135,7 @@ async fn subscribe_sends_a_confirmation_email_with_a_link() {
.mount(&app.email_server) .mount(&app.email_server)
.await; .await;
app.post_subscriptions(body.into()).await; app.post_subscriptions(body).await;
let email_request = &app.email_server.received_requests().await.unwrap()[0]; let email_request = &app.email_server.received_requests().await.unwrap()[0];
let confirmation_links = app.get_confirmation_links(email_request); let confirmation_links = app.get_confirmation_links(email_request);
@@ -127,14 +146,15 @@ async fn subscribe_sends_a_confirmation_email_with_a_link() {
async fn subscribe_fails_if_there_is_a_fatal_database_error() { async fn subscribe_fails_if_there_is_a_fatal_database_error() {
let app = TestApp::spawn().await; let app = TestApp::spawn().await;
let body = "name=Alphonse&email=alphonse.paix%40outlook.com"; let email = "alphonse.paix@outlook.com";
let body = format!("name=Alphonse&email={0}&email_check={0}", email);
sqlx::query!("ALTER TABLE subscriptions DROP COLUMN email") sqlx::query!("ALTER TABLE subscriptions DROP COLUMN email")
.execute(&app.connection_pool) .execute(&app.connection_pool)
.await .await
.unwrap(); .unwrap();
let response = app.post_subscriptions(body.into()).await; let response = app.post_subscriptions(body).await;
assert_eq!(response.status().as_u16(), 500); assert_eq!(response.status().as_u16(), 500);
} }

View File

@@ -15,10 +15,11 @@ async fn confirmation_links_without_token_are_rejected_with_a_400() {
} }
#[tokio::test] #[tokio::test]
async fn the_link_returned_by_subscribe_returns_a_200_if_called() { async fn clicking_on_the_link_shows_a_confiramtion_message() {
let app = TestApp::spawn().await; let app = TestApp::spawn().await;
let body = "name=Alphonse&email=alphonse.paix%40outlook.com"; let email = "alphonse.paix@outlook.com";
let body = format!("name=Alphonse&email={email}&email_check={email}");
Mock::given(path("v1/email")) Mock::given(path("v1/email"))
.and(method("POST")) .and(method("POST"))
@@ -27,19 +28,27 @@ async fn the_link_returned_by_subscribe_returns_a_200_if_called() {
.mount(&app.email_server) .mount(&app.email_server)
.await; .await;
app.post_subscriptions(body.into()).await; app.post_subscriptions(body).await;
let email_request = &app.email_server.received_requests().await.unwrap()[0]; let email_request = &app.email_server.received_requests().await.unwrap()[0];
let confirmation_links = app.get_confirmation_links(email_request); let confirmation_links = app.get_confirmation_links(email_request);
let response = reqwest::get(confirmation_links.html).await.unwrap(); let response = reqwest::get(confirmation_links.html).await.unwrap();
assert_eq!(response.status().as_u16(), 200); assert_eq!(response.status().as_u16(), 200);
assert!(
response
.text()
.await
.unwrap()
.contains("Your account has been confirmed")
);
} }
#[tokio::test] #[tokio::test]
async fn clicking_on_the_confirmation_link_confirms_a_subscriber() { async fn clicking_on_the_confirmation_link_confirms_a_subscriber() {
let app = TestApp::spawn().await; let app = TestApp::spawn().await;
let body = "name=Alphonse&email=alphonse.paix%40outlook.com"; let email = "alphonse.paix@outlook.com";
let body = format!("name=Alphonse&email={email}&email_check={email}");
Mock::given(path("v1/email")) Mock::given(path("v1/email"))
.and(method("POST")) .and(method("POST"))
@@ -48,7 +57,7 @@ async fn clicking_on_the_confirmation_link_confirms_a_subscriber() {
.mount(&app.email_server) .mount(&app.email_server)
.await; .await;
app.post_subscriptions(body.into()).await; app.post_subscriptions(body).await;
let email_request = &app.email_server.received_requests().await.unwrap()[0]; let email_request = &app.email_server.received_requests().await.unwrap()[0];
let confirmation_links = app.get_confirmation_links(email_request); let confirmation_links = app.get_confirmation_links(email_request);