【问题标题】:How to access all data in a firestore database with admin approval?如何在管理员批准的情况下访问 Firestore 数据库中的所有数据?
【发布时间】:2020-07-23 22:59:30
【问题描述】:

我目前正在构建一个vuejs 网络应用程序,它使用来自firebasefirestore。基本结构是用户用数据填写应用程序,然后管理员可以查看该数据以查看他们是否有资格获得资助。我遇到的问题是,当管理员向firestore 请求信息时,它只返回一个空数组。

使用此firebase 云函数分配管理员标签:

const admin = require('firebase-admin');
admin.initializeApp();

exports.addAdminRole = functions.https.onCall((data, context) => {
  //get user and add custom claim (admin)

  return admin.auth().getUserByEmail(data.email).then(user => {
    return admin.auth().setCustomUserClaims(user.uid, {
      admin: true
    });
  }).then(() => {
    return {
      message: `Success! ${data.email} has been made an admin`
    }
  }).catch(err => {
    return err;
  });
});

我的firestore结构如下:

users
 |_user1_uid
   |_info
 |_user2_uid
    |_info

我为获取信息而拨打的电话是这样的:

db.collection('users')
  .get()
  .then(snapshot => {
     console.log(snapshot.docs)
  })

如您所见,该调用应该获取我拥有的所有文档的快照。 (例如:console.log 应该表明我有三个用户> (3) [n, n, n])。但是,返回的是一个空数组。

我的firestore 规则是这样的:

service cloud.firestore {
   match /databases/{database}/documents {

    match /users/{userId} {
        allow read, write: if request.auth.token.admin == true;
      }

    match /users/{userId}/{document=**} {
      allow create: if request.auth != null;
      allow read, write: if request.auth.token.admin == true;
      allow read, write: if request.auth.uid == userId;
      
    }
  }
}

任何关于我的管理员为何无法获取用户信息的建议或指示将不胜感激。

谢谢!

【问题讨论】:

  • 另外,如果您需要更多信息,请告诉我
  • 所以你是说 console.log() 确实被执行并打印了一个空数组?
  • 没错!我发现如果我在firestore 中手动创建一个带有自动ID 的虚拟文档,我的代码就能够获取该文档。这就是为什么我认为这可能是一个安全规则问题。
  • 安全规则要么拒绝整个查询,要么返回所有文档。没有中间立场。
  • 真的吗?那我现在就更糊涂了。因为我可以看到这些文件,但它们没有被退回。是否与 userId 是每个文档的名称这一事实有关?

标签: javascript firebase google-cloud-firestore firebase-authentication


【解决方案1】:

好的,我知道发生了什么。当我开始制作文档时,我使用的是以下代码:

db.collection('users').doc(this.uid)
  .collection('info').doc('county').set({
     county: this.county
  )}

我没有意识到的是,这使得包含this.uid 的文档成为虚拟的。如果我再努力一点,我会在 firebase 上看到此通知:

我找到了一个相对简单的解决方法,首先使用虚拟数据创建 UID 文档,然后再向其中添加实际信息,如下所示:


db.collection('users').doc(this.uid).set({
  dummy: 'dummy'
})

这解决了我的问题。感谢大家的帮助!我很感激!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-28
    • 2013-06-19
    • 2014-10-21
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    相关资源
    最近更新 更多