首页 > 解决方案 > 用户只能在 Firestore 中访问他/她的文档

问题描述

我正在通过设置 Firestore 规则而苦苦挣扎。

根据屏幕截图,我收集了具有动态文档 ID 的用户。

在此处输入图像描述

我正在尝试为用户设置仅访问他/她的文档的规则。

FbId 是 facebook id(因为它是我的应用程序中的身份验证方式)

userId 是firebase id(不确定是否重要保存)

这是我目前的规则:

match /users/{document=**} {
  allow read, write: if normalUser();
  }

  function normalUser() {
  return request.auth.token.firebase.sign_in_provider == "facebook.com"
  && request.auth.uid != null;
}

此规则授予对整个集合的经过身份验证的用户的访问权限。

如何设置此规则?如果有什么我需要改变结构?

更新:我不想更改用户集合的文档 ID 以匹配用户 ID,因为我有另一个集合,用户可以有多个文档;所以这个解决方案并不适合一切。

谢谢

标签: google-cloud-firestorefirebase-security

解决方案


使用用户的 Firebase 身份验证 UID 作为文档的 ID 会容易得多。Facebook UID 不会在安全规则中可用。

如果您使用 Firebase UID,则可以编写类似于文档中的规则以实现基于用户的安全性。单击并阅读上面写着“另一种常见模式是确保用户只能读取和写入自己的数据”的地方。这可能是您想要做的。

service cloud.firestore {
  match /databases/{database}/documents {
    // Make sure the uid of the requesting user matches name of the user
    // document. The wildcard expression {userId} makes the userId variable
    // available in rules.
    match /users/{userId} {
      allow read, update, delete: if request.auth.uid == userId;
      allow create: if request.auth.uid != null;
    }
  }
}

推荐阅读