【问题标题】:Firebase Security Rules for users to read and write their own dataFirebase 安全规则供用户读写自己的数据
【发布时间】:2021-06-10 14:23:15
【问题描述】:

我正在使用 Flutter 和 Firebase,并提出了以下 Firebase 结构。

房间和用户集合:

我希望用户能够读取和写入他们的数据。 我写了以下规则:

为了获得房间,我在 Flutter 中使用了以下代码:

     Stream<List<RoomModel>> getRooms() {
        var user = firebaseAuth.currentUser;
        return _db
            .collection('rooms')
            // .where("userId", "==", user.uid)
            .snapshots()
            .map((snapshot) => snapshot.docs
                .map((document) => RoomModel.fromFirestore(document.data()))
                .toList());
      }

房间模型:

    // import 'package:firebase_auth/firebase_auth.dart';
    
    class RoomModel {
      final String roomId;
      final double price;
      final String location;
      final String userId;
    
      RoomModel(this.roomId, this.price, this.location, this.userId);
    
      Map<String, dynamic> toMap() {
        // final firebaseAuth = FirebaseAuth.instance;
        // var user = firebaseAuth.currentUser;
        return {
          'roomId': roomId,
          'price': price,
          'userId': userId,
          'location': location,
        };
      }
    
      RoomModel.fromFirestore(Map firestore)
          : roomId = firestore['roomId'],
            price = firestore['price'],
            location = firestore['location'],
            userId = firestore['userId'];
    }

但是,我仍然得到了所有房间,包括其他用户的房间。

后来我还想阅读所有房间。我该怎么做?

【问题讨论】:

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


    【解决方案1】:

    我会添加子集合。 users/USERID/rooms/。通过添加索引来获取所有房间使用collectionGroup

     var myUserId = firebase.auth().currentUser.uid;
     var myReviews = firebase.firestore().collectionGroup('room')
       .where('userId', '==', myUserId);
     myReviews.get().then(function (querySnapshot) {
        // Do something with these rooms!
     })
    

    在此处阅读更多内容。

    https://firebase.google.com/docs/firestore/query-data/indexing?authuser=0 https://firebase.googleblog.com/2019/06/understanding-collection-group-queries.html

    【讨论】:

    • .where('userId', '==', myUserId);我如何在 .dart 文件本身中使用它?这弹出错误。上面我写的代码是在 dart 中的。
    • 还有一件事,你的想法就像它的 SQL 数据库,这就是你感到困惑的原因。想想 userCollection 有 RoomSubCollection 也有 roomCollection 有 userSubcollection,所以当你调用 user/userID/rooms/ 时,它会给你一个房间里的文档集合,房间集合 roomID 你会得到哪些用户在那里。有时您需要进行批量写入以同时在用户集合中添加一个房间和在房间集合中添加一个用户。忘记外键,firestore 中没有加入
    • 我同意上述cmets。您的数据模型需要重组以添加子集合。这将有助于您制定安全规则并访问数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 2016-09-13
    • 2019-01-10
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多