firebase 删除属于用户的数据

firebase delete data belongs to a user

我有一个电影应用程序。人们可以对电影发表评论。

我检查过:

https://www.firebase.com/docs/security/guide/securing-data.html#section-data-variables

https://www.firebase.com/docs/security/guide/user-security.html

但我找不到答案。

comments {
  550: {
     UKs5lg...: {
           comment: "this is comment",
           userId: "Jkulsç122doasdjk"
    },
     WfyG5Hsl...: {
           comment: "this is comment2",
           userId: "Jkulsç122doasdjk"
    }
},
 1694: {
     Ki5Uydmk...: {
           comment: "movie 2 comment 1",
           userId: "Jkulsç122doasdjk"
    },
     Kovx9ox...: {
           comment: "movie 2 comment2",
           userId: "Jkulsç122doasdjk"
    }
}

}

在数据库中,550、1694等数字是电影的id号。正如您所见,每部电影都有具有唯一 ID 的评论。每个评论都有 comment 和 userId(发送此评论的用户的 uid)属性。我删除了评论,但我希望用户可以删除自己的评论。所以我想设置如下规则:

{
  "rules": {
    "comments": {
      "$movieId": {
                ".read": true,
                ".write": ??????,
      }
  }
}
}

我应该写什么安全规则而不是问号?我想这样写;

".write" : "!data.exists() || (!newData.exists() && data.child(blabla+ 'userId').val() === auth.uid)"

但我不会写,因为我不知道我小时候应该如何获得唯一的 ID。

您需要将规则下推到您想要执行操作的级别。既然你说每个用户应该只能删除他们自己的评论,那么执行这个的规则应该在评论上:

{
  "rules": {
    "comments": {
      ".read": true,
      "$movieId": {
        "$commentId": {
          ".write": "!data.exists() || (!newData.exists() && data.child('userId').val() === auth.uid)",
        }
      }
    }
  }
}