Profile update tests
This commit is contained in:
@@ -158,7 +158,10 @@ pub async fn update_post(
|
||||
))
|
||||
.into_response())
|
||||
}
|
||||
_ => Ok(HtmlTemplate(ErrorTemplate::Forbidden).into_response()),
|
||||
_ => Ok(HtmlTemplate(MessageTemplate::error(
|
||||
"You are not authorized. Only the author can edit his post.".into(),
|
||||
))
|
||||
.into_response()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::authentication::AuthenticatedUser;
|
||||
use crate::routes::verify_password;
|
||||
use crate::session_state::TypedSession;
|
||||
use crate::templates::{ErrorTemplate, MessageTemplate, UserEditTemplate};
|
||||
use crate::templates::{MessageTemplate, UserEditTemplate};
|
||||
use crate::{
|
||||
authentication::Role,
|
||||
domain::{PostEntry, UserEntry},
|
||||
@@ -18,6 +18,7 @@ use axum::{
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
use validator::Validate;
|
||||
|
||||
pub async fn user_edit_form(
|
||||
Extension(AuthenticatedUser { user_id, .. }): Extension<AuthenticatedUser>,
|
||||
@@ -41,9 +42,10 @@ pub async fn user_edit_form(
|
||||
Ok(template.into_response())
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[derive(Debug, Validate, serde::Deserialize)]
|
||||
pub struct EditProfileForm {
|
||||
user_id: Uuid,
|
||||
#[validate(length(min = 3, message = "Username must be at least 3 characters."))]
|
||||
username: String,
|
||||
full_name: String,
|
||||
bio: String,
|
||||
@@ -62,8 +64,27 @@ pub async fn update_user(
|
||||
}): Extension<AuthenticatedUser>,
|
||||
Form(form): Form<EditProfileForm>,
|
||||
) -> Result<Response, AppError> {
|
||||
if let Err(e) = form.validate() {
|
||||
let error_messages: Vec<_> = e
|
||||
.field_errors()
|
||||
.iter()
|
||||
.flat_map(|(field, errors)| {
|
||||
errors.iter().map(move |error| {
|
||||
error
|
||||
.message
|
||||
.as_ref()
|
||||
.map(|msg| msg.to_string())
|
||||
.unwrap_or(format!("Invalid field: {}", field))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let template = HtmlTemplate(MessageTemplate::error(error_messages.join("\n")));
|
||||
return Ok(template.into_response());
|
||||
}
|
||||
if form.user_id != session_user_id {
|
||||
let template = HtmlTemplate(ErrorTemplate::Forbidden);
|
||||
let template = HtmlTemplate(MessageTemplate::error(
|
||||
"You are not authorized. Refresh the page and try again.".into(),
|
||||
));
|
||||
return Ok(template.into_response());
|
||||
}
|
||||
let updated_username = form.username.trim();
|
||||
@@ -78,7 +99,7 @@ pub async fn update_user(
|
||||
.is_some()
|
||||
{
|
||||
let template = HtmlTemplate(MessageTemplate::error(
|
||||
"The username is already taken.".into(),
|
||||
"This username is already taken.".into(),
|
||||
));
|
||||
return Ok(template.into_response());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user