【问题标题】:Firestore Security Rules - On create, check attribute is not in another documentFirestore 安全规则 - 创建时,检查属性不在另一个文档中
【发布时间】:2018-04-24 13:34:20
【问题描述】:

我正在使用 firestore,并且有包含名为 domain 的属性的用户:

{ 
    domain: "@domain.com"
}

我目前正在使用云功能为注册用户生成一个随机域。云函数查询数据库以检查随机域是否已经存在,这会导致几秒钟的延迟。

我的问题是,如果另一个用户已经存在于 Firestore 安全规则中的该域中,是否有一种方法可以防止插入新用户,而无需查询整个数据库?

到目前为止,我已经尝试将它添加到我的安全规则中,但它允许重复:

match /databases/{database}/documents {
    match /users/{Id} {
    allow read: if true;
    allow create: if get(/databases/$(database)/documents/users/$(Id)).data.domain != request.resource.data.domain;
  }
}

知道仅使用安全规则是否可行吗?

【问题讨论】:

    标签: javascript firebase google-cloud-firestore firebase-security


    【解决方案1】:

    您无法检查某个集合是否已存在于集合中的任何 个其他文档中。如果您想一想,那是有道理的 - 这样的操作将非常昂贵。

    可以做的是检查集合中是否已经存在具有特定 ID 的文档。因此,针对您的问题类型的典型解决方案是创建一个使用域作为 ID 的集合。

    例如

    users
      user1: { domain: "@domain.com" }
      user2: { domain: "@other.com" }
    domains
      "domain.com": "user1"
      "other.com": "user2"
    

    现在您的安全规则可以检查该域是否已在 /domains 集合中声明。

    请注意,您需要使用batched write 来执行更新,因为在这种方法中/users/domains 必须始终保持同步。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-04
      • 2018-06-15
      • 2020-06-19
      • 1970-01-01
      • 2019-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多