首页 > 解决方案 > 如何设置 Firebase 安全读取规则

问题描述

我正在创建一个聊天系统,并且有一个搜索功能,如果用户的个人资料是公开的,我可以在其中搜索用户。我的firebase数据库结构如下。

users:{
     $uid1:{
          name:"John",
          created:13739373,
          type:"PRIVATE"
           },
     $uid2:{
          name:"Susan",
          created:12393930,
          type:"PUBLIC"
           },
     $uid3:{
          name:"Titan",
          created:12582938,
          type:"CLOSED"
           }
   }

所以,我为这样的用户read设置了规则。

 ".read":"data.child('type').val()==='PUBLIC' || //if user is already friend, alse allow type CLOSED"

如果类型是或(如果两个用户已经是朋友),如何为用户read完美设置规则。我无法设置规则,因为这是搜索功能。PUBLICCLOSEDread$uid

编辑:这是我的friends道路。

   friends:{
               $uid1:{
                          $uid2: 1273738,  //friend since timestamp
                          $uid3: 1274693,
                          $uid4: 1284869,
                         ...
                    }
           }

Edit2: PUBLIC每个人都可以看到,PRIVATE没有人可以看到/搜索,CLOSED只有朋友可以看到。

标签: firebasefirebase-realtime-databasefirebase-security

解决方案


您必须更新的 Firebase 实时规则是,

"users": {
      "$user_id":{ 
        ".read": "data.child('type').val() == 'PUBLIC' || (data.child('type').val() == 'CLOSED' && auth != null && root.child('friends').child($user_id).child(auth.uid).val() > 0 ) || (data.child('type').val() == 'PRIVATE' && auth != null && $user_id == auth.uid ) "
}

推荐阅读