Firebase私聊模式和规则

时间:2015-04-01 00:40:20

标签: firebase firebase-security

我正在尝试在我正在处理的应用中设置私人聊天功能,并且我在解决数据异常化/正确设置规则方面遇到了一些麻烦。

在做了一些阅读之后,我意识到规则是全有或全无,所以使用过滤规则不是一种选择。

我在纸上概述了我的基本想法,并将其粘贴在下面。基本上会有两条主要路线,用户和聊天。

用户只是一个键控列表,每个键与经过身份验证的用户匹配。然后在列表的每个成员中,我将只有每个聊天,所述用户被列为键。

对于聊天路线,我会列出所有聊天记录。

现在有了规则。

用户只能在密钥与其uid匹配的列表中读取其数据。对于写作我不那么自信。我想我必须让任何有身份验证的人写信,否则开始聊天的用户无法通过在用户路线的聊天列表中播放聊天ID来通知其他人新聊天。

对于聊天规则,只有在用户通过身份验证且聊天密钥位于用户路径中的数据内时,才允许读取和写入。

看起来我是否正朝着正确的方向前进?

users:{

  user1:{
    chat1: true,
    chat2: true
    ...
  },

  user2:{
    chat1: true,
    chat3: true
    ....
  }
}


chats:{
  chat1:{
    lastUpdate: timestamp,
    messages:{
      0:{
        from: user1
        to: user2,
        message: some message
      }
      ...
    }
  }
}

rules:{
  .read: false,
  .write: false,

  users:{
    $user_id:{
      .read: auth != null && $user_id == auth.uid,
      .write: auth != null //not sure here as other users need to write here if the start a new chat
    }
  },

  chats:{
    $chat_id: {
      .read: auth != null && root.child('users').child($chat_id).contains(auth.id),
      .write: auth != null && root.child('users').child($chat_id).contains(auth.id)
    }
  }
}

1 个答案:

答案 0 :(得分:0)

我一直在玩这个,所以这里有一个选项(绝不是我建议这是最好的方法)

规则:

   {
      "rules":{
        ".read": false,
        ".write": false,

        "users":{
          "$user_id":{
            ".read": "auth != null && $user_id == auth.uid",
            ".write": "auth != null" //not sure here as other users need to write here if the start a new chat
          }
        },

        "chats":{
          "$chat_id": {
            ".read": "auth != null && root.child('users').child(auth.uid).child('chats').hasChild($chat_id)",
            ".write": "auth != null && (root.child('users').child(auth.uid).child('chats').hasChild($chat_id) || !data.exists())"
          }
        }
      }
    }

then for users I have a structure like this:

    users:{
      someUserId:{
        chats:{ //embedded a second level so I can save firebaseObj.someUserId to get the keys more easily
          someChatId: true //and repeat for each chat 

        }
      }
    }

聊天记录是这样的:

chats:{
  someChatId:{
    //chat data
  }
  //more chat objects
}

如果有更好的方法可以做到这一点,我不会感到惊讶,但至少这可能是那些陷入困境的人的开始。如果/当我得到更好的解决方案时,我会记得更新这个。

相关问题