Android应用程序中的Firebase规则验证和捕获验证失败

时间:2017-02-16 08:28:59

标签: android firebase firebase-realtime-database firebase-security

设计

  • 可以登录该应用程序的用户
  • 登录用户可以创建将存储在node下的客户,其值将是当前登录的用户ID

当前数据库值

{
  "customers" : {
    "UserId1" : {
      "custId1" : {
        "customerCode" : "thk",
        "customerLimit" : "58866",
        "customerName" : "Test New "
      },
      "custId2" : {
        "customerCode" : "thh",
        "customerLimit" : "5698",
        "customerName" : "Yeth"
      }
    },
    "UserId2" : {
      "custId3" : {
        "customerCode" : "thh",
        "customerLimit" : "5886",
        "customerName" : "Test "
      },
      "custId4" : {
        "customerCode" : "tbh",
        "customerLimit" : "58669",
        "customerName" : "New Test"
      }
    }
  }
}

以下是customersfirebase表格中当前定义的规则。

{
  "rules": {
    "customers":{
      ".read": "auth != null", 
      ".write": "auth != null", 
      "$CID":{
            "customerName":{
                ".validate": "newData.isString() && newData.val().length < 100"
            },
            "customerCode":{
                ".validate": "newData.isString() && newData.val().length<4 && !newData.exists()"
            },
            "customerLimit":{}
      }
    }   
  }
}

即使我已经为customerCode定义了一条规则,即它的值应该小于4个字符,但它允许插入5个字符。另外,如何为每个customerCode添加验证userId唯一性的验证?截至目前它有!newData.exists()但它也不起作用。

有人可以指导我朝正确的方向发展吗?

1 个答案:

答案 0 :(得分:1)

我认为您最多可以插入5个字符,因为.length的{​​{1}}从0开始,就像newData.val().lenght一样。换句话说,如果要为每个userId链接customerCode的唯一性,则应在firebase数据库中创建一个新表,如:

array

使用此模型,您可以将规则修改为:

{
  "customers": {
    "UserId1": {
      "custId1": {
        "customerCode": "customerId1",
        "customerLimit": "58866",
        "customerName": "Test New "
      },
      "custId2": {
        "customerCode": "customerId2",
        "customerLimit": "5698",
        "customerName": "Yeth"
      }
    },
    "UserId2": {
      "custId3": {
        "customerCode": "customerId3",
        "customerLimit": "5886",
        "customerName": "Test "
      },
      "custId4": {
        "customerCode": "customerId4",
        "customerLimit": "58669",
        "customerName": "New Test"
      }
    }
  }
  "customerCode": {
    "custId1": {
      "customerId1": "thh"
    }
    "custId2": {
      "customerId2": "thk"
    }
    "custId3": {
      "customerId3": "thh"
    }
    "custId4": {
      "customerId4": "tbh"
    }
  }
}

在上一个示例中,规则可能并不完美,但我确信您可以找到有关它如何适合您的应用程序的方式来查看firechat database rules。我学到了很多东西。