【问题标题】:Allow only the user who owns the data to edit it in Firebase仅允许拥有数据的用户在 Firebase 中对其进行编辑
【发布时间】:2026-02-02 10:20:05
【问题描述】:

这是我的数据库的外观:

我想要的是这样的:

  • 每个人都可以添加和读取数据。
  • 只有添加数据的用户才能使用已保存为孩子的 uid 编辑/删除数据。

我试过这个,但测试后我只能添加新数据,但不能编辑或删除它作为它的所有者:

{
  "rules": {
    ".read": false,
    ".write": false,
      
    "MOREBLOCKS":{
      ".read": true,
      "$block":{
        ".write": "(!data.exists() && newData.child('uid').val() == auth.uid ) || (data.child('uid').val() == auth.uid && newData.child('uid').val() == auth.uid)"
      }
    },
  }
}

【问题讨论】:

  • 乍一看,这条规则看起来不错。您是否已经删除了|| 子句之一以查看问题出在哪里?另外:你是如何测试这不起作用的?如果它在代码中,您可以编辑您的问题以包含minimal code with which you can reproduce the problem吗?
  • 是的,我尝试了你的想法,但还没有看到好的结果。关于代码,我将所有子项放入一个列表视图并用 2 个按钮显示它们,一个用于添加新项目,另一个用于删除当前位置项目,没有特殊代码。

标签: firebase firebase-realtime-database firebase-security


【解决方案1】:

经过多次测试,我想出了以下规则,希望对您有所帮助。

{
  "rules": {
  ".read": false,
  ".write": false,
      
  "MOREBLOCKS": {
  ".read": true,  
    
  "$blocks":{
  ".write": "(!data.exists() && newData.child('uid').val() == auth.uid ) || (!newData.exists() && data.child('uid').val() === auth.uid) || (data.child('uid').val() == auth.uid && newData.child('uid').val() == auth.uid)",
      }
    },
  }
}

【讨论】:

    最近更新 更多