标签: firebase-admin

Firebase Admin SDK 使用提供程序创建用户

我正在尝试使用 Firebase Cloud Functions 为我的应用程序创建 REST API。我知道如何在 Cloud Functions 中使用 Admin SDK。它确实有API createUser。我的前端应用程序允许用户使用 Google 和 Facebook 登录,但我不知道如何将它们组合在一起。

我的应用程序已成功实施Sign in with GoogleSign in with Facebook但我如何以及将哪些数据传输到 Cloud Functions(或任何 REST API 服务器),以便它可以在 Firebase 中使用适当的提供商创建用户。

更新以获得更多解释

我正在为 iOS 和 Android 创建一个具有某种基于云的后端的应用程序。现在我正在尝试使用 Firebase,但我不打算将我的应用程序与 Firebase 紧密耦合,因此不想将 Firebase-iOS 和 Firebase-Android SDK 拉入我的应用程序代码中。我希望能够自由地将后端切换到 AWS 或 Azure,而无需更改前端代码。

一种(也是唯一的?)方法是创建一个服务器,该服务器将公开 REST API 端点并代表我完成通常 SDK 所做的工作。为了实现这一目标,我使用了 Cloud Functions,但这并不重要,只要我有 API 可以与实际的云进行通信。

在做出解释之后,现在我的问题是如何让我的用户使用 Google 和 Facebook 等外部提供商登录应用程序,并且仍然实现我想要做的事情。当我让用户通过提供商登录时,我没有将他们的密码发送到后端来创建新的电子邮件/密码用户。

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

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

firebase 管理员无法查询大项目

对于大型项目,使用 firebase admin 从云函数中的集合检索数据失败。我用来查询云函数选择的示例代码如下

admin.database().orderByChild('mmyyyy').equalTo(month).once('value');
Run Code Online (Sandbox Code Playgroud)

当我尝试检索 10600 个项目(试图找出原因)时,此调用失败。在谷歌控制台中有这个日志,但没有其他可以指出我正确的方向

textPayload:  "Function execution took 18547 ms, finished with status: 'response error'"   
Run Code Online (Sandbox Code Playgroud)

经过多次失败的尝试后,我决定尝试使用 firebase sdk 在客户端上执行此调用,如下所示:

result = await firebase.database().ref(`transactions`).orderByChild('mmyyyy').equalTo(month).once('value');
Run Code Online (Sandbox Code Playgroud)

这在客户端上完美运行,没有错误,并返回我的所有项目,其中 17000 个(该 json 的大小为 26MB)。

为什么会这样呢?是否有任何未记录的限制?

注意:我将云功能内存增加到 1GB,超时时间增加到 5 分钟,但没有帮助。

这是完整的示例代码

admin.database().orderByChild('mmyyyy').equalTo(month).once('value');
Run Code Online (Sandbox Code Playgroud)

firebase firebase-realtime-database google-cloud-functions firebase-admin

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

Firebase Admin SDK 从 TypeScript 初始化失败

我正在尝试在我的 TypeScript (Nest.js) 应用程序中导入 Firebase Admin SDK。

let serviceAccount = require("../../creds.json");
console.log(serviceAccount);

const firebase = require("firebase");
firebase.initializeApp(environment.firebase);

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "projectid"
});
Run Code Online (Sandbox Code Playgroud)

但是当我尝试构建应用程序时,出现以下错误。

ERROR in ./node_modules/@google-cloud/firestore/src/v1beta1/firestore_client.js
Module not found: Error: Can't resolve './firestore_client_config' in '/home/jaybell/trellis-server/trellis/node_modules/@google-cloud/firestore/src/v1beta1'
 @ ./node_modules/@google-cloud/firestore/src/v1beta1/firestore_client.js 28:17-53
 @ ./node_modules/@google-cloud/firestore/src/v1beta1/index.js
 @ ./node_modules/@google-cloud/firestore/src/index.js
 @ ./src/server/main.server.ts

ERROR in ./node_modules/google-gax/lib/operations_client.js
Module not found: Error: Can't resolve './operations_client_config' in '/home/jaybell/trellis-server/trellis/node_modules/google-gax/lib'
 @ ./node_modules/google-gax/lib/operations_client.js 30:17-54
 @ ./node_modules/google-gax/index.js
 @ ./node_modules/@google-cloud/firestore/src/v1beta1/index.js
 @ ./node_modules/@google-cloud/firestore/src/index.js
 @ ./src/server/main.server.ts

ERROR in ./node_modules/google-gax/index.js
Module not found: Error: Can't resolve './package' in '/home/jaybell/trellis-server/trellis/node_modules/google-gax' …
Run Code Online (Sandbox Code Playgroud)

node.js firebase typescript firebase-admin angular

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

使用functions.config().firebase 进行初始化时,如何包含我的firebase 服务帐户密钥?

我正在初始化我的 firebase 函数,如下所示:

admin.initializeApp(functions.config().firebase)
Run Code Online (Sandbox Code Playgroud)

我已经生成了一个服务帐户密钥,我相信我需要出于身份验证目的来执行此操作。

它给了我一个带有各种键/值的 json 表。

说明是将其添加到 admin.initializeApp 中,如下所示:

var serviceAccount = require("path/to/serviceAccountKey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});
Run Code Online (Sandbox Code Playgroud)

这与我的做法非常不同。

我什至不确定我是否需要这样做,因为我确实可以使用以前的方法访问 firestore,但是使用有效用户 id 令牌进行身份验证不起作用,在 firebase 中出现以下错误:

错误:错误:解码 Firebase ID 令牌失败。确保您传递了代表 ID 令牌的整个字符串 JWT。有关如何检索 ID 令牌的详细信息,请参阅 https://firebase.google.com/docs/auth/admin/verify-id-tokens 。

通过嗅探,似乎缺少的是 admin sdk 服务帐户。

javascript firebase google-cloud-functions firebase-admin

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

使用 Firebase Admin SDK 将转化事件添加到云消息

我可以使用下面的代码发送推送通知,但我还需要将“转化事件”与通知相关联。这可以通过控制台完成,但我找不到如何使用 SDK 来完成此操作。

var message = new Message()
            {
                Data = new Dictionary<string, string>()
                {
                    { "test1", "6165" },
                    { "test2", "161" },
                },
                Notification =
                {
                    Body = "",
                    Title = ""
                },
                Topic = topic,

            };
            // Send a message to the devices subscribed to the provided topic.
            Task<string> response =  FirebaseMessaging.DefaultInstance.SendAsync(message, true);
            // Response is a message ID string.
            response.Wait();
            Console.WriteLine("Successfully sent message: " + response);
Run Code Online (Sandbox Code Playgroud)

firebase firebase-cloud-messaging firebase-analytics firebase-admin

5
推荐指数
0
解决办法
217
查看次数

Firebase 管理 SDK:未获取访问令牌

目标是让我的 Express 服务器使用 Firebase Cloud Messaging (FCM) 发送推送通知。

问题是admin SDK的初始化似乎不起作用。代码是用 JavaScript 编写的,节点版本是 10.16.0,firebase-admin 版本是 8.3.0,服务器在最新的 Ubuntu 上运行。

我按照 firebase 指南设置了管理 SDK: https ://firebase.google.com/docs/admin/setup#initialize_the_sdk

设置了 GOOGLE_APPLICATION_CREDENTIALS 环境变量,并尝试使用该变量打开文件:

nano $GOOGLE_APPLICATION_CREDENTIALS
Run Code Online (Sandbox Code Playgroud)

一次

admin.messaging().send(message)
Run Code Online (Sandbox Code Playgroud)

被调用时,会抛出以下错误:

Error sending message: { Error: Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal metadata.google.internal:80. Error code: ENOTFOUND".
    at FirebaseAppError.FirebaseError [as constructor] (/local/home/user/node_modules/firebase-admin/lib/utils/error.js:42:28)
    at FirebaseAppError.PrefixedFirebaseError …
Run Code Online (Sandbox Code Playgroud)

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

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

如何在 Node js 中加载 Firebase 管理密钥?

我想使用 firebase admin SDK 让我的节点服务器免费访问我的数据库。index.js这是我文件夹中的代码functions

const functions = require("firebase-functions");
const admin = require("firebase-admin");

// Initialize app
admin.initializeApp({
  credential: admin.credential.cert("logininfo.json"),
  databaseURL: "https://thenameofmydatabase.firebaseio.com/",
  databaseAuthVariableOverride: {
    uid: "nameserver"
  }
});
Run Code Online (Sandbox Code Playgroud)

在同一个文件夹中,我有我的 logininfo.json,它看起来像这样(出于明显的原因审查了密钥):

{
  "type": "service_account",
  "project_id": "...",
  "private_key_id": "...",
  "private_key": "...",
  "client_email": "...",
  "client_id": "...",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "..."
}
Run Code Online (Sandbox Code Playgroud)

Failed to parse certificate key file: Error: ENOENT: no such file or directory但是,我在尝试部署到 firebase 托管时收到错误。

我该如何解决这个问题,是否有更安全/优雅的方法来处理这个问题?我可以在 firebase 托管中的某处更改GOOGLE_APPLICATION_CREDENTIALS变量吗?

node.js firebase firebase-hosting google-cloud-functions firebase-admin

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

Spring boot - 从 jar 内访问 firebase admin sdk 凭证 json 文件

我有一个使用 Firebase Admin SDK 的 Java Spring Boot 后端应用程序。在 FirebaseConfig 的 init 方法中,我必须提供 FirebaseOptions 的凭据文件,

@PostConstruct
public void init() throws IOException {
    ClassLoader classLoader=Thread.currentThread().getContextClassLoader();
    FileInputStream refreshToken = new FileInputStream("src/main/resources/progresee-fa969-firebase-adminsdk-3vip2-d80bf340b7.json");
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(GoogleCredentials.fromStream(refreshToken))
        .setDatabaseUrl(dbUrl)
        .build();
    FirebaseApp.initializeApp(options);
}
Run Code Online (Sandbox Code Playgroud)

当我在本地运行时一切正常,但是当我构建 jar 文件并上传到服务器托管服务(AWS)时,我收到 FileNotFound 错误 -

Caused by: java.io.FileNotFoundException: /progresee-fa969-firebase-adminsdk-3vip2-d80bf340b7.json (No such file or directory)
at java.io.FileInputStream.open0(Native Method) ~[na:1.8.0_222]
at java.io.FileInputStream.open(FileInputStream.java:195) ~[na:1.8.0_222]
at java.io.FileInputStream.<init>(FileInputStream.java:138) ~[na:1.8.0_222]
at java.io.FileInputStream.<init>(FileInputStream.java:93) ~[na:1.8.0_222]
at com.progresee.app.firebase.FirebaseConfig.init(FirebaseConfig.java:55) ~[classes!/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_222]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_222]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_222] …
Run Code Online (Sandbox Code Playgroud)

java spring firebase-admin

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

firebase 无法确定项目 ID

这是我使用节点发出的请求


// Initialize the default app
var admin = require('firebase-admin');

var app = admin.initializeApp({
  credential: admin.credential.applicationDefault(),
  databaseURL: process.env.FIREBASE_DATABASE
});

console.log(process.env.FIREBASE_DATABASE);


router.post('/', (req, res, next) => {

    app.auth().getUserByEmail("j.100233260@gmail.com")
    .then(function(userRecord) {
            // See the UserRecord reference doc for the contents of userRecord.
            console.log('Successfully fetched user data:', userRecord.toJSON());
            res.json(userRecord.toJSON())
        })
        .catch(function(error) {
                console.log('Error fetching user data:', error);
                res.json(error)

            });

        }

        );
Run Code Online (Sandbox Code Playgroud)

我在我的机器上设置了环境变量

在此输入图像描述

对于我的 firebase 数据库,我使用了 env

在此输入图像描述

给出为

databaseURL: "https://fssssss.firebaseio.com",
Run Code Online (Sandbox Code Playgroud)

从 Firebase 管理 GUI 中,

当我请求这条路线时邮递员中的错误

{
    "code": "app/invalid-credential",
    "message": "Failed to determine project …
Run Code Online (Sandbox Code Playgroud)

node.js firebase-authentication firebase-admin

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

如何按“_createTime”对 firestore 文档进行排序?

我正在使用带有 Admin SDK 的云 Firebase 函数从我的 Firestore 集合中获取最新文档。排序基于timestamp字段。该值是在编写文档时明确提供的。

获取代码

const fetchedTransaction = (await transactionsColRef.orderBy('timestamp', 'desc')
                .limit(1).get()).docs[0]

console.log(fetchedTransaction)
console.log('Transaction created at', fetchedTransaction.createTime.toDate())
Run Code Online (Sandbox Code Playgroud)

这些console.log语句打印以下输出。看_createTime在底部。

输出

const fetchedTransaction = (await transactionsColRef.orderBy('timestamp', 'desc')
                .limit(1).get()).docs[0]

console.log(fetchedTransaction)
console.log('Transaction created at', fetchedTransaction.createTime.toDate())
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种方法来排序文档,而_createTime不是timestamp每次都写入一个值。使用orderBy('_createTime')orderBy('createTime')没有效果。

firebase google-cloud-functions firebase-admin google-cloud-firestore

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