如何在安全规则中验证事务下usuarios与juegos集合的联动写入?
Firebase安全规则验证事务联动写入(Usuarios与Juegos集合)
核心思路
Firebase的事务(原子批量写入)会作为单一请求提交,安全规则可通过request.writeOperations属性获取所有待执行的写入操作。我们需要在两个集合的写入规则中,互相验证请求同时包含对方集合的合法写入,确保联动操作的完整性。
具体规则实现
1. 定义辅助函数(复用逻辑)
先创建通用函数,检查请求中是否包含指定集合的写入操作:
function hasWriteToCollection(targetCollection) { return request.writeOperations.any(operation => operation.path.segments[0] == targetCollection ); }
2. Usuarios集合写入规则
验证写入usuarios时,请求必须同时包含juegos集合的写入,还可额外验证两个文档的关联(比如游戏文档ID对应用户ID):
match /usuarios/{userId} { allow create: if hasWriteToCollection("juegos") && // 可选:验证juegos写入的文档与当前用户关联 request.writeOperations.any(operation => operation.path.segments[0] == "juegos" && operation.path.segments[1] == userId ); }
3. Juegos集合写入规则
同理,验证写入juegos时,请求必须同时包含usuarios集合的写入:
match /juegos/{gameId} { allow create: if hasWriteToCollection("usuarios") && // 可选:验证usuarios写入的文档与当前游戏关联 request.writeOperations.any(operation => operation.path.segments[0] == "usuarios" && operation.path.segments[1] == gameId ); }
进阶:验证文档内容关联
如果需要确保两个写入的文档数据逻辑一致(比如游戏文档中的用户ID与新建用户ID匹配),可以进一步检查写入的文档内容:
function hasMatchingUserGameLink(userId) { return request.writeOperations.any(operation => operation.path.segments[0] == "juegos" && operation.path.segments[1] == userId && operation.resource.data.usuarioId == userId // 验证游戏文档的用户ID字段 ); } match /usuarios/{userId} { allow create: if hasMatchingUserGameLink(userId); }
关键说明
- 事务的原子性保证:只要任一集合的写入不满足规则,整个事务会直接失败,不会出现部分写入的情况。
- 单独写入拦截:如果尝试单独写入
usuarios或juegos集合,规则会直接拒绝,符合联动写入的要求。 request.writeOperations仅对批量写入(事务、批量更新)生效,单个文档写入时该数组仅包含当前操作。
内容的提问来源于stack exchange,提问作者random
相关产品推荐
相关产品推荐

