Firebase安全规则仅读取特定项目 [英] Firebase security rules to read specific items only

查看:56
本文介绍了Firebase安全规则仅读取特定项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚接触Firebase,感到自己完全被数据库规则迷住了.我需要允许用户读取所有者字段等于特定值的项目.

I am new to using Firebase and feel myself completely lost with DB rules. I need to allow users to read items that have owner field equal to specific value.

这是我拥有的记录结构:

This is the records structure I have:

{
  "books" : {
    "-LKwbZsfy55d24kwX4tf" : {
      "description" : "Adventures",
      "title" : "Captain Donsak",
      "owner" : "b7bS753Hvc0fmQ24Jnc"
    },
    "-LKwc1Xna07nequDtpF6" : {
      "description" : "History",
      "title" : "World War II",
      "owner" : "hLoOnnv4883Vhvm9Vt4"
    },
    "-LKwi4qcsqbgvZPdhCXp" : {
      "description" : "Adventures",
      "title" : "Sea Wolf",
      "owner" : "umV4hFm96vpdwBytx63"
    }
  }
}

我尝试了几种规则选择,包括遵循规则(firebase docs中提供了这些规则),但是无论如何,当我应用任何这些规则时,它都会返回0个项目.

I've tried several options of rules, including following (these were provided in firebase docs), but in any case it returns 0 items when I apply any of these rules.

{
  "rules": {     
    "books": {
        ".read": "data.child('owner').val() === 'umV4hFm96vpdwBytx63'",
        ".write": "auth != null"   
    }
  }
}


{
  "rules": {     
    "books": {
      "$uid":{
        ".read": "root.child('owner').val() == 'umV4hFm96vpdwBytx63'",
        ".write": "auth != null"   
      }        
    }
  }
}

如果我只指定

".read": "auth != null"  

它返回所有记录,但这不是我所需要的.

it returns all records, but this is not what I need.

我使用一个简单的js命令来读取数据:

I use a simple js command to read the data:

const itemsRef = firebase.database().ref('books'); 

基本上,我需要使用安全规则来过滤数据,但这是不可能的,正如下面的RenaudTarnec所述.因此,我将不得不使用js对其进行过滤:

Basically what I need is to filter data using security rules, but this is not possible as stated by RenaudTarnec below. So I'll have to use js to filter it:

const itemsRef = firebase.database().ref('books').orderByChild('owner').equalTo(owner); 

请告知可能出什么问题. 谢谢.

Please advise what could be wrong. Thank you.

推荐答案

实际上"Firebase规则不是过滤器",请参见

Actually "Firebase rules are not filters", see https://firebase.google.com/docs/database/security/securing-data#rules_are_not_filters

这意味着,要获取此数据,您必须使用与您的安全规则对齐"的查询.

It means that, to fetch this data, you have to use a query that is "aligned" with your security rules.

类似于JavaScript中的以下内容,请参见 https://firebase. google.com/docs/database/web/lists-of-data

Like the following in JavaScript, see https://firebase.google.com/docs/database/web/lists-of-data

var query = firebase.database().ref('books').orderByChild('owner').equalTo('umV4hFm96vpdwBytx63');

这篇关于Firebase安全规则仅读取特定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆