限制可写入路径的记录数量(参考安全规则中的其他路径)

2023-11-21

假设我的 Firebase 系列如下所示:

{
  "max":5
  "things":{}
}

我将如何使用的价值max在我的安全规则中限制数量things?

{
  "rules": {
    "things": {
      ".validate": "newData.val().length <= max"
    }
  }
}

使用现有属性是通过以下方式完成的root or parent并且非常简单。

{
  "rules": {
    "things": {
      // assuming value is being stored as an integer
      ".validate": "newData.val() <= root.child('max')"
    }
  }
}

然而,确定记录数量并强制执行比简单地编写安全规则要复杂一些:

  • 因为没有.length在一个对象上,我们需要存储存在多少条记录
  • 我们需要以安全/实时的方式更新该号码
  • 我们需要知道我们要添加的记录相对于该计数器的数量

一种幼稚的方法

假设限制很小(例如 5 条记录),一种穷人的方法是简单地在安全规则中枚举它们:

{
  "rules": {
    "things": {
      ".write": "newData.hasChildren()", // is an object
      "thing1": { ".validate": true },
      "thing2": { ".validate": true },
      "thing3": { ".validate": true },
      "thing4": { ".validate": true },
      "thing5": { ".validate": true },
      "$other": { ".validate": false
    }
  }
}

一个真实的例子

像这样的数据结构可以工作:

/max/<number>
/things_counter/<number>
/things/$record_id/{...data...}

因此,每次添加记录时,计数器都必须递增。

var fb = new Firebase(URL);
fb.child('thing_counter').transaction(function(curr) {
   // security rules will fail this if it exceeds max
   // we could also compare to max here and return undefined to cancel the trxn
   return (curr||0)+1;
}, function(err, success, snap) {
   // if the counter updates successfully, then write the record
   if( err ) { throw err; }
   else if( success ) {
      var ref = fb.child('things').push({hello: 'world'}, function(err) {
         if( err ) { throw err; }
         console.log('created '+ref.name());
      });
   }
});

每次删除记录时,计数器都必须递减。

var recordId = 'thing123';
var fb = new Firebase(URL);
fb.child('thing_counter').transaction(function(curr) {
   if( curr === 0 ) { return undefined; } // cancel if no records exist
   return (curr||0)-1;
}, function(err, success, snap) {
   // if the counter updates successfully, then write the record
   if( err ) { throw err; }
   else if( success ) {
      var ref = fb.child('things/'+recordId).remove(function(err) {
         if( err ) { throw err; }
         console.log('removed '+recordId);
      });
   }
});

现在谈谈安全规则:

{
  "rules": {
    "max": { ".write": false },

    "thing_counter": {
      ".write": "newData.exists()", // no deletes
      ".validate": "newData.isNumber() && newData.val() >= 0 && newData.val() <= root.child('max').val()"
    },

    "things": {
      ".write": "root.child('thing_counter').val() < root.child('max').val()"
    }
  }
}

请注意,这不会强制用户在更新记录之前写入 thing_counter,因此虽然适合限制记录数量,但不适合执行游戏规则或防止作弊。

其他资源和想法

如果您想要游戏级别的安全性,请查看这把小提琴,其中详细介绍了如何使用增量 ID 创建记录,包括强制实施计数器所需的安全规则。您可以将其与上述规则结合起来,以强制执行增量 id 的最大值,并确保在写入记录之前更新计数器。

另外,请确保您没有对此想得太多,并且有一个合法的用例来限制记录数量,而不仅仅是为了满足一定程度的担忧。简单地在数据结构上强制执行穷人的配额会非常复杂。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

限制可写入路径的记录数量(参考安全规则中的其他路径) 的相关文章

随机推荐