Firestore安全规则:如何通过安全规则强制在Firestore文档中创建的字段数? [重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

我无法使用Firestore安全规则限制创建的文档中的字段数。 https://firebase.google.com/docs/firestore/security/rules-structure

我的用户文档中有7个字段。我想限制任何文件CREATE尝试我期望的字段数。我已将数字设置为100,这显然不是我发送给故意创建失败的内容。我希望100失败,但事实并非如此。

match /users/{uid} {
  // Applies to writes to nonexistent documents
  allow create: if request.resource.data.size() == 100;
}

我还尝试将size属性直接放在资源对象上但没有成功。

allow create:if request.resource.size()== 100;

这是尝试CREATE操作的代码;

const DEFAULT_systemRole = 'User';
  const DEFAULT_disabled = false; 
  // creates up a static sentinel value to be set on the Firestore server
  var serverTimestamp = admin.firestore.FieldValue.serverTimestamp()
  admin.firestore().collection('users').doc(req.body.uid).set({

    // sent from client
    usernameSlug: req.body.usernameSlug,
    username: req.body.username,
    email: req.body.email,

    // set only here on server
    systemRole: DEFAULT_systemRole,
    disabled: DEFAULT_disabled,
    dateModified: serverTimestamp,
    dateCreated: serverTimestamp,

  }).then(function() {
    console.log("Successfully created FireStore user");
  }).catch(function(error) {
    console.log("Error creating user:", error);
    throw(error)
  }) 
node.js google-cloud-firestore firebase-security-rules
2个回答
0
投票

我刚刚在模拟器中测试了这个,它似乎对我有用:

enter image description here

因此上述安全规则需要2个字段。

当我用一个字段(在屏幕截图中)编写一个新文档时,写入失败。

当我将规则更改为只需要一个字段时,相同的写入成功。


0
投票

根据设计,我碰巧使用的Firebase Admin sdk似乎不支持Firebase安全规则。相反,Firebase管理员sdk BYPASSES所有安全规则。所以看起来我会将所有调用移动到Firebase Admin sdk并简单地使用以下规则锁定Firestore数据库,以防止客户端黑客攻击的任何可能性。

  match /users/{uid} {

    allow read, write: if false;

  }

以下帖子也发现了同样的情况; How to get Firestore rules working with service accounts

© www.soinside.com 2019 - 2024. All rights reserved.