diff --git a/src/main.rs b/src/main.rs index 6a1d092..67c752a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -686,6 +686,42 @@ async fn add_mail( } } +async fn add_alias( + state: State>, + User(user): User, + Form(add): Form, +) -> Result { + let has_mail = sqlx::query!( + "SELECT COUNT(*) FROM emails WHERE id != $1 AND mail = $2", + user, + add.mail + ) + .fetch_one(&state.db) + .await? + .count + .expect("count should not be null"); + + if has_mail != 0 { + Ok(Redirect::to(&format!( + "/?{}", + serde_urlencoded::to_string(&HomeQuery { + user_error: Some(UserError::MailAlreadyExists) + }) + .expect("could not generate query") + ))) + } else { + sqlx::query!( + "INSERT INTO emails (id, mail, alias) VALUES ($1, $2, true) ON CONFLICT DO NOTHING", + user, + add.mail + ) + .execute(&state.db) + .await?; + + Ok(Redirect::to("/")) + } +} + #[tracing::instrument(skip(state))] async fn add_recipient( state: State>, @@ -790,6 +826,7 @@ async fn main() -> color_eyre::Result<()> { .route("/", get(home)) .route("/mail/delete", post(delete_mail)) .route("/mail/add", post(add_mail)) + .route("/alias/add", post(add_alias)) .route("/alias/recipient/add", post(add_recipient)) .route("/alias/recipient/delete", post(delete_recipient)) .route("/alias/delete", post(delete_alias)) diff --git a/templates/home.html b/templates/home.html index 0aa6ad1..a851067 100644 --- a/templates/home.html +++ b/templates/home.html @@ -154,5 +154,14 @@ {% endfor %} + {{ self::add_modal(modal_id="addAlias", + add_button="Add new alias", + button_classes="mt-2", + add_text="Add new alias", + action="/alias/add", + input_name="mail", + payload=[], + prefill=true) + }} {% endblock content %}