如何使用 Firebase 规则仅授予某些叶节点权限 [英] How to use Firebase rules to only give permission to certain leaf nodes

查看:29
本文介绍了如何使用 Firebase 规则仅授予某些叶节点权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的基本问题是如何设置 Firebase 规则以仅允许从其父节点访问某些叶节点?

My basic question is how do you setup Firebase rules to only allow access certain leaf nodes from their parent?

假设我有如下所示的数据:

Lets say I have data that looks like this:

root: {
  posts: {
    post1: {
      user: "foo",
      post: "this is a post",
      restricted: false
    },
    post2: {
      user: "bar",
      post: "this is another post",
      restricted: true
    },
    post3: {
      user: "bar",
      post: "this is my final post",
      restricted: false
    }
  }
}

我想 $bind 到帖子节点并获取允许该用户获取的所有帖子.我可能希望管理员访问所有帖子,但非管理员只能访问 post1 和 post3.

I want to $bind to the posts node and get all the posts which that user is allowed to get. I might want the admin to access all of the posts but non-admins to only be able to access post1 and post3.

注意:我使用 angularFire 的 $bind 来同步节点.

Note: I'm using angularFire's $bind to synchronize nodes.

我不相信这是可能的,但我希望能够像这样设置我的规则:

I don't believe this is possible but I would like to be able to set up my rules kinda like this:

{
  "rules": {
    "posts": {
      ".read": "auth.admin || $post.hasChild('restricted').val() !== true",
      "$post": {
      }
    }
  }
}

其他用户是如何做到这一点的?谢谢.

How are other users accomplishing this? Thanks.

推荐答案

你可以使用 data.hasChild 表达式来实现:

You can use the data.hasChild expression to achieve this:

{
  "rules": {
    "posts": {
      ".read": "auth.admin || data.hasChild('restricted').val() !== true"
    }
  }
}

但是,这不是推荐的方法,在实践中也行不通.安全规则不适合基于访问过滤数据 - 您会在控制台中看到权限被拒绝错误,因为 angularFire 会尝试从/blog 读取所有帖子,但会失败.

However, this is not the recommended approach and won't work in practice. Security rules are not a good fit for filtering data based on access - you'll see permission denied errors in the console because angularFire will try to read all the posts from /blog and it will fail.

相反,每个用户都应该知道他们可以访问哪些帖子,并且只能直接获取这些帖子.您可以使用 push()(或 angularFire 中的 $add)来生成随机的帖子 ID 并设置安全规则,这样您就可以在知道帖子 ID 的情况下访问数据,例如.

Instead, each user should know which posts they have access to and only fetch those directly. You can use push() (or $add in angularFire) to generate random post IDs and set the security rules such that you can access the data if you know the post ID, for example.

这篇关于如何使用 Firebase 规则仅授予某些叶节点权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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