Firebase安全规则 - 仅允许读取用户的内容

时间:2015-01-26 21:28:39

标签: angularjs firebase angularfire firebase-security firebasesimplelogin

我的Firebase数据结构有点像这样:

+ tasks
  + task_id
    + title
    + user
    + ...
+ users
  + ...

来自前端(使用AngularJS和AngularFire(加上内置的SimpleLogin)) - 当登录用户创建任务时,用户的uid(例如simplelogin:2)被放入任务的用户部分创建

当用户登录时,他们只能使用以下命令查看其任务:

$firebase( ref.orderByChild('user').equalTo(User.uid) );

下一步是保护数据,这是我正在努力的地方。我试过了:

"tasks": {
   ".indexOn": ["user", "order"],
   ".write": "auth != null",
   ".read": "auth != null && data.child('user').val() == auth.uid",
     "$task": {
        "title": {
           ".validate": "newData.isString() && newData.val().length <= 1000"
        },
        "completed": {
        },
        "time_added": {
            ".validate": "newData.val() <= now"
        },
        "order": {
        },
        "user": {
            ".validate": "newData.val() != null && newData.val() == auth.uid"
        },
        "$other": {
           ".validate": false
        }
     }
  }

还有:

"tasks": {
     "$task": {
       ".indexOn": ["user", "order"],
       ".write": "auth != null",
       ".read": "auth != null && data.child('user').val() == auth.uid",

        "title": {
           ".validate": "newData.isString() && newData.val().length <= 1000"
        },
        "completed": {
        },
        "time_added": {
            ".validate": "newData.val() <= now"
        },
        "order": {
        },
        "user": {
            ".validate": "newData.val() != null && newData.val() == auth.uid"
        },
        "$other": {
           ".validate": false
        }
     }
  }

但是我得到了:

  

错误:permission_denied:客户端无权访问所需数据。

我哪里错了?

1 个答案:

答案 0 :(得分:4)

tasks集合没有user个孩子。每个特定的任务都有一个user个孩子。因此,您需要将读取规则向下移动一级:

"tasks": {
    "$task_id" {
        ".read": "auth != null && data.child('user').val() == auth.uid",
    }

另见以下示例:https://www.firebase.com/docs/security/guide/user-security.html