【问题标题】:Firebase Cloud Firestore Security Rules With MapFirebase Cloud Firestore 安全规则与地图
【发布时间】:2020-11-27 04:36:12
【问题描述】:

我对 Cloud Firestore 的安全规则有理解上的问题。我不明白如何使用可以访问其数据的地图来检查用户的 uid。

提前感谢您的回答

这是我尝试过的规则

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    //TEST ONLY
    //match /{document=**} {
    //  allow read, write;
    //}
    
    // match logged in user doc in users collection
    match /users/users/{userId} {
      allow create : if request.auth.uid != null;
      allow read : if request.auth.uid == userId;
      
      match /{anything=**} {
        allow read, write : if request.auth.uid == userId;
      }
    }
  }
}

这里是我如何使用 Firestore 的示例:

// Collection reference
final CollectionReference _usersCollection = Firestore.instance.collection('users');

Stream<List<double>> get existingRecord {
  return _usersCollection.document('users').snapshots()
    .map(_existingRecordListFormSnapshot);
}

List<double> _existingRecordListFormSnapshot(DocumentSnapshot snapshot) {
  ...
  double tips = snapshot.data['$uid']['data']['$year']['$month']['$week']['$day']['Tips'];
}

我的问题是我只希望用户可以访问他们的数据。为此,我制作了一个“用户”文档,其中包含一个“用户”地图,其中包含所有用户数据,并以其唯一的 uid 命名。而且我无法设置安全规则,以便只有用户可以访问他的数据。

图表如下所示: 用户 / 用户 / [{userID}, {userID}, ...]

我不知道我是否清楚,但我真的找不到如何只允许用户在用户数据映射中访问他们的数据

【问题讨论】:

  • 在 Stack Overflow 上,不要提供代码图片。将代码复制到问题中并对其进行格式化,以便于阅读、复制和搜索。对于安全规则,还需要显示与该规则匹配的客户端。如果不了解旨在允许或拒绝的特定查询,规则本身并没有任何意义。
  • 我更新了我的帖子,抱歉问题模糊了
  • 我仍然不清楚您要做什么,但您不能使用匹配通配符在文档中查找字段。匹配只能引用文档。您可能希望每个用户数据位于不同的文档中,并使用他们的 UID 作为文档 ID。
  • 我会这样做的!非常感谢您的帮助!

标签: google-cloud-firestore firebase-security


【解决方案1】:

不要将所有用户放在同一个文档中,而是应该为每个用户拥有一个文档,(文档的名称与 Firestore uid 相同,以简化规则)。

那么你的规则可以很简单:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {   
    // match logged in user doc in users collection
    match /users/{userId} {
      allow create : if request.auth.uid != null;
      allow read : if request.auth.uid == userId;
      
      match /{anything=**} {
        allow read, write : if request.auth.uid == userId;
      }
    }
  }
}

【讨论】:

  • 我会这样做的!非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-16
  • 2018-06-19
  • 2020-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
相关资源
最近更新 更多