遍历数据库进行验证的 Firebase 安全规则

Firebase security rules traversing through the database for validation

我在尝试以下验证规则时遇到问题:

            ".validate": "newData.val() >= now - 2000 && newData.val() >= data.parent().parent().parent().parent().parent().child('users/'+auth.uid+'/lastPostAt').val() - 2000"

以下是我的 Firebase 数据库架构的相关区域:

areas
    -> area1
        -> posts
            -> uid
                 -> post object ( has timestamp property (date) - firebase timestamp)


user
    -> uid
         -> user object ( has timestamp property (lastPostAt) - Firebase timestamp)

提交 post 时,它会更新提交 post.

的特定用户的用户对象中的 lastPostAt 时间戳 属性

我正在寻找的是一些 Firebase 规则,以确保在提交新 post 时不会存储它,除非用户在过去 2 分钟内未提交另一个 post。

我在 Whosebug 上查看了这个 post,但我想看看是否可以用我的实现来做到这一点。

在我的 post 节点的 $uid 下,我正在尝试 .validate 规则:

        "posts" : {
           "$message_id": {
                ".indexOn": "username",
                ".write": "newData.hasChildren(['date'])",
                "date" : {
                    ".validate": "newData.val() >= now - 2000 && newData.val() >= data.parent().parent().parent().parent().parent().child('users/'+auth.uid+'/lastPostAt').val() - 2000"
            }

目前,当我提交 post 时,两个时间戳是相同的,但我可以毫无延迟地保持 posting 越来越多的 posts。

如果您想在两分钟内阻止其他帖子,newData.val() 需要至少 120,000 毫秒 lastPostAt

所以你的规则应该是:

"date" : {
    ".validate": "newData.val() >= now - 2000 && newData.val() >= data.parent().parent().parent().parent().parent().child('users/'+auth.uid+'/lastPostAt').val() + 120000"
}

此外,如果您使用的是ServerValue.TIMESTAMP,您可以使用:

newData.val() === now

在规则中使用它可以防止使用任意的未来时间戳。 (如果你不使用 ServerValue.TIMESTAMP,你应该考虑使用它。)