Sfoglia il codice sorgente

Create route to delete a device

Lee Morgan 2 mesi fa
parent
commit
08d4fc4a82

+ 30 - 0
src/controllers/device/delete.rs

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

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

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

+ 31 - 0
src/models/device.rs

@@ -52,4 +52,35 @@ impl Device {
 
         Ok(())
     }
+
+    pub async fn delete(
+        db: &PgPool,
+        user_id: Uuid,
+        home_id: Uuid,
+        device_id: Uuid
+    ) -> Result<(), AppError> {
+        let result = sqlx::query!(
+            "DELETE FROM devices
+            WHERE id = $1
+                AND home_id = $2
+                AND EXISTS (
+                    SELECT 1
+                    FROM users_homes
+                    WHERE user_id = $3
+                        AND home_id = $2
+                        AND is_admin = true
+                );",
+            device_id,
+            home_id,
+            user_id
+        )
+            .execute(db)
+            .await?;
+
+        if result.rows_affected() == 0 {
+            return Err(AppError::forbidden("Unauthorized access to device"));
+        }
+
+        Ok(())
+    }
 }

+ 3 - 1
src/routes/device.rs

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