firebase 努力让我的Firestore规则正确-要么用户可以看到所有用户的数据或没有,我错在哪里了?

2cmtqfgy  于 2023-08-07  发布在  其他
关注(0)|答案(1)|浏览(68)

以下是在Firestore中访问的数据供参考:


的数据
我觉得问题出在第二列的EventID中,但以下是我目前的规则:

rules_version = '2';     ​

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

    match /Events/{docId} {     
      allow read, write: if request.auth != null;

    }

  }

}

字符串
这一个工作,但显然,只要用户被授权,他们可以看到每个人的数据。
这是我尝试的,我认为应该工作:

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
  
    match /Events/{docId} { 
      allow read, write: if request.auth != null && request.auth.uid == resource.data.userId;
    }
  }
}


如果我的理解正确的话,应该只显示在EventID数据中找到其userID的用户的数据。
我的怀疑是,要么我的道路是错误的,要么我误解了Firestore是如何阅读这些规则的。
编辑:下面是调用数据的代码

body: StreamBuilder(
        stream: FirebaseFirestore.instance
            .collection("Events")
            .orderBy("date", descending: false)
            .snapshots(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              itemCount: snapshot.data!.docs.length,
              itemBuilder: (context, index) {
                final post = snapshot.data!.docs[index];
                return EventCard(
                    titleEvent: post['eventTitle'],
                    locationEvent: post['eventLocation'],
                    dateEvent: post['date'],
                    timeHour: post['timeHour'],
                  timeMinute: post['timeMinute'],
                );
              },
            );
          } else if (snapshot.hasError) {
            return Center(
              child: Text('Error${snapshot.error}'),
            );
          }
          return const Center(
            child: CircularProgressIndicator(),
          );
        },
      ),

e0uiprwp

e0uiprwp1#

在没有看到您的代码的情况下,很难确定,但我最初的猜测是您的代码试图读取整个Events集合。请记住,规则不是过滤器。相反,这些规则只是进行检查,以确保您的代码请求的文档数不会超过允许访问的数量。
因此,您的规则不会过滤集合,只返回用户拥有的文档,而是拒绝请求更多文档的读取操作。解决方案是use a query只请求当前用户的文档。
在Flutter代码中,这将是:

FirebaseFirestore.instance
  .collection("Events")
  .orderBy("date", descending: false)
  .where("userId", isEqualTo: FirebaseAuth.instance.currentUser.uid) // 👈
  .snapshots()

字符串

相关问题