get() 和 getAfter() 之间的 Firebase 安全规则区别

标签 firebase google-cloud-firestore firebase-security

在文档中,它说:

Using the get() and exists() functions, your security rules can evaluate incoming requests against other documents in the database.

这对我来说没问题,这个例子对我来说很有意义:

service cloud.firestore {
  match /databases/{database}/documents {
    match /cities/{city} {
      // Make sure a 'users' document exists for the requesting user before allowing any writes to the 'cities' collection
      allow create: if exists(/databases/$(database)/documents/users/$(request.auth.uid))

      // Allow the user to delete cities if their user document has the
      // 'admin' field set to 'true'
      allow delete: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true
    }
  }
}

然后它说

For writes, you can use the getAfter() function to access the state of a document after a transaction or batch of writes completes but before the transaction or batch commits.

我可能还没有完全理解这个概念。我的问题是:

  1. 为什么事务或批量写入必须使用getAfter(),我们可以只使用get()吗?
  2. 如果您必须使用 getAfter() 进行事务或批量写入,这是否意味着您仍然需要 get() 进行正常写入?它们如何同时存在?

谢谢。

最佳答案

首先,请记住,在数据库中的任何内容被写入更改之前,写入的安全规则就会生效。这就是安全规则能够安全有效地拒绝访问的方式,而无需回滚任何已经发生的写入。

您引用的文档表明 getAfter 可用于检查数据库的内容在记录整个事务的状态之后(在内存中的一种“暂存”环境中),但是在事务实际更改数据库之前,对所有人可见。这与 get 不同,因为 get 只查看数据库的实际内容,在事务最终提交之前。简而言之,getAfter 使用整个事务或批处理的整个分段写入,而 get 使用数据库的实际现有内容。

如果 get 适合您的情况,则您不必使用 getAfter

getAfter 在您需要检查可能在事务或批处理中更改的其他文档时很有用,并且仍然有机会通过不符合规则来拒绝整个事务或批处理。因此,例如,如果在单个事务中写入的两个文档必须具有某些共同的字段值才能保持一致,则需要使用 getAfter 来验证两者之间的相等性。 get 在这里没有帮助,因为它不知道事务中尚未写入的其他文档的任何信息。

另一方面,如果您的规则需要检查事务中的文档是否未更改现有文档中的 a 字段(即不是正在检查的当前文档),get 将有必要在事务写入之前获取该值。

关于get() 和 getAfter() 之间的 Firebase 安全规则区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55320248/

相关文章:

javascript - Cloud Firestore 优化了数据库设置,可实现最少的读/写操作

java - 选择要更新的位置时如何正确使用Firestore ID

flutter - 为 flutter android 项目添加 google gms 服务时出错并且厌倦了搜索答案

firebase - 将 Firestore 安全规则集 () 转换为字符串值

Firebase:协作应用程序的安全规则

java - 如何因 Firebase 存储中的文件大小限制规则而出现拒绝上传错误

Firebase 报告选项

java - 如何使用 Firestore 查询的结果填充微调器?

ios - 在 Swift 中从 Firebase 检索数据

Firebase 托管/功能 - 如何获得真实的主机名(域名)