14

我正在努力为我的应用程序设置适当的安全规则。

我正在编写的应用程序的概述是,用户可以使用电子邮件和密码注册自己(我正在使用 Firebase 简单登录,效果很好)。登录后,用户可以添加他们的待办事项。

angularFire('https://<firebase>/firebaseio.com/todos', $scope, 'todos');

要针对任何用户添加新的 todo,我只需更新 todos 模型。

$scope.todos.push({
   user: 'a@b.com',
   todo: 'What to do?'
});

我用来限制非注册用户添加任何待办事项的这个安全规则:

  {
    "rules": {
      ".read": true,
      "todos": {
        ".write": "auth != null",
        ".validate": "auth.email == newData.child('user').val()"
      }
    }
  }

但它甚至不允许经过身份验证的用户写入任何数据并引发错误,“FIREBASE WARNING: on() or once() for /todos failed: Error: permission_denied.”

但是如果我在模拟器中添加以下数据,那么它会按预期工作。

{user: "a@b.com", todo: 'What to do?'} 

这是日志:

/todos:.write: "auth != null"
    => true
/todos:.validate: "auth.email == newData.child('user').val()"
    => true
/todos:.validate: "auth.email == newData.child('user').val()"
    => true

Write was allowed.
4

1 回答 1

17

push将具有随机生成的 ID(按时间顺序)的新子代添加到/todos. 所以,newData不是指向你认为它指向的东西。将您的规则更改为:

{
  "rules": {
    ".read": true,
    "todos": {
      "$todoid": {
        ".write": "auth != null",
        ".validate": "auth.email == newData.child('user').val()"
      }
    }
  }
}

更新:上述规则有效,但 angularFire 当前将整个数组写回服务器,导致身份验证失败。您可以改用 angularFireCollection,只写回新的 TODO,如下所示:

$scope.todos = angularFireCollection(new Firebase(URL));

$scope.todos.add({user: 'a@b.com', todo: 'What to do?'});

当新项目添加到列表中时,优化 angularFire 的行为存在一个未解决的问题,但与此同时,您可以使用 angularFireCollection 来获得正确的行为。

于 2013-09-09T18:09:06.223 回答