使用Firebase功能,从没有管理员SDK的情况下从Firestore收集中获取数据

发布于 2025-01-24 03:47:30 字数 2344 浏览 0 评论 0原文

任务是在我对云功能进行API调用后,在Firestore进行CRUD操作,后来应触发Firestore功能,以在cards Collection中获取一组项目。
以下是一些规则:

  • 不需要用户身份验证
  • 它不需要拥有带有权限权限的服务帐户

“规则”背后的目的是合法操作发生在云功能中,因为它是一个授权的管理员本身(因为它们被部署到Firebase安全环境中,对吗?)。由于该计划是作为云功能托管项目,因此我们应要求我们拥有firebase-admin sdk。

到目前为止,我尝试使用firebase-functions实施相同的功能,但仅当规则不公开限制为:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /Cards/{card}{
      allow write,read: if false;
    }
  }
}

由于这起作用,但是规则是“不安全”,我只想按照云功能进行“ admin”进行这些操作。这是一些返回一系列文档的代码,即使我的数据中有可从Web GUI查看。

import { getFirestore } from "firebase-admin/firestore";
import * as admin from "firebase-admin";

const GetCard = (cardID: string)=> {
require("../../path-to-the-file.json");

  admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
  });

  getFirestore()
    .collection("Cards")
    .get()
    .then((cardsSnapshot) => {
      cardsSnapshot.forEach((card) => {
        console.log("card from collection: ", JSON.stringify(card.data()));
      });
    });
};

编辑:为什么我决定使用Adminsdk的原因,即使云功能不需要它是我遇到的错误:

Error adding document:  [FirebaseError: Missing or insufficient permissions.] {
>    code: 'permission-denied',
>    customData: undefined,
>    toString: [Function (anonymous)]
>  }

运行此代码后:

import { initializeApp } from "firebase/app";
import { collection, getDocs, getFirestore } from "firebase/firestore";

const GetCard = (cardID: string): Promise<Card> => {
  const firebaseConfig = {...CONFIGS...};
  const app = initializeApp(firebaseConfig);
  const db = getFirestore(app);

  getDocs(collection(db, "Cards"))
    .then((querySnapshot) => {
      querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
      });
    })
    .catch((e) => {
      console.error("Error adding document: ", e);
    });
};

The task is to make CRUD operations in Firestore after I make an API call to Cloud Function, which later should trigger a Firestore function to get a set of items in Cards collection.
Here are some rules:

  • There should be no user authentication needed
  • It shouldn't need to have a service account with granted permissions

The purpose behind the "rules" is to legitimate operations happening in Cloud Functions as it was an authorized admin itself (Because they are deployed to Firebase safe environment anyways right?). Since the plan is to host the project as a Cloud Function, we should be required to have firebase-admin SDK.

For so far, I tried to implement the same with firebase-functions but it only worked if the rule was not restricted publicly being as:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /Cards/{card}{
      allow write,read: if false;
    }
  }
}

enter image description here
Since this works, but the rule is "insecure" I'd like to do these operations only as "admin" would through Cloud Functions. Here is some code that returns an empty array of documents, even though I have data in it viewable from web GUI.

import { getFirestore } from "firebase-admin/firestore";
import * as admin from "firebase-admin";

const GetCard = (cardID: string)=> {
require("../../path-to-the-file.json");

  admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
  });

  getFirestore()
    .collection("Cards")
    .get()
    .then((cardsSnapshot) => {
      cardsSnapshot.forEach((card) => {
        console.log("card from collection: ", JSON.stringify(card.data()));
      });
    });
};

EDIT: the reason why I decided to use adminSDK even though Cloud Functions don't need it was the error I was getting:

Error adding document:  [FirebaseError: Missing or insufficient permissions.] {
>    code: 'permission-denied',
>    customData: undefined,
>    toString: [Function (anonymous)]
>  }

After running this code:

import { initializeApp } from "firebase/app";
import { collection, getDocs, getFirestore } from "firebase/firestore";

const GetCard = (cardID: string): Promise<Card> => {
  const firebaseConfig = {...CONFIGS...};
  const app = initializeApp(firebaseConfig);
  const db = getFirestore(app);

  getDocs(collection(db, "Cards"))
    .then((querySnapshot) => {
      querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
      });
    })
    .catch((e) => {
      console.error("Error adding document: ", e);
    });
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏雨凉 2025-01-31 03:47:30

...不使用firebase函数

没有管理员SDK

则不使用admin SDK实际上使用admin SDK。因此,它们完全绕过了Firestore安全规则:它们具有完整的访问权限(Write&amp; read),以便您数据库的所有集合。

因此,如果我正确理解,通过使用云功能,您将满足您的需求。


只是为了完成,有一个云功能的服务帐户,但它是由平台自动设置的,因此对您来说是透明的。

... without admin SDK using Firebase Functions

Actually Cloud Functions do use the Admin SDK. As such they totally bypass the Firestore security rules: they have full access rights (write & read) to all the collections of your database.

So if I correctly understand, by using Cloud Functions you will fulfill you needs.


Just to be complete, there is a service account for the Cloud Function but it is automatically set-up by the platform, so it is transparent for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文