Cloud Firestore - 仍然收到“任何用户都可以写入您的整个数据库”错误

Ang*_*ver 3 firebase firebase-security google-cloud-firestore

我已向 Cloud Firestore 数据库添加规则,但仍然收到以下问题消息:

  • 任何用户都可以读取您的整个数据库
  • 任何用户都可以写入您的整个数据库

请参阅下面的规则。

在此输入图像描述

事实上,任何用户都可以读取和写入“用户”集合,否则我将无法登录/注册用户。如何解决问题?

谢谢

Chr*_*isO 5

当前规则的问题在于它允许任何用户读取/写入任何其他用户的用户文档。您需要对其进行更多限制才能查看文档的 userId。像这样的东西

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

    // Ensure the user is authenticated
    function userIsAuthenticated() {
        return request.auth != null && request.auth.uid != null
    }

    // Ensure the user owns the existing resource
    function userOwnsResource() {
        return userIsAuthenticated() && request.auth.uid == resource.data.userId
    }

    // Ensure the user owns the new resource
    function userOwnsNewResource() {
      return userIsAuthenticated() && request.auth.uid == request.resource.data.userId 
    }

    match /users/{userId=**} {
      allow read, update, delete: if userOwnsResource();
      allow create: if userOwnsNewResource();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

userOwnsResource检查用户是否可以访问现有资源。userOwnsNewResource检查他们是否可以为其 userId 创建新文档。显然,您可以在其他规则中重用这些函数,这很方便。