From 237ef6250d5d6adaf95fdf8be345dd7c5bfe300d Mon Sep 17 00:00:00 2001 From: traxys Date: Mon, 9 Oct 2023 13:20:02 +0200 Subject: [PATCH] Allow to delete aliases --- src/main.rs | 38 ++++++++++++++++++++++++++++++++++++++ templates/home.html | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 54834b0..50dc178 100644 --- a/src/main.rs +++ b/src/main.rs @@ -910,6 +910,43 @@ async fn alias_add( Ok(Redirect::to("/")) } +#[tracing::instrument(skip(state))] +async fn alias_delete( + state: State>, + User(user): User, + Form(alias): Form, +) -> Result { + let mut tx = state.db.begin().await?; + + let can_use_alias = sqlx::query!( + "SELECT COUNT(*) FROM emails WHERE id = $1 AND mail = $2", + user, + alias.mail + ) + .fetch_one(&mut *tx) + .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!("DELETE FROM alias WHERE alias = $1", alias.mail) + .execute(&mut *tx) + .await?; + + sqlx::query!("DELETE FROM emails WHERE mail = $1", alias.mail) + .execute(&mut *tx) + .await?; + + tx.commit().await?; + + Ok(Redirect::to("/")) +} + #[derive(Deserialize, Debug)] struct Password { password: SecretString, @@ -977,6 +1014,7 @@ async fn main() -> color_eyre::Result<()> { .route("/list/delete", post(delete_list)) .route("/password", post(set_password)) .route("/alias/add", post(alias_add)) + .route("/alias/delete", post(alias_delete)) .fallback(page_not_found) .with_state(Arc::new(AppState { db, diff --git a/templates/home.html b/templates/home.html index 516e6d9..1a5cbfa 100644 --- a/templates/home.html +++ b/templates/home.html @@ -134,7 +134,7 @@ {{ self::delete_modal(modal_id="aliasDelete" ~ alias_idx ~ loop.index, confirm_text="Delete alias '" ~ alias ~ "' (for '" ~ mail.primary ~ "')", action="/alias/delete", - payload=["alias", alias]) + payload=["mail", alias]) }} {% endfor %}