Firebase rule that works like a filter [duplicate]

跟風遠走 提交于 2020-01-15 11:57:07

问题


When using .read with a true rule on the Users node, I give access to some authenticated user read every user listed on that tree. I need just some of then.

I need some rule that works like a filter. So on getting User/ path, this authenticated user will get an users array of only those that have permission path like this $uid > permission > auth.uid = true.

{
  "rules": {
    "Users" : {
      ".read": true,
      "$uid" : {
        ".read" : "(auth != null && auth.uid === $uid) || root.child('Users/'+ $uid+'/permission/'+ auth.uid).val() == true",
        ".write" : false
      }
    },
  }
}

回答1:


You can't use rules as filters, they are atomic to the specific branch you are trying to read/write.

Your outer read rule is giving access to the whole /Users branch. Removing it and having the userId that you want to read you will get the behavior you are expecting. So, unfortunately this will work only when reading with ref.child("Users").child(targetUserId).once....

{
  "rules": {
    "Users" : {
      "$uid" : {
        ".read" : "(auth != null && auth.uid === $uid) || root.child('Users/'+ $uid+'/permission/'+ auth.uid).val() == true",
        ".write" : false
      }
    }
  }
}

If you want to have, in one single call, the list of user ids that the authenticated user has access to I recommend you to actually save the accessible users inside /User/userId instead of having the ones that can read. And your rules will slightly change.

 {
      "rules": {
        "Users" : {
          "$uid" : {
            ".read" : "(auth != null && auth.uid === $uid) || root.child('Users/'+ auth.uid +'/accessibleUsers/'+ $uid).val() == true",
            ".write" : false
          }
        }
      }
    }

Additionally, this can get complex when scaling so, depending on what you plan for you application, you should be thinking of having this accessible users list in a separate branch (outside of Users).



来源:https://stackoverflow.com/questions/38687594/firebase-rule-that-works-like-a-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!