From 57e540f4502937e397d3145237c4d7a8e7e497e5 Mon Sep 17 00:00:00 2001 From: philipp Date: Sun, 24 Sep 2023 09:55:51 +0200 Subject: [PATCH] allow users to delete trips --- src/model/logbook.rs | 19 ++++++++++++++----- src/tera/log.rs | 22 +++++++++++++++------- 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/src/model/logbook.rs b/src/model/logbook.rs index 1480c7c..06cac5c 100644 --- a/src/model/logbook.rs +++ b/src/model/logbook.rs @@ -68,6 +68,11 @@ pub enum LogbookUpdateError { ArrivalNotAfterDeparture, } +#[derive(Debug, PartialEq)] +pub enum LogbookDeleteError { + NotYourEntry, +} + #[derive(Debug, PartialEq)] pub enum LogbookCreateError { BoatAlreadyOnWater, @@ -327,11 +332,15 @@ ORDER BY departure DESC Ok(()) } - pub async fn delete(&self, db: &SqlitePool) { - sqlx::query!("DELETE FROM logbook WHERE id=?", self.id) - .execute(db) - .await - .unwrap(); //Okay, because we can only create a Logbook of a valid id + pub async fn delete(&self, db: &SqlitePool, user: &User) -> Result<(), LogbookDeleteError> { + if user.is_admin || user.id == self.shipmaster { + sqlx::query!("DELETE FROM logbook WHERE id=?", self.id) + .execute(db) + .await + .unwrap(); //Okay, because we can only create a Logbook of a valid id + return Ok(()); + } + Err(LogbookDeleteError::NotYourEntry) } } diff --git a/src/tera/log.rs b/src/tera/log.rs index 9a1cda3..2e578f3 100644 --- a/src/tera/log.rs +++ b/src/tera/log.rs @@ -15,7 +15,10 @@ use tera::Context; use crate::model::{ boat::Boat, - logbook::{LogToAdd, LogToFinalize, Logbook, LogbookCreateError, LogbookUpdateError}, + logbook::{ + LogToAdd, LogToFinalize, Logbook, LogbookCreateError, LogbookDeleteError, + LogbookUpdateError, + }, logtype::LogType, user::{AdminUser, User, UserWithWaterStatus}, }; @@ -224,14 +227,19 @@ async fn home( } #[get("//delete")] -async fn delete(db: &State, logbook_id: i32, _adminuser: AdminUser) -> Flash { +async fn delete(db: &State, logbook_id: i32, user: User) -> Flash { let logbook = Logbook::find_by_id(db, logbook_id).await; if let Some(logbook) = logbook { - logbook.delete(db).await; - Flash::success( - Redirect::to("/log"), - format!("Logbook with ID {} successfully deleted!", logbook_id), - ) + match logbook.delete(db, &user).await { + Ok(_) => Flash::success( + Redirect::to("/log"), + format!("Logbook with ID {} successfully deleted!", logbook_id), + ), + Err(LogbookDeleteError::NotYourEntry) => Flash::error( + Redirect::to("/log"), + "Du hast nicht die Berechtigung, den Eintrag zu löschen!", + ), + } } else { Flash::error( Redirect::to("/log"),