Firebase Firestore 无需身份验证即可获取用户文档

时间:2021-03-27 06:42:46

标签: firebase flutter google-cloud-firestore firebase-security

我正在尝试使用 firebase 在 flutter 中构建应用程序。我不想让用户对他/她进行 Firebase 身份验证。

我只希望他们使用他们的电话号码作为密码。这意味着他/她可以输入电话号码来查看他们的数据而无需身份验证。没有电话号码,他们无法读取数据。(也没有 OTP)。

现在我在firestore规则中有这个,所以任何拥有电话号码的人都可以查看数据。

 function isUserRef(field) { 
  return field in resource.data
    && resource.data.mobile == /customers/document/$(request.resource.data.mobile)
}

match /customers/{document=**} {
  allow read : if isUserRef(request.resource.data.mobile);
}

请求资源数据包含如下。

User{
"id" : null,
"mobile" : "7878445778"
}

但是上面的规则仍然与基于他/她的手机号码的文档不匹配。我根本不想让用户进行身份验证。这是一个简单的应用程序,数据不是问题。

感谢任何帮助!!谢谢。

2 个答案:

答案 0 :(得分:1)

不清楚您的数据库是如何设置的或您如何传递电话号码,但这里有一种更简单的方法可以帮助您指导。

设置您的数据库,其中电话号码是客户的 ID。如果这不可能,请创建一个 phoneToCustomers 集合,用于将电话号码与客户进行匹配。

示例 1:电话号码作为客户 ID

假设您的客户 ID 是他们的电话号码:

{
  "customers": {
    "7878445778": {...},
    "1231231234": {...}
  }
}

通过这个简单的规则,你可以完成你想要的:

match /customers/{phone} {

  // Allow anyone with the phone number to access this document
  allow get: if true;

  // Can't list all customers
  allow list: if false;
}

示例 2:客户 ID 查找表

假设您的数据库如下所示:

{
  "customers": {
    "abc123": {...},
    "xyz987": {...}
  },
  "phoneToCustomers": {
    "7878445778": "abc123",
    "1231231234": "xyz987"
  }
}

这些规则会阻止用户查询您的客户或电话号码,但允许在用户知道 ID 的情况下检索文档。

match /customers/{customerId} {

  // Allow anyone with the customer ID to access this document
  allow get: if true;

  // Can't list all customers
  allow list: if false;
}

match /phoneToCustomers/{phone} {

  // Allow anyone with the phone number to access this document
  allow get: if true;

  // Can't list all customers
  allow list: if false;
}

然后您需要 get() /phoneToCustomers/7878445778 来获取客户 ID,然后第二个 get() 来检索 /customers/<customerId> 处的客户数据。

答案 1 :(得分:0)

要针对数据库中的其他文档评估传入请求,您可以使用 get()exists() 请求,它们需要完全指定的文档路径。

请记住,函数可以访问在您定义它们的范围内定义的变量。

此函数检查是否存在命名为用户电话号码的文档:

function isUser(request) { 
  let requestData = request.resource.data.mobile;
  let docExists = exists(/databases/$(database)/documents/customers/$(requestData)); 
return docExists;

此函数检查文档是否有包含用户电话号码的字段:

function isUser(document, request) {
  let requestData = request.resource.data.mobile;
  let fieldExists = get(/databases/$(database)/documents/customers/$(document)).data.mobile == requestData;
return fieldExists;

如您所见,此用例还需要将 document 通配符传递给函数。

使用第一个函数,您的安全规则将是:

match /customers/{document} {
  allow read : if isUser(request);
}

使用第二个功能,您的安全规则将是:

match /customers/{document} {
  allow read : if isUser(document, request);
}