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

@@ -2,6 +2,7 @@ mod admin;
mod health_check;
mod home;
mod login;
mod register;
mod subscriptions;
mod subscriptions_confirm;
@@ -9,5 +10,6 @@ pub use admin::*;
pub use health_check::*;
pub use home::*;
pub use login::*;
pub use register::*;
pub use subscriptions::*;
pub use subscriptions_confirm::*;

View File

@@ -7,6 +7,9 @@
</head>
<body>
<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>
</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,
extract::State,
http::StatusCode,
response::{IntoResponse, Response},
response::{IntoResponse, Redirect, Response},
};
use axum_messages::Messages;
use chrono::Utc;
use rand::{Rng, distr::Alphanumeric};
use serde::Deserialize;
@@ -63,12 +64,16 @@ impl IntoResponse for SubscribeError {
tracing::error!("{:?}", self);
let status = match self {
SubscribeError::UnexpectedError(_) => StatusCode::INTERNAL_SERVER_ERROR,
SubscribeError::ValidationError(_) => StatusCode::BAD_REQUEST,
};
let message = "An internal server error occured.";
(status, Json(ErrorResponse { message })).into_response()
match self {
SubscribeError::UnexpectedError(_) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
message: "An internal server error occured.",
}),
)
.into_response(),
SubscribeError::ValidationError(_) => Redirect::to("/register").into_response(),
}
}
}
@@ -81,6 +86,7 @@ impl IntoResponse for SubscribeError {
)
)]
pub async fn subscribe(
messages: Messages,
State(AppState {
connection_pool,
email_client,
@@ -89,11 +95,17 @@ pub async fn subscribe(
}): State<AppState>,
Form(form): Form<SubscriptionFormData>,
) -> 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
.begin()
.await
.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)
.await
.context("Failed to insert new subscriber in the database.")?;
@@ -113,7 +125,8 @@ pub async fn subscribe(
.commit()
.await
.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(
@@ -198,6 +211,7 @@ Click <a href=\"{}\">here</a> to confirm your subscription.",
pub struct SubscriptionFormData {
name: String,
email: String,
email_check: String,
}
impl TryFrom<SubscriptionFormData> for NewSubscriber {
@@ -205,6 +219,9 @@ impl TryFrom<SubscriptionFormData> for NewSubscriber {
fn try_from(value: SubscriptionFormData) -> Result<Self, Self::Error> {
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)?;
Ok(Self { name, email })
}

View File

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

View File

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