Use HTML swap to display success and error messages

This commit is contained in:
Alphonse Paix
2025-09-17 03:40:23 +02:00
parent a3533bfde7
commit 7689628ffb
18 changed files with 134 additions and 232 deletions

View File

@@ -2,13 +2,14 @@ use crate::{
authentication::{self, AuthenticatedUser, Credentials, validate_credentials},
routes::AdminError,
startup::AppState,
templates::SuccessTemplate,
};
use askama::Template;
use axum::{
Extension, Form,
extract::State,
response::{IntoResponse, Redirect, Response},
response::{Html, IntoResponse, Response},
};
use axum_messages::Messages;
use secrecy::{ExposeSecret, SecretString};
#[derive(serde::Deserialize)]
@@ -23,7 +24,6 @@ pub async fn change_password(
State(AppState {
connection_pool, ..
}): State<AppState>,
messages: Messages,
Form(form): Form<PasswordFormData>,
) -> Result<Response, AdminError> {
let credentials = Credentials {
@@ -31,23 +31,26 @@ pub async fn change_password(
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)
Err(AdminError::ChangePassword(
"You entered two different passwords - the field values must match.".to_string(),
))
} else if validate_credentials(credentials, &connection_pool)
.await
.is_err()
{
messages.error("The current password is incorrect.");
Err(AdminError::ChangePassword)
Err(AdminError::ChangePassword(
"The current password is incorrect.".to_string(),
))
} else if let Err(e) = verify_password(form.new_password.expose_secret()) {
messages.error(e);
Err(AdminError::ChangePassword)
Err(AdminError::ChangePassword(e))
} 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())
.map_err(|e| AdminError::ChangePassword(e.to_string()))?;
let template = SuccessTemplate {
success_message: "Your password has been changed.".to_string(),
};
Ok(Html(template.render().unwrap()).into_response())
}
}