Translation (WIP)

This commit is contained in:
Greg Burri 2025-01-05 22:38:46 +01:00
parent 9b0fcec5e2
commit e9873c1943
29 changed files with 586 additions and 285 deletions

View file

@ -9,6 +9,7 @@ use serde::Deserialize;
use crate::{
data::{db, model},
html_templates::*,
translation,
};
#[derive(Deserialize)]
@ -21,6 +22,7 @@ pub async fn recipes_list_fragments(
State(connection): State<db::Connection>,
current_recipe: Query<CurrentRecipeId>,
Extension(user): Extension<Option<model::User>>,
Extension(tr): Extension<translation::Tr>,
) -> Result<impl IntoResponse> {
let recipes = Recipes {
published: connection.get_all_published_recipe_titles().await?,
@ -33,5 +35,5 @@ pub async fn recipes_list_fragments(
},
current_id: current_recipe.current_recipe_id,
};
Ok(RecipesListFragmentTemplate { user, recipes })
Ok(RecipesListFragmentTemplate { user, tr, recipes })
}

View file

@ -9,20 +9,20 @@ use crate::{
consts,
data::{db, model},
html_templates::*,
translation,
};
///// RECIPE /////
#[debug_handler]
pub async fn create(
State(connection): State<db::Connection>,
Extension(user): Extension<Option<model::User>>,
Extension(tr): Extension<translation::Tr>,
) -> Result<Response> {
if let Some(user) = user {
let recipe_id = connection.create_recipe(user.id).await?;
Ok(Redirect::to(&format!("/recipe/edit/{}", recipe_id)).into_response())
} else {
Ok(MessageTemplate::new("Not logged in").into_response())
Ok(MessageTemplate::new("Not logged in", tr).into_response())
}
}
@ -30,10 +30,11 @@ pub async fn create(
pub async fn edit_recipe(
State(connection): State<db::Connection>,
Extension(user): Extension<Option<model::User>>,
Extension(tr): Extension<translation::Tr>,
Path(recipe_id): Path<i64>,
) -> Result<Response> {
if let Some(user) = user {
if let Some(recipe) = connection.get_recipe(recipe_id).await? {
if let Some(recipe) = connection.get_recipe(recipe_id, false).await? {
if recipe.user_id == user.id {
let recipes = Recipes {
published: connection.get_all_published_recipe_titles().await?,
@ -45,19 +46,20 @@ pub async fn edit_recipe(
Ok(RecipeEditTemplate {
user: Some(user),
tr,
recipes,
recipe,
languages: *consts::LANGUAGES,
}
.into_response())
} else {
Ok(MessageTemplate::new("Not allowed to edit this recipe").into_response())
Ok(MessageTemplate::new("Not allowed to edit this recipe", tr).into_response())
}
} else {
Ok(MessageTemplate::new("Recipe not found").into_response())
Ok(MessageTemplate::new("Recipe not found", tr).into_response())
}
} else {
Ok(MessageTemplate::new("Not logged in").into_response())
Ok(MessageTemplate::new("Not logged in", tr).into_response())
}
}
@ -65,15 +67,17 @@ pub async fn edit_recipe(
pub async fn view(
State(connection): State<db::Connection>,
Extension(user): Extension<Option<model::User>>,
Extension(tr): Extension<translation::Tr>,
Path(recipe_id): Path<i64>,
) -> Result<Response> {
match connection.get_recipe(recipe_id).await? {
match connection.get_recipe(recipe_id, true).await? {
Some(recipe) => {
if !recipe.is_published
&& (user.is_none() || recipe.user_id != user.as_ref().unwrap().id)
{
return Ok(MessageTemplate::new_with_user(
&format!("Not allowed the view the recipe {}", recipe_id),
tr,
user,
)
.into_response());
@ -93,6 +97,7 @@ pub async fn view(
Ok(RecipeViewTemplate {
user,
tr,
recipes,
recipe,
}
@ -100,6 +105,7 @@ pub async fn view(
}
None => Ok(MessageTemplate::new_with_user(
&format!("Cannot find the recipe {}", recipe_id),
tr,
user,
)
.into_response()),

View file

@ -19,6 +19,7 @@ use crate::{
data::{db, model},
email,
html_templates::*,
translation::{self, Sentence},
utils, AppState,
};
@ -27,9 +28,11 @@ use crate::{
#[debug_handler]
pub async fn sign_up_get(
Extension(user): Extension<Option<model::User>>,
Extension(tr): Extension<translation::Tr>,
) -> Result<impl IntoResponse> {
Ok(SignUpFormTemplate {
user,
tr,
email: String::new(),
message: String::new(),
message_email: String::new(),
@ -59,34 +62,37 @@ pub async fn sign_up_post(
State(connection): State<db::Connection>,
State(config): State<Config>,
Extension(user): Extension<Option<model::User>>,
Extension(tr): Extension<translation::Tr>,
Form(form_data): Form<SignUpFormData>,
) -> Result<Response> {
fn error_response(
error: SignUpError,
form_data: &SignUpFormData,
user: Option<model::User>,
tr: translation::Tr,
) -> Result<Response> {
Ok(SignUpFormTemplate {
user,
email: form_data.email.clone(),
message_email: match error {
SignUpError::InvalidEmail => "Invalid email",
_ => "",
}
.to_string(),
SignUpError::InvalidEmail => tr.t(Sentence::InvalidEmail),
_ => String::new(),
},
message_password: match error {
SignUpError::PasswordsNotEqual => "Passwords don't match",
SignUpError::InvalidPassword => "Password must have at least eight characters",
_ => "",
}
.to_string(),
SignUpError::PasswordsNotEqual => tr.t(Sentence::PasswordDontMatch),
SignUpError::InvalidPassword => tr.tp(
Sentence::InvalidPassword,
&[Box::new(common::consts::MIN_PASSWORD_SIZE)],
),
_ => String::new(),
},
message: match error {
SignUpError::UserAlreadyExists => "This email is not available",
SignUpError::DatabaseError => "Database error",
SignUpError::UnableSendEmail => "Unable to send the validation email",
_ => "",
}
.to_string(),
SignUpError::UserAlreadyExists => tr.t(Sentence::EmailAlreadyTaken),
SignUpError::DatabaseError => "Database error".to_string(),
SignUpError::UnableSendEmail => tr.t(Sentence::UnableToSendEmail),
_ => String::new(),
},
tr,
}
.into_response())
}
@ -95,17 +101,17 @@ pub async fn sign_up_post(
if let common::utils::EmailValidation::NotValid =
common::utils::validate_email(&form_data.email)
{
return error_response(SignUpError::InvalidEmail, &form_data, user);
return error_response(SignUpError::InvalidEmail, &form_data, user, tr);
}
if form_data.password_1 != form_data.password_2 {
return error_response(SignUpError::PasswordsNotEqual, &form_data, user);
return error_response(SignUpError::PasswordsNotEqual, &form_data, user, tr);
}
if let common::utils::PasswordValidation::TooShort =
common::utils::validate_password(&form_data.password_1)
{
return error_response(SignUpError::InvalidPassword, &form_data, user);
return error_response(SignUpError::InvalidPassword, &form_data, user, tr);
}
match connection
@ -113,7 +119,7 @@ pub async fn sign_up_post(
.await
{
Ok(db::user::SignUpResult::UserAlreadyExists) => {
error_response(SignUpError::UserAlreadyExists, &form_data, user)
error_response(SignUpError::UserAlreadyExists, &form_data, user, tr)
}
Ok(db::user::SignUpResult::UserCreatedWaitingForValidation(token)) => {
let url = utils::get_url_from_host(&host);
@ -133,16 +139,16 @@ pub async fn sign_up_post(
Ok(()) => Ok(
MessageTemplate::new_with_user(
"An email has been sent, follow the link to validate your account",
user).into_response()),
tr, user).into_response()),
Err(_) => {
// error!("Email validation error: {}", error); // TODO: log
error_response(SignUpError::UnableSendEmail, &form_data, user)
error_response(SignUpError::UnableSendEmail, &form_data, user, tr)
}
}
}
Err(_) => {
// error!("Signup database error: {}", error); // TODO: log
error_response(SignUpError::DatabaseError, &form_data, user)
error_response(SignUpError::DatabaseError, &form_data, user, tr)
}
}
}
@ -151,6 +157,7 @@ pub async fn sign_up_post(
pub async fn sign_up_validation(
State(connection): State<db::Connection>,
Extension(user): Extension<Option<model::User>>,
Extension(tr): Extension<translation::Tr>,
ConnectInfo(addr): ConnectInfo<SocketAddr>,
Query(query): Query<HashMap<String, String>>,
headers: HeaderMap,
@ -159,7 +166,7 @@ pub async fn sign_up_validation(
if user.is_some() {
return Ok((
jar,
MessageTemplate::new_with_user("User already exists", user),
MessageTemplate::new_with_user("User already exists", tr, user),
));
}
let (client_ip, client_user_agent) = utils::get_ip_and_user_agent(&headers, addr);
@ -183,6 +190,7 @@ pub async fn sign_up_validation(
jar,
MessageTemplate::new_with_user(
"Email validation successful, your account has been created",
tr,
user,
),
))
@ -191,18 +199,23 @@ pub async fn sign_up_validation(
jar,
MessageTemplate::new_with_user(
"The validation has expired. Try to sign up again",
tr,
user,
),
)),
db::user::ValidationResult::UnknownUser => Ok((
jar,
MessageTemplate::new_with_user("Validation error. Try to sign up again", user),
MessageTemplate::new_with_user(
"Validation error. Try to sign up again",
tr,
user,
),
)),
}
}
None => Ok((
jar,
MessageTemplate::new_with_user("Validation error", user),
MessageTemplate::new_with_user("Validation error", tr, user),
)),
}
}
@ -212,9 +225,11 @@ pub async fn sign_up_validation(
#[debug_handler]
pub async fn sign_in_get(
Extension(user): Extension<Option<model::User>>,
Extension(tr): Extension<translation::Tr>,
) -> Result<impl IntoResponse> {
Ok(SignInFormTemplate {
user,
tr,
email: String::new(),
message: String::new(),
})
@ -231,6 +246,7 @@ pub async fn sign_in_post(
ConnectInfo(addr): ConnectInfo<SocketAddr>,
State(connection): State<db::Connection>,
Extension(user): Extension<Option<model::User>>,
Extension(tr): Extension<translation::Tr>,
headers: HeaderMap,
Form(form_data): Form<SignInFormData>,
) -> Result<(CookieJar, Response)> {
@ -251,7 +267,8 @@ pub async fn sign_in_post(
SignInFormTemplate {
user,
email: form_data.email,
message: "This account must be validated first".to_string(),
message: tr.t(Sentence::AccountMustBeValidatedFirst),
tr,
}
.into_response(),
)),
@ -260,7 +277,8 @@ pub async fn sign_in_post(
SignInFormTemplate {
user,
email: form_data.email,
message: "Wrong email or password".to_string(),
message: tr.t(Sentence::WrongEmailOrPassword),
tr,
}
.into_response(),
)),
@ -292,16 +310,19 @@ pub async fn sign_out(
#[debug_handler]
pub async fn ask_reset_password_get(
Extension(user): Extension<Option<model::User>>,
Extension(tr): Extension<translation::Tr>,
) -> Result<Response> {
if user.is_some() {
Ok(MessageTemplate::new_with_user(
"Can't ask to reset password when already logged in",
tr,
user,
)
.into_response())
} else {
Ok(AskResetPasswordTemplate {
user,
tr,
email: String::new(),
message: String::new(),
message_email: String::new(),
@ -329,15 +350,18 @@ pub async fn ask_reset_password_post(
State(connection): State<db::Connection>,
State(config): State<Config>,
Extension(user): Extension<Option<model::User>>,
Extension(tr): Extension<translation::Tr>,
Form(form_data): Form<AskResetPasswordForm>,
) -> Result<Response> {
fn error_response(
error: AskResetPasswordError,
email: &str,
user: Option<model::User>,
tr: translation::Tr,
) -> Result<Response> {
Ok(AskResetPasswordTemplate {
user,
tr,
email: email.to_string(),
message_email: match error {
AskResetPasswordError::InvalidEmail => "Invalid email",
@ -362,7 +386,12 @@ pub async fn ask_reset_password_post(
if let common::utils::EmailValidation::NotValid =
common::utils::validate_email(&form_data.email)
{
return error_response(AskResetPasswordError::InvalidEmail, &form_data.email, user);
return error_response(
AskResetPasswordError::InvalidEmail,
&form_data.email,
user,
tr,
);
}
match connection
@ -376,10 +405,14 @@ pub async fn ask_reset_password_post(
AskResetPasswordError::EmailAlreadyReset,
&form_data.email,
user,
tr,
),
Ok(db::user::GetTokenResetPasswordResult::EmailUnknown) => error_response(
AskResetPasswordError::EmailUnknown,
&form_data.email,
user,
tr,
),
Ok(db::user::GetTokenResetPasswordResult::EmailUnknown) => {
error_response(AskResetPasswordError::EmailUnknown, &form_data.email, user)
}
Ok(db::user::GetTokenResetPasswordResult::Ok(token)) => {
let url = utils::get_url_from_host(&host);
match email::send_email(
@ -396,6 +429,7 @@ pub async fn ask_reset_password_post(
{
Ok(()) => Ok(MessageTemplate::new_with_user(
"An email has been sent, follow the link to reset your password.",
tr,
user,
)
.into_response()),
@ -405,13 +439,19 @@ pub async fn ask_reset_password_post(
AskResetPasswordError::UnableSendEmail,
&form_data.email,
user,
tr,
)
}
}
}
Err(error) => {
event!(Level::ERROR, "{}", error);
error_response(AskResetPasswordError::DatabaseError, &form_data.email, user)
error_response(
AskResetPasswordError::DatabaseError,
&form_data.email,
user,
tr,
)
}
}
}
@ -419,18 +459,20 @@ pub async fn ask_reset_password_post(
#[debug_handler]
pub async fn reset_password_get(
Extension(user): Extension<Option<model::User>>,
Extension(tr): Extension<translation::Tr>,
Query(query): Query<HashMap<String, String>>,
) -> Result<Response> {
if let Some(reset_token) = query.get("reset_token") {
Ok(ResetPasswordTemplate {
user,
tr,
reset_token: reset_token.to_string(),
message: String::new(),
message_password: String::new(),
}
.into_response())
} else {
Ok(MessageTemplate::new_with_user("Reset token missing", user).into_response())
Ok(MessageTemplate::new_with_user("Reset token missing", tr, user).into_response())
}
}
@ -452,15 +494,18 @@ enum ResetPasswordError {
pub async fn reset_password_post(
State(connection): State<db::Connection>,
Extension(user): Extension<Option<model::User>>,
Extension(tr): Extension<translation::Tr>,
Form(form_data): Form<ResetPasswordForm>,
) -> Result<Response> {
fn error_response(
error: ResetPasswordError,
form_data: &ResetPasswordForm,
user: Option<model::User>,
tr: translation::Tr,
) -> Result<Response> {
Ok(ResetPasswordTemplate {
user,
tr,
reset_token: form_data.reset_token.clone(),
message_password: match error {
ResetPasswordError::PasswordsNotEqual => "Passwords don't match",
@ -481,13 +526,13 @@ pub async fn reset_password_post(
}
if form_data.password_1 != form_data.password_2 {
return error_response(ResetPasswordError::PasswordsNotEqual, &form_data, user);
return error_response(ResetPasswordError::PasswordsNotEqual, &form_data, user, tr);
}
if let common::utils::PasswordValidation::TooShort =
common::utils::validate_password(&form_data.password_1)
{
return error_response(ResetPasswordError::InvalidPassword, &form_data, user);
return error_response(ResetPasswordError::InvalidPassword, &form_data, user, tr);
}
match connection
@ -498,34 +543,39 @@ pub async fn reset_password_post(
)
.await
{
Ok(db::user::ResetPasswordResult::Ok) => Ok(MessageTemplate::new_with_user(
"Your password has been reset",
user,
)
.into_response()),
Ok(db::user::ResetPasswordResult::ResetTokenExpired) => {
error_response(ResetPasswordError::TokenExpired, &form_data, user)
Ok(db::user::ResetPasswordResult::Ok) => {
Ok(
MessageTemplate::new_with_user("Your password has been reset", tr, user)
.into_response(),
)
}
Err(_) => error_response(ResetPasswordError::DatabaseError, &form_data, user),
Ok(db::user::ResetPasswordResult::ResetTokenExpired) => {
error_response(ResetPasswordError::TokenExpired, &form_data, user, tr)
}
Err(_) => error_response(ResetPasswordError::DatabaseError, &form_data, user, tr),
}
}
/// EDIT PROFILE ///
#[debug_handler]
pub async fn edit_user_get(Extension(user): Extension<Option<model::User>>) -> Response {
pub async fn edit_user_get(
Extension(user): Extension<Option<model::User>>,
Extension(tr): Extension<translation::Tr>,
) -> Response {
if let Some(user) = user {
ProfileTemplate {
username: user.name.clone(),
email: user.email.clone(),
user: Some(user),
message: String::new(),
message_email: String::new(),
message_password: String::new(),
user: Some(user),
tr,
}
.into_response()
} else {
MessageTemplate::new("Not logged in").into_response()
MessageTemplate::new("Not logged in", tr).into_response()
}
}
@ -552,6 +602,7 @@ pub async fn edit_user_post(
State(connection): State<db::Connection>,
State(config): State<Config>,
Extension(user): Extension<Option<model::User>>,
Extension(tr): Extension<translation::Tr>,
Form(form_data): Form<EditUserForm>,
) -> Result<Response> {
if let Some(user) = user {
@ -559,6 +610,7 @@ pub async fn edit_user_post(
error: ProfileUpdateError,
form_data: &EditUserForm,
user: model::User,
tr: translation::Tr,
) -> Result<Response> {
Ok(ProfileTemplate {
user: Some(user),
@ -584,6 +636,7 @@ pub async fn edit_user_post(
_ => "",
}
.to_string(),
tr,
}
.into_response())
}
@ -591,17 +644,17 @@ pub async fn edit_user_post(
if let common::utils::EmailValidation::NotValid =
common::utils::validate_email(&form_data.email)
{
return error_response(ProfileUpdateError::InvalidEmail, &form_data, user);
return error_response(ProfileUpdateError::InvalidEmail, &form_data, user, tr);
}
let new_password = if !form_data.password_1.is_empty() || !form_data.password_2.is_empty() {
if form_data.password_1 != form_data.password_2 {
return error_response(ProfileUpdateError::PasswordsNotEqual, &form_data, user);
return error_response(ProfileUpdateError::PasswordsNotEqual, &form_data, user, tr);
}
if let common::utils::PasswordValidation::TooShort =
common::utils::validate_password(&form_data.password_1)
{
return error_response(ProfileUpdateError::InvalidPassword, &form_data, user);
return error_response(ProfileUpdateError::InvalidPassword, &form_data, user, tr);
}
Some(form_data.password_1.as_ref())
} else {
@ -621,7 +674,7 @@ pub async fn edit_user_post(
.await
{
Ok(db::user::UpdateUserResult::EmailAlreadyTaken) => {
return error_response(ProfileUpdateError::EmailAlreadyTaken, &form_data, user);
return error_response(ProfileUpdateError::EmailAlreadyTaken, &form_data, user, tr);
}
Ok(db::user::UpdateUserResult::UserUpdatedWaitingForRevalidation(token)) => {
let url = utils::get_url_from_host(&host);
@ -644,14 +697,17 @@ pub async fn edit_user_post(
}
Err(_) => {
// error!("Email validation error: {}", error); // TODO: log
return error_response(ProfileUpdateError::UnableSendEmail, &form_data, user);
return error_response(
ProfileUpdateError::UnableSendEmail, &form_data, user, tr);
}
}
}
Ok(db::user::UpdateUserResult::Ok) => {
message = "Profile saved";
}
Err(_) => return error_response(ProfileUpdateError::DatabaseError, &form_data, user),
Err(_) => {
return error_response(ProfileUpdateError::DatabaseError, &form_data, user, tr)
}
}
// Reload after update.
@ -664,10 +720,11 @@ pub async fn edit_user_post(
message: message.to_string(),
message_email: String::new(),
message_password: String::new(),
tr,
}
.into_response())
} else {
Ok(MessageTemplate::new("Not logged in").into_response())
Ok(MessageTemplate::new("Not logged in", tr).into_response())
}
}
@ -675,6 +732,7 @@ pub async fn edit_user_post(
pub async fn email_revalidation(
State(connection): State<db::Connection>,
Extension(user): Extension<Option<model::User>>,
Extension(tr): Extension<translation::Tr>,
ConnectInfo(addr): ConnectInfo<SocketAddr>,
Query(query): Query<HashMap<String, String>>,
headers: HeaderMap,
@ -683,7 +741,7 @@ pub async fn email_revalidation(
if user.is_some() {
return Ok((
jar,
MessageTemplate::new_with_user("User already exists", user),
MessageTemplate::new_with_user("User already exists", tr, user),
));
}
let (client_ip, client_user_agent) = utils::get_ip_and_user_agent(&headers, addr);
@ -705,13 +763,14 @@ pub async fn email_revalidation(
let user = connection.load_user(user_id).await?;
Ok((
jar,
MessageTemplate::new_with_user("Email validation successful", user),
MessageTemplate::new_with_user("Email validation successful", tr, user),
))
}
db::user::ValidationResult::ValidationExpired => Ok((
jar,
MessageTemplate::new_with_user(
"The validation has expired. Try to sign up again with the same email",
tr,
user,
),
)),
@ -719,6 +778,7 @@ pub async fn email_revalidation(
jar,
MessageTemplate::new_with_user(
"Validation error. Try to sign up again with the same email",
tr,
user,
),
)),
@ -726,7 +786,7 @@ pub async fn email_revalidation(
}
None => Ok((
jar,
MessageTemplate::new_with_user("Validation error", user),
MessageTemplate::new_with_user("Validation error", tr, user),
)),
}
}