如何使用 Firebase 中的安全规则限制 (Flutter) 字符串 min/max 长度

How to limit (Flutter) string min/max length with security rules in Firebase

我正在使用 Firestore 数据库,现在我正在尝试在构建许多没有安全规则的页面后添加安全规则。那绝对是一个巨大的错误。我已经查看了很多文档并观看了一堆 Firebase 安全规则视频,这些视频都很清楚,但作为初学者我仍然需要指导。我还回顾了 SO 线程,这些线程帮助我达到了这一点。

我的目标是让客户端验证和服务器端验证在用户创建新帐户并添加用户名时至少需要 3 个字符,最多允许 20 个字符。当他们更新他们的用户名时,同样的规则应该适用。这是数据库的图像。

我的安全规则是:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
    allow read, write, update: if request.auth != null
    && request.auth.uid == userId
    && resource.data.username.length >= 3
    && resource.data.username.length <= 30
    && resource.data.undername is string;
    }

在 Rules Playground 中,我收到一条错误消息:

错误 运行 模拟 — 错误:simulator.rules 第 [10] 行,第 [28] 列。空值错误。

并且在控制台中我收到类似的错误消息:

状态{code=PERMISSION_DENIED, description=缺少或权限不足。, cause=null}

我不知道我的规则代码哪里出了问题。任何帮助将不胜感激。谢谢

您必须检查 request.resource.data which contains incoming data and not resource.data which holds existing data from the document. Also try using size() 而不是 .length 来检查字符串长度:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{uid} {
      allow read, write, update: if request.auth != null
        && request.auth.uid == userId
        && request.resource.data.username.size() >= 3
        && request.resource.data.username.size() <= 30
        && request.resource.data.undername is string;
    }
  }
}

例如,如果文档中用户名的当前值为 'Jim',而您正尝试将其更新为 'James',则 resource.data.username.size() 的值将为 3 (现有名称的长度)和 request.resource.data.username.size() 将是 5(新名称的长度)。这是您应该测量的新名称的长度,因此您需要使用 request.resource.