【问题标题】:How do I restrict writes to a document owned by a user in Firestore?如何限制对 Firestore 中用户拥有的文档的写入?
【发布时间】:2018-04-24 06:09:43
【问题描述】:

我有一些文章。

每篇文章都有一个参考字段,指向撰写该特定文章的作者的个人资料文档

经过身份验证的用户(使用 Firebase 的身份验证)将与这些配置文件相关联。

只有在当前登录用户拥有文章的情况下,我如何才能使这些文章可由当前登录的用户编辑?

在 Firestore 的文档中,有一个反复出现的例子:

service cloud.firestore {
  match /databases/{database}/documents {

    // Allows you to edit the current user document (like a user's profile).
    match /users/{userId} {
      allow read, write: if request.auth.uid == userId;
    }

    // Allows you to read/write messages as long as you're logged in (doesn't matter who you're logged in as, so theoretically you could change other peoples' messages ????).
    match /rooms/{roomId} {
      match /messages/{messageId} {
        allow read, write: if request.auth != null;
      }
    }

  }
}

如何构建和编辑某个用户拥有的文档的示例在哪里?

【问题讨论】:

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


    【解决方案1】:

    假设您有一个文件,例如owner: <uid>存储在里面,你可以这样做:

    service cloud.firestore {
      match /databases/{database}/documents {
        match /somecollection/{id} {
          allow write: if resource.data.owner == request.auth.uid;
        }
      }
    }
    

    【讨论】:

    • 我的文章文档没有owner: <uid>,它有owner: <Reference to another document>(即firestore.googleapis.com/project/xxxxxxxxx-eb000/database/(default)/documents/users/ajsidjasidjsaidjasidasj)。引用包含 uid。
    • Fwiw,我正在尝试您的建议,但它似乎不适用于参考。我怀疑我需要做一些get() 的东西,但不能让语法恰到好处...... :(
    • 在处理用户信息时,我建议您将 uid 存储为字符串,只要您出于这个确切原因想要引用所有者 - 可能有其他方法可以做到这一点,但我不是确定这将如何工作。
    • 谢谢迈克尔。显然 Firestore 不提供使用引用类型进行验证的方法(希望他们会添加这个,我已经打开了一个功能请求)...stackoverflow.com/questions/46568850/…
    猜你喜欢
    • 2018-06-27
    • 2019-12-12
    • 2023-04-01
    • 2021-08-05
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多