【问题标题】:firebase multi path update and rules for each pathfirebase 多路径更新和每个路径的规则
【发布时间】:2017-11-12 14:29:10
【问题描述】:

我正在实现一个用户和事件系统。一个限制是用户一次只能主持 1 个活动。

我最初尝试通过查询events.write 规则中的events 节点来实现限制,方法是查找已经具有等于auth.uid 的userId 的事件。但我不知道该怎么做,所以我决定创建一个新节点hosts,作为查找表。它只存储当前正在举办活动的任何用户 ID。如果用户尝试创建事件,并且他们的 userId 已经存在于 hosts 中,那么这是一个错误。

规则:

{
  "rules":{
        "users":{
            "$uid":{
                ".read": "auth.uid == $uid",
              ".write": "auth.uid == $uid",
              ".validate": "newData.exists()"
          }
      },
      "hosts":{
            "$uid":{
                ".read": "true",
                //to be a host, you must be a user
              ".write": "auth.uid == $uid &&    root.child('users').hasChild(auth.uid) &&   !root.child('hosts').hasChild(auth.uid)",
              ".validate": "newData.exists()"
          }
      },
      "events":{
          "$uid":{
                ".read": "true",
                //to create an event, you must be a host
              ".write": "root.child('hosts').hasChild(auth.uid)",
              ".validate": "true"
          }
      }
  }
}

Javascript:

createEvent(form){
    var user = firebase.auth().currentUser
    var db = firebase.database();
    var newEventRef = db.ref('events').push();
    var newEvent = {}
    newEvent[uid] = form*/

    var update = {
        ['hosts/'+user.uid]: true
        update['events/'+newEventRef.key] = form
    };
    db.ref().update(update)
        .then((...args)=>{
            ...
        })
        .catch(err=>{
            ...
        })
},

更新调用的问题是它总是失败。我正在尝试同时插入hostsevents。但是eventswrite 规则要求 userId 在写入之前位于hosts,所以我想这就是它失败的原因。

我必须进行 2 次单独的更新吗? 1 将userId插入hosts,如果成功,再插入events

【问题讨论】:

    标签: javascript firebase firebase-realtime-database firebase-security


    【解决方案1】:

    在安全规则中有三个引用数据的变量:

    • data - 存在于规则位置的数据在更新之前
    • newData - 存在于规则位置的数据更新后
    • root - 存在于 thd 数据库根目录中的数据在更新之前

    因此,当您在规则中引用 root 时,您将获得更新前的数据。要获取更新的数据,您必须参考newData。由于很遗憾没有newRoot,您必须通过多次调用parent()newData 导航到所需的级别。

    曾经的例子:

      "events":{
          "$uid":{
                ".read": "true",
                //to create an event, you must be a host
              ".write": "newData.parent().parent().child('hosts').hasChild(auth.uid)",
              ".validate": "true"
          }
      }
    

    【讨论】:

    • 这帮我解决了一个 2 小时的问题,不知道 newData 的相对路径情况,非常好的和简单的解释,使用 parent() 修复:)
    猜你喜欢
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 2013-02-13
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多