我想限制我的非高级用户每天只发布一个帖子。高级用户没有限制。我不清楚如何设置我的数据库规则。目前,我只验证了用户可以发布到数据库。注意 我想写入"添加帖子"节点
我的数据库 JSON 如下所示:
User :
uid:
verified : true
premium : false
还有我的规则:
{
"rules": {
"AddPost": {
".read": "auth != null",
".write":
"root.child('Users').child(auth.uid).child('verified').val() == true"
}
,"Users": {
".read": "auth != null",
".write": "auth != null"
}
,"FavoritedBusinesses": {
".read": "auth != null",
".write": "auth != null"
}
,"Geolocs": {
".read": "auth != null",
".write": "auth != null"
}
,"ReviewPost": {
".read": "auth != null",
".write": "auth != null"
}
,"Views": {
".read": "auth != null",
".write": "auth != null"
}
}
}
我的解决方案因此,在弗兰克斯的指导下,我能够将一些规则串在一起。作为基本规则,每个用户都必须经过验证,因此我将其置于"验证"条件中,因为它是一个共同点。然后在首先写入时,我们检查用户是否是高级用户,如果它返回 false,然后我们检查我们在上一篇文章中存储的时间戳的最后一个时间戳。但是,如果第一个条件失败,则意味着用户实际上是高级的,应该被允许发布。
新数据库规则
".write": "root.child('Users').child(auth.uid).child('premium').val()
=== false && (newData.parent().child('Users').child(auth.uid).child('lastPostStamp').val() === now) && (newData.parent().child('Users').child(auth.uid).child('lastPostStamp').val() > root.child('Users').child(auth.uid).child('lastPostStamp').val() + 24*60*60*1000) || root.child('Users').child(auth.uid).child('premium').val() === true ",
".validate": "root.child('Users').child(auth.uid).child('verified').val() === true"
正如Doug评论的那样,这是可能的:
- 要求用户每次写帖子时,他们也会将时间戳写入已知位置(例如
/Users/$uid/last_post_timestamp
)。 - 验证他们是否只能将
ServerValue.TIMESTAMP
写入该位置。 - 验证他们只能在
/Users/$uid/last_post_timestamp
中的当前值至少为一天前时编写新帖子。
因此,您需要在新帖子的规则中加入以下内容:
(newData.parent().child('Users').child(auth.uid).child('last_post_timestamp').val()
=== now) &&
(newData.parent().child('Users').child(auth.uid).child('last_post_timestamp').val()
> root.child('Users').child(auth.uid).child('last_post_timestamp').val() + 24*60*60*1000)