标签: firebase-admin

为什么我在 python firebase-admininitialize_app() 上收到此错误?

当我尝试连接 google firebase 实时数据库时,出现此错误:

ValueError: The default Firebase app already exists. This means you called 
initialize_app() more than once without providing an app name as the second argument. In 
most cases you only need to call initialize_app() once. But if you do want to initialize 
multiple apps, pass a second argument to initialize_app() to give each app a unique name.
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

cred = credentials.Certificate('firebase-sdk.json')

firebase_admin.initialize_app(cred, {
'databaseURL': 'https://test-139a6-default-rtdb.firebaseio.com/'
})
Run Code Online (Sandbox Code Playgroud)

python firebase firebase-admin

5
推荐指数
1
解决办法
4346
查看次数

将 nextjs monorepo 项目与 lerna 一起使用时,无法解析 firebase-admin/lib 中的“fs”

我有一个 Lerna MonoRepo 项目设置。

喜欢

root/
   lerna.json
   packgae.json
   package.lock.json
   packages/
       app1 - Create react app (with firebase sdk dependency)
       app2 - Next Js app (with firebase-admin dependency)
       components - shared react components.
Run Code Online (Sandbox Code Playgroud)

当我尝试构建下一个 js 应用程序时,会发生以下错误。

Blockquote ModuleNotFoundError:找不到模块:错误:无法解析“root-project/node_modules/firebase-admin/lib”中的“fs”。

reactjs lerna monorepo firebase-admin next.js

5
推荐指数
1
解决办法
2888
查看次数

如何使用模块化 Firebase v9 初始化 Firebase 管理?

我正在使用 firebase admin 与自定义后端(next.js api 路由)进行Firestore交互auth

Firebase 最近宣布他们将采用模块化的 tree-shaking 包。

如何重构下面的代码以利用 tree-shaking firebase 模块?

import * as firebaseAdmin from "firebase-admin";

if (!firebaseAdmin.apps.length) {
  const adminCredentials = {
    credential: firebaseAdmin.credential.cert({
      projectId: env.fbProjIdPublic,
      clientEmail: env.fbClientEmail,
      privateKey: JSON.parse(env.fbPvtKey),
    }),
    databaseURL: env.fbDbUrlPublic,
  };

  firebaseAdmin.initializeApp(adminCredentials);
}

export default firebaseAdmin;
Run Code Online (Sandbox Code Playgroud)

到目前为止我还没有找到替代品firebaseAdmin.credential.cert

node.js es6-modules firebase-admin

5
推荐指数
1
解决办法
2464
查看次数

Next.js 中间件模块未找到:无法解析“fs”

_middleware当我尝试初始化 Firebase admin V9 时,在 Next.js 文件中出现此错误。有人知道如何解决这个问题吗?

./node_modules/@google-cloud/storage/build/src/bucket.js:22:0
Module not found: Can't resolve 'fs'
Run Code Online (Sandbox Code Playgroud)

../../firebase/auth-admin

import * as admin from "firebase-admin";

if (!admin.apps.length) {
  admin.initializeApp({
    credential: admin.credential.cert({
      projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
      clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
      privateKey: process.env.FIREBASE_ADMIN_PRIVATE_KEY,
    }),
  });
}

const firestore = admin.firestore();

const auth = admin.auth();

export { firestore, auth };
Run Code Online (Sandbox Code Playgroud)

在我的中调用它_middleware

import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
import { auth } from "../../firebase/auth-admin";

export default async function authenticate(
  req: NextRequest,
  ev: NextFetchEvent
) {
  const token = …
Run Code Online (Sandbox Code Playgroud)

javascript firebase-admin next.js

5
推荐指数
1
解决办法
2万
查看次数

如何使用 Firebase 管理 SDK 链接电子邮件/密码登录方法?

我正在尝试使用 firebase admin SDK 来链接电子邮件/密码登录方法。

根据 firebase 文档,我们可以将用户链接到特定的提供商https://firebase.google.com/docs/reference/admin/node/firebase-admin.auth.updaterequest.md#updaterequestprovidertolink


基于我正在使用的:

await admin
           .auth()
           .updateUser(user.uid, {
                providerToLink: {
                    uid: user.email,
                    email: user.email,
                    displayName: user.displayName,
                    providerId: 'password',
                },
            })
            .catch((error: any) => {
                console.error(`${error}`);
            });
Run Code Online (Sandbox Code Playgroud)

它应该将电子邮件/密码登录方法链接到特定用户,但它不是返回错误

  • 代码=auth/invalid-provider-id
  • 消息=The providerId must be a valid supported provider identifier string.

当providerId等于facebook.com或时它按预期工作google.com

问题

我是否应该使用另一个提供程序 ID 来链接电子邮件/密码登录方法?

我是否应该使用另一种方法来链接电子邮件/密码登录方法?


节点版本:12

firebase-管理员:9.12.0

node.js firebase firebase-authentication firebase-admin

5
推荐指数
1
解决办法
1324
查看次数

Go admin sdk 忽略 Firebase 存储模拟器

我正在尝试为我的 firebase 项目设置存储模拟器。我正在使用 Go 管理 sdk。然而,尽管遵循了记录的流程,但它似乎被忽略了。

应用程序初始化:

func App(ctx context.Context) (*firebase.App, error) {
    opt := option.WithCredentialsFile("firebase-service-account.json")
    config := firebase.Config{
        StorageBucket: "<my-project-id>.appspot.com",
    }
    app, err := firebase.NewApp(ctx, &config, opt)
    if err != nil {
        return nil, fmt.Errorf("error initializing app: %v", err)
    }
    return app, nil
}
Run Code Online (Sandbox Code Playgroud)

启动时加载的 .env 文件:

FIRESTORE_EMULATOR_HOST="localhost:8081"
FIREBASE_STORAGE_EMULATOR_HOST="localhost:9199"
GCLOUD_PROJECT="my-project-id"
Run Code Online (Sandbox Code Playgroud)

export FIREBASE_STORAGE_EMULATOR_HOST="localhost:9199"我还尝试通过运行:和来手动设置这些 export GCLOUD_PROJECT="my-project-id"

但是,当写入默认存储桶时,我的 blob 出现在实际的 firestore 控制台中进行存储,而不是存储模拟器中。

GCLOUD_PROJECT从我的服务帐户 json 文件中提取了该值,project_id特别是该字段。还确认这9199是存储正在运行的端口。

除了设置这些之外FIREBASE_STORAGE_EMULATOR_HOSTGCLOUD_PROJECT我还缺少其他东西吗?

go firebase-tools firebase-storage firebase-admin

5
推荐指数
1
解决办法
699
查看次数

Firebase-admin Firestore node.js 与模块化 v9 js sdk 共享逻辑

升级到 Web v9 模块化 sdk 时,共享 Firestore api 逻辑(在管理 Node.js 和 js Web 之间)的推荐方法是什么?我之前的做法是仅提供数据库(和deleteField)(如果它被无服务器函数使用)。

// admin db init
import { FieldValue, getFirestore } from "firebase-admin/firestore"
const FSAdmin = createFirebaseAdminApp(options);
const db = getFirestore(FSAdmin)
Run Code Online (Sandbox Code Playgroud)

这似乎不再有效,因为如果您尝试将getFirestore(FSAdmin)与 v9 docRef 一起使用doc(db, collectionName, documentID),它会给您一个错误:

FirebaseError:预计 collection() 的第一个参数是 CollectionReference、DocumentReference 或 FirebaseFirestore

javascript node.js firebase firebase-admin google-cloud-firestore

5
推荐指数
1
解决办法
532
查看次数

使用 Firebase 在 TypeScript 中导入 AuthError

使用 Firebase 时,有没有办法检查 TypeScript 中的错误是否属于“AuthError”类型。

我有一个 Https Callable 函数,它有一个 try/catch 块,其中包含以下内容:

try{
    await admin.auth().getUser(data.uid); // will throw error if user does not exist
    await admin.auth().deleteUser(data.uid);
} catch (error) {
    if(error instanceof AuthError) { // error here
        if (error.code === "auth/user-not-found") {
            logger.error(`Error: auth/user-not-found, Given user ID does not exist in Firebase Authentication`);
            throw new https.HttpsError("not-found", "Given user ID does not exist in Firebase Authentication");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我的 IDE 中的 if 语句会出现错误:

'AuthError' 仅指类型,但在此处用作值。ts(2693)

我正在使用import { AuthError } from …

firebase typescript firebase-authentication google-cloud-functions firebase-admin

5
推荐指数
1
解决办法
1325
查看次数

Firebase 凭据作为 Python 环境变量:无法反序列化关键数据

我正在使用该库开发带有 Firestore 实时数据库的 Python Web 应用程序firebase_admin。Firestore 密钥采用包含 10 个变量的 .json 文件形式。但是,我想将其中一些变量存储为环境变量,这样它们就不会公开可见。因此,我不使用 Firebase SDK .json 文件,而是使用该文件的元素创建自己的字典。字典看起来像这样,所有内容都是直接从 .json 文件复制的:

my_credentials = {
    "type": "service_account",
    "project_id": "bookclub-b2db5",
    "private_key_id": os.environ.get("PRIVATE_KEY_ID"),
    "private_key": os.environ.get("PRIVATE_KEY"),
    "client_email": os.environ.get("CLIENT_EMAIL"),
    "client_id": os.environ.get("CLIENT_ID"),
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": os.environ.get("AUTH_PROVIDER_X509_CERT_URL"),
    "client_x509_cert_url": os.environ.get("AUTH_PROVIDER_X509_CERT_URL")
}
Run Code Online (Sandbox Code Playgroud)

我已将私钥设置为PRIVATE_KEY环境变量。私钥大致是这样的(这里的字符是组成的):

"-----BEGIN PRIVATE KEY-----\nEW8nYP9T840Sb8tQMi\nhZ(...MORE CHARACTERS HERE...)EW8nYP9T840Sb8tQMi/EW8nYP9T840Sb8tQMi\EW8nYP9T840Sb8tQMi/EW8nYP9T840Sb8tQMi=\n-----END PRIVATE KEY-----\n"
Run Code Online (Sandbox Code Playgroud)

然后,我尝试从这些凭据创建 Firebase 证书并初始化应用程序

cred = firebase_admin.credentials.Certificate(my_credentials)

firebase_admin.initialize_app(cred, {'databaseURL': 'https://myapp.firebasedatabase.app/'})
Run Code Online (Sandbox Code Playgroud)

然而,事实证明 PRIVATE_KEY 环境变量不可读(无法反序列化),并且会抛出错误:

Traceback (most recent call last):
  File "C:\Users\jarem\Desktop\data_science\python-working-directory\_MyApps\BookClub2.0\venv\lib\site-packages\firebase_admin\credentials.py", line 96, in __init__
    self._g_credential = …
Run Code Online (Sandbox Code Playgroud)

python oauth firebase python-cryptography firebase-admin

5
推荐指数
1
解决办法
1978
查看次数

Firebase数据库onWrite的云功能触发两次

嗨我正在开发一个通知系统,但是我在删除已处理的通知数据时遇到问题.该onWrite事件监听器被触发两次导致两个通知.

你能帮我找一个解决方法,以便onWrite事件监听器不应该被触发两次吗?删除已处理的数据非常重要.

exports.sendMessageNotification = functions.database.ref('/notification/message/{recipientUid}/{senderUid}').onWrite(event => {
/* processing notification and sends FCM */

return admin.messaging().sendToDevice(tokens, payload).then(response => {
      // For each message check if there was an error.
      const toRemove = [];
      response.results.forEach((result, index) => {
        const error = result.error;
        if (error) {
          console.error('Failure sending notification to', tokens[index], error);
          // Cleanup the tokens who are not registered anymore.
          if (error.code === 'messaging/invalid-registration-token' ||
              error.code === 'messaging/registration-token-not-registered') {
            toRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
          }
        }
      });

      //Deletes processed notification
      console.log("Removing notification");
      const …
Run Code Online (Sandbox Code Playgroud)

node.js firebase firebase-realtime-database firebase-cloud-messaging firebase-admin

4
推荐指数
1
解决办法
2663
查看次数