【发布时间】: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=>{
...
})
},
更新调用的问题是它总是失败。我正在尝试同时插入hosts 和events。但是eventswrite 规则要求 userId 在写入之前位于hosts,所以我想这就是它失败的原因。
我必须进行 2 次单独的更新吗? 1 将userId插入hosts,如果成功,再插入events?
【问题讨论】:
标签: javascript firebase firebase-realtime-database firebase-security