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

时间:2019-03-27 09:03:53

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

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

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

请参阅以下规则。

enter image description here

实际上,任何用户都可以读写“用户”集合,否则我将无法登录/注册用户。该如何解决呢?

谢谢

1 个答案:

答案 0 :(得分:2)

当前规则的问题在于,它允许任何用户读取/写入任何其他用户的用户文档。您需要进一步限制它以查看文档的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();
    }
  }
}

userOwnsResource检查用户是否可以访问现有资源。 userOwnsNewResource检查他们是否可以为其userId创建一个新文档。您显然可以方便地在其他规则中重复使用这些功能。