云Firestore的Firebase规则

时间:2019-08-07 14:50:15

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

设置Firebase的乘法规则。

带有3个数据库集合的示例。

Cloud Firestore

在国家的Firebase集合上,应允许所有用户读写。

在火力交加的汽车收藏中,只有管理员可以写作。

在飞机的火力基地收藏中,所有经过身份验证的用户都可以写信。

无效的文档: https://firebase.google.com/docs/rules/basics#cloud-firestore

如何使用正确的语法设置规则?

    // All public to include countries
    service cloud.firestore {
       match /databases/{database}/documents {
         match /{document=**} {
           allow read: if true ; 
           allow write: if true ;
         }
       }

     // check cars collection
     match /databases/{database}/documents/Cars {
        // For attribute-based access control, Check a boolean `admin` attribute
        allow read: if true ;
        allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true;

    }

     // check airplanes collection
      match /databases/{database}/documents/Airplanes {
        // Allow only authenticated content owners access
        match /{database}/{userId}/{documents=**} {
          allow read: if true ; 
          allow write: if request.auth.uid == userID
        }
      }
    }

1 个答案:

答案 0 :(得分:1)

您的规则中有一些错误。

  1. 您有一条声明,允许每个人编写每个文档。如果有多个match语句与当前请求匹配,并且其中一个语句允许该请求,则最终判决为ALLOW。删除以下内容:
match /{document=**} {
    allow read: if true ; 
    allow write: if true ;
}
  1. Firestore区分大小写。为避免错误,请使用一致的命名对流,例如camelCase或pascal_case。

  2. 您必须在match语句的末尾添加一个文档match变量

这应该有效:

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

        match /users/{userId} {
            allow read: if true;
            allow write: if request.auth != null && request.auth.uid == userId;
        }

        match /cars/{carId} {
            allow read: if true ;
            allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true;
        }

        match /airplanes/{airplane} {
            allow read: if true ; 
            allow write: if request.auth != null ;
        }
    }
}