【问题标题】:How to make rules for chat app using flutter and firebase如何使用 Flutter 和 Firebase 为聊天应用制定规则
【发布时间】:2021-10-26 02:46:54
【问题描述】:

我正在用颤振编写聊天应用程序,我不知道如何在 firebase 上设置规则,这样只有群聊中的 2 个用户可以读写。这就是我在 firebase 上存储消息的方式。

String date = DateTime.now().millisecondsSinceEpoch.toString();
groupId = userId-anotherId
var ref = FirebaseFirestore.instance
          .collection('messages')
          .doc(groupId)
          .collection(groupId)
          .doc(date);
      FirebaseFirestore.instance.runTransaction((transaction) async {
        transaction.set(ref, {
          "senderId": userId,
          "receiverId": anotherId,
          "timestamp": date,
          'content': msg,
          "type": 'text',
        });
      });

感谢您的帮助。

【问题讨论】:

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


    【解决方案1】:
    • 从前端联系数据库并不是最安全的方式。
    • 如果您制作这个应用程序是为了学习,那很好。
    • 但对于生产应用程序,您应该在后端添加类似这样的自定义逻辑,并将您的前端与该 API 连接。
    • 类似这样的东西。 Flutter app --> API --> YOUR_LOGIC --> DATABASE

    【讨论】:

    • 对不起,我对此知之甚少。我必须把它放在应用程序或firebase控制台中吗?如何?感谢您的宝贵时间。
    【解决方案2】:

    您需要members 的集合才能进行群聊。这样您就可以很容易地检查规则,只要成员 uid 位于 groupChats/{groupID}/members/{id} 的路径下。你甚至可以为 firestoe 规则创建一个函数,如下所示:

     //Checks if user is member of group
        function isMember(groupID) {
          return  get(/databases/$(database)/documents/groupChats/${groupID}/members/$(request.auth.uid)).data==true
        }
    

    数据库结构是:

    -
    groupChats
       --group1
           members
             --userUid1
             --userUid2
       --group2
           members
             --userUid2
             --userUid4
    
    

    您可以使用boolean 或您想要的任何数据。

    【讨论】:

    • 感谢您的回复。尽管您的回答中有一些细节,但我很难理解。成员集合的结构将如何。在你的回答中,还有groupChats,和我使用的groupId一样吗?谢谢。
    • 我已经用结构更新了答案。 groupId 应该与您使用的相同。群聊应该保存在根路径下。
    • 对不起,我尝试了好几件事都没有成功。我回到了以前的规则,它不再起作用了。我得到这个错误:侦听查询(目标=查询(消息/ aS17OHPBRgbAknBLJbTWvhz8Oyr1 - HLRS7zmA7uNUzy6kF6hUPlmGn0i2 / aS17OHPBRgbAknBLJbTWvhz8Oyr1 - HLRS7zmA7uNUzy6kF6hUPlmGn0i2为了通过-timestamp, - 的名称的); limitType = LIMIT_TO_FIRST)失败:状态:{代码= PERMISSION_DENIED,描述=缺少权限或权限不足。,原因=空}。这是以前有效的规则。匹配 /messages/{userId}/{document=**} { 允许写入,读取:如果 request.auth.uid != null; }
    • 对不起,这是我的错误,我在谷歌控制台中丢失了一个大括号。我的旧规则正在奏效。我仍然不知道如何执行您所说的规则。这是旧规则:match /messages/{userId}/{document=} { allow write, read:if request.auth.uid != null}** 但它不安全。
    • 你有什么不明白的。在评论中定义群组聊天系统的结构和安全规则并不是一件容易的事。
    【解决方案3】:

    解决方案非常简单。我在优酷上看到的。 enter link description here

    这是安全规则: 匹配 /messages/{groupChatId}/{document=**} { 允许写入,读取:如果 groupChatId.split(" - ") 中的 request.auth.uid }

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 2019-12-17
      相关资源
      最近更新 更多