From e983079d8e545ba44aadb69cad798867d0ac0256 Mon Sep 17 00:00:00 2001 From: traxys Date: Tue, 29 Aug 2023 21:43:23 +0200 Subject: [PATCH] Handle adding new aliases --- src/main.rs | 40 ++++++++++++++++++++++++++++++++++++++++ templates/home.html | 2 +- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index b41ad2b..a7af419 100644 --- a/src/main.rs +++ b/src/main.rs @@ -641,6 +641,45 @@ async fn add_mail( } } +#[derive(Deserialize, Debug)] +struct AddRecipient { + alias: String, + recipient: String, +} + +#[tracing::instrument(skip(state))] +async fn add_recipient( + state: State>, + User(user): User, + Form(add): Form, +) -> Result { + let can_use_alias = sqlx::query!( + "SELECT COUNT(*) FROM emails WHERE id = $1 AND mail = $2", + user, + add.alias + ) + .fetch_one(&state.db) + .await? + .count + .expect("count should not be null") + > 0; + + if !can_use_alias { + tracing::error!("User is not authorized to use this alias"); + return Err(Error::InternalError); + } + + sqlx::query!( + "INSERT INTO alias_recipient (mail, recipient) VALUES ($1, $2) ON CONFLICT DO NOTHING", + add.alias, + add.recipient + ) + .execute(&state.db) + .await?; + + Ok(Redirect::to("/")) +} + #[tokio::main] async fn main() -> color_eyre::Result<()> { color_eyre::install()?; @@ -673,6 +712,7 @@ async fn main() -> color_eyre::Result<()> { .route("/", get(home)) .route("/mail/delete", post(delete_mail)) .route("/mail/add", post(add_mail)) + .route("/alias/recipient/add", post(add_recipient)) .fallback(page_not_found) .with_state(Arc::new(AppState { db, diff --git a/templates/home.html b/templates/home.html index b0b635d..9c48e49 100644 --- a/templates/home.html +++ b/templates/home.html @@ -140,6 +140,7 @@
+