Procházet zdrojové kódy

Create route to delete a home.

Lee Morgan před 2 měsíci
rodič
revize
262fcf1b32

+ 13 - 1
src/app_error.rs

@@ -32,6 +32,12 @@ pub enum AppError {
 
     #[error("Unauthorized")]
     Auth,
+
+    #[error("Invalid UUID")]
+    InvalidUuid(#[from] uuid::Error),
+
+    #[error("{0}")]
+    Forbidden(String)
 }
 
 impl ResponseError for AppError {
@@ -42,7 +48,9 @@ impl ResponseError for AppError {
             AppError::Database(_) => StatusCode::INTERNAL_SERVER_ERROR,
             AppError::JsonDeserializationError(_) => StatusCode::BAD_REQUEST,
             AppError::NotFound(_) => StatusCode::NOT_FOUND,
-            AppError::Auth => StatusCode::UNAUTHORIZED
+            AppError::Auth => StatusCode::UNAUTHORIZED,
+            AppError::InvalidUuid(_) => StatusCode::BAD_REQUEST,
+            AppError::Forbidden(_) => StatusCode::FORBIDDEN
         }
     }
 
@@ -72,4 +80,8 @@ impl AppError {
     pub fn not_found(msg: &str) -> Self {
         AppError::NotFound(msg.into())
     }
+
+    pub fn forbidden(msg: &str) -> Self {
+        AppError::Forbidden(msg.into())
+    }
 }

+ 21 - 0
src/controllers/home/delete.rs

@@ -0,0 +1,21 @@
+use actix_web::{HttpResponse, HttpRequest, web, delete};
+use sqlx::PgPool;
+use uuid::Uuid;
+use serde_json::json;
+use crate::{
+    app_error::AppError,
+    auth::user_auth,
+    models::home::Home
+};
+
+#[delete("/home/{home_id}")]
+pub async fn route(
+    db: web::Data<PgPool>,
+    path: web::Path<String>,
+    req: HttpRequest
+) -> Result<HttpResponse, AppError> {
+    let user = user_auth(&db, &req).await?;
+    let home_id = Uuid::parse_str(&path.into_inner())?;
+    Home::delete_one(&db, home_id, user.id).await?;
+    Ok(HttpResponse::Ok().json(json!({"success": true})))
+}

+ 1 - 0
src/controllers/home/mod.rs

@@ -1 +1,2 @@
 pub mod create;
+pub mod delete;

binární
src/models/.home.rs.kate-swp


+ 20 - 0
src/models/home.rs

@@ -33,4 +33,24 @@ impl Home {
 
         Ok(())
     }
+
+    pub async fn delete_one(db: &PgPool, home_id: Uuid, user_id: Uuid) -> Result<(), AppError> {
+        let result = sqlx::query!(
+            "DELETE FROM homes
+            USING users_homes
+            WHERE homes.id = $1
+                AND users_homes.user_id = $2
+                And users_homes.home_id = homes.id",
+            home_id,
+            user_id
+        )
+            .execute(db)
+            .await?;
+
+        if result.rows_affected() == 0 {
+            Err(AppError::forbidden("Invalid permissions to delete home"))
+        } else {
+            Ok(())
+        }
+    }
 }

+ 3 - 1
src/routes/home.rs

@@ -1,8 +1,10 @@
 use actix_web::web;
 use crate::controllers::home::{
-    create
+    create,
+    delete
 };
 
 pub fn config(cfg: &mut web::ServiceConfig) {
     cfg.service(create::route);
+    cfg.service(delete::route);
 }