node.js - Firestore : Different rules for creating and updating documents

标签 node.js firebase google-cloud-firestore firebase-security

我有一个特定的需求,即允许我的用户创建匹配特定结构的 Firestore 文档,但不允许这些相同的用户在创建时更新该结构。

简而言之,我希望我的用户能够创建新文档但不能更新它们。

我定义了以下安全规则:

service cloud.firestore {
  match /databases/{database}/documents {
    function isAuthenticated() {
      return request.auth.uid != null
    }

    match /conversations/{conversationId} {
      function isParticipant() {
        return resource.data.participants[request.auth.uid] == true
      }

      function NewConversation() {
        // One of the participants must be the current user
        return request.resource.data.participants[request.auth.uid] == true
      }

      allow read, delete: if isAuthenticated() && isParticipant()
      allow create: if isAuthenticated() && NewConversation()
      // allow update: if isAuthenticated() && NewConversation()
    }
  }
}

然而,事实证明,无论我如何尝试创建文档,我总是得到告密者 permission-denied错误。我很确定我要保存的文档包含 participants将当前用户的 Id 作为键映射到 true ,正如规则所期望的那样。

如果我也允许 update,我可以成功创建文档通过取消注释第三条规则来操作。

这是 Firestore 错误还是我误解了什么?

documentation (以及 createupdate 操作的明确分离)似乎表明这是可能的。

为了完整起见,这是我提出的未通过测试的客户端请求:

it('allows creating new conversations', async function() {
  // clients.primary is a Firestore instance authenticated with
  // the primary user used below as a key
  const doc = await clients.primary.collection('/conversations').add({
    participants: {
      [users.primary.uid]: true,
      [users.secondary.uid]: true,
    },
  })
})

最佳答案

尝试:

function isAuthenticated() {
  return request.auth != null && request.auth.uid != null
}

如果您的请求不包含“auth”,firebase 将崩溃并可能返回权限违规。

关于node.js - Firestore : Different rules for creating and updating documents,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48911815/

相关文章:

firebase - 我怎么知道 Firebase 云消息传递 token 已停用?

javascript - Angular 种子克隆 "npm start"命令错误

android - 更新到新 SDK 后与 Firebase 数据库失去连接

node.js - 整个存储帐户的 Azure 共享访问签名

swift - 获取 "Type ' FieldValue' has no member 'arrayUnion' "when adding element to Firestore array

google-cloud-firestore - Firestore 增量字段值

node.js - Firebase 无效的文档引用。文档引用必须有偶数个段

firebase - 在 Firestore 上设置数据时将字符串转换为映射

javascript - Expressjs - 全局对象

javascript - CoffeeScript 覆盖基本类型,更改值