标签: firebase-admin

Firestore 自定义令牌

我正在尝试将自定义身份验证令牌与 firestore 一起使用。我正在使用 NodeJS 使用以下代码生成令牌。

const admin = require('firebase-admin');
const serviceAccount = require('./ServiceAccountKey.json')

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

var uid = "some-uid";
var claim = {
  control: true
};
admin.auth().createCustomToken(uid, true)
  .then(function(customToken) {
    console.log(customToken)
  })
  .catch(function(error) {
    console.log("Error creating custom token:", error);
  });
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我得到一个令牌。我使用该令牌并使用带有标题的https://firestore.googleapis.com/v1beta1/projects/example-project-5caa9/databases/(default)/documents/users进行尝试

授权:承载 eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGFpbXMiOnsiY29udHJvbCI6dHJ1ZX0sInVpZCI6InNvbWUTdWlkIiwiaWF0IjoxNTI4MTQ0NzY3LCJleHAiOjE1MjgxNDgzNjcsImF1 ZCI6Imh0dHBzOi8vaWRlbnRpdHl0b29sa2l0Lmdvb2dsZWFwaXMuY29tL2dvb2dsZS5pZGVudGl0eS5pZGVudGl0eXRvb2xraXQudjEuSWRlbnRpdHlUb29sa2l0IiwiaXNzIjoiZmlyZWJh c2UtYWRtaW5zZGsteG9jMDRAZXhhbXBsZS1wcm9qZWN0LTVjYWE5LmlhbS5nc2VydmljZWFjY291bnQuY29tIiwic3ViIjoiZmlyZWJhc2UtYWRtaW5zZGsteG9jMDRAZXhhbXBsZS1wcm9qZWN0LTVjYWE 5LmlhbS5nc2VydmljZWFjY291bnQuY29tIn0.Bjl6VY5CZKIPNyCayROWr_ZBSRmo11hiwtnx_cbbw2Ggk3J2x0Ml2OkpXhU-vAD6Q53fCZwGgXeCdxnsXw0lr55cJH3Q6J7gitzQoRnfJgUX 9Dv1gbI90OWashxMmxtzPIpwgSnfBv61mkdv9ZVrF8o362mQBx_LUQzvGgVPEN9_9UNCH7peOS4KYr_YRMpCQVem0XMNh9WKlyBZuScjHpY6dZZhXqOHda0W9-MNAfvQ-D0pt-osq4ty-D_WYk6Cj LNmxzvHoZeoIk1YShJM4Mpyec3lXFcCXNYG2c3_r2tskTB0LF7Fc7Bg5XuJwlrAzHrnRis6iZFCx8sqH1b-Zg

获取以下 JSON。

{
    "error": {
        "code": 401,
        "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
        "status": …
Run Code Online (Sandbox Code Playgroud)

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

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

Firebase 管理 SDK FCM 错误

我在 Dialogflow 履行中使用 firebase admin 版本 6.0.0 发送 fcm 通知。

admin.messaging().send({
    "message": {
        "notification": {
            "title": "Portugal vs. Denmark",
            "body": "great match!"
        },
        "token": user_info.device_id
    }
})
.then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
})
.catch((error) => {
    console.log('Error sending message:', error);
});
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误

Error: Exactly one of topic, token or condition is required
at FirebaseMessagingError.Error (native)
at FirebaseMessagingError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:39:28)
at FirebaseMessagingError.PrefixedFirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:85:28)
at new FirebaseMessagingError (/user_code/node_modules/firebase-admin/lib/utils/error.js:241:16)
at validateMessage …
Run Code Online (Sandbox Code Playgroud)

javascript firebase firebase-cloud-messaging firebase-admin

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

是否可以使用 Firebase Cloud Messaging API 列出所有推送通知?

我正在寻找了解 Firebase FCM API 的范围。我的公司要求我实施自定义 FCM 管理面板。假设,管理员可以使用该面板查看默认 Firebase FCM 发送的所有推送通知、向单个设备发送推送通知或订阅预定义主题。

在构建用于向单个设备发送推送通知的列表视图和基本表单后,我将构建一个后端服务器来自动触发 Firebase API 端点来推送通知。但是,我在 Firebase API 方面遇到了一些麻烦。

  1. 是否可以使用 Firebase API 创建 FCM 管理面板?
  2. 除了用于 FCM 的 Firebase API 中的send之外,还有其他公共方法吗?

编辑:我构建了一个原型 lambda 函数,它可以根据 Firebase 中存储的规则查询数据库来发送自动推送通知。该功能计划每天运行。通过下面的这个函数,我调用消息传递对象

private void sentAutomatedMessages(List<String> tokens, CardAbandonmentRule rule) {

    for (String token : tokens) {

        //Create Messaging object for every user that fits in this user
        Messaging msgHandler = new Messaging(rule.getTitle(), rule.getMessage(), token);
        try {
            msgHandler.handleSingleDevicePush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

类定义和发送推送通知的方法=> …

javascript firebase google-cloud-messaging firebase-cloud-messaging firebase-admin

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

Firebase 存储管理错误:400 存储桶名称无效

我正在尝试使用 firebase 函数来维护我的数据库和存储。基本上在过期后将一些旧条目从一个引用/存储桶删除到另一个引用/存储桶。数据库部分工作得很好。然而,存储部分却没有那么多。以下是我初始化代码中所有内容的方法:

var functions = require('firebase-functions');
var admin = require("firebase-admin");
var serviceAccount = require('./my-app-bla-bla.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://my-app.firebaseio.com',
  storageBucket: 'gs://my-app.appspot.com'
});
Run Code Online (Sandbox Code Playgroud)

然后在清理数据库和存储的 cron 作业中,我有以下内容(这只是一些小的相关部分):

const st = admin.storage();

st.bucket("gs://my-app.appspot.com/old-listings/"+listingKey).create(function(error, bucket, apiResponse) {
    if (error) {
        console.log("Couldn't create an OldListing bucket: " + error.code);
        console.log(apiResponse);
    } else {
        console.log("Created OldListing bucket");
    }
});
Run Code Online (Sandbox Code Playgroud)

最后一段代码触发错误并给出以下日志:

Couldn't create an OldListing bucket: 400
{ error: 
   { errors: [ [Object] ],
     code: 400,
     message: 'Invalid bucket name: \'my-app.appspot.com/old-listings/SomeUniqueID\'' } }
Run Code Online (Sandbox Code Playgroud)

因为我是第一次运行此代码,所以该文件夹old-listings尚不存在。所以我想也许我应该首先自己创建它的存储桶。它给了我同样的错误。 …

firebase google-cloud-functions firebase-storage firebase-admin

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

无法在 firebase 存储桶中创建文件夹 - firebase admin

就我而言,我有一个 Url 列表,我想从这些 url 下载每个文件并将其组织在 firebase 存储桶中,我的问题是我无法通过 nodejs javascript/typescript 在 firebase 存储桶中创建文件夹。

好吧,firebase storage 提供了 ref() 和 child 方法来上传子文件夹中的文件(请参阅this)但firebase只为firebase客户端库提供这些方法,并不是我们不能在nodejs中使用客户端库,而是他们隐藏了一些命名空间当您在 nodejs 中连接 firebase 客户端库并且存储是其中之一时(请参阅)。

我很高兴他们分别考虑了前端和后端,因为前端和后端在安全性和用例方面有完全不同的场景,所以他们真正编写在 nodejs 中使用的是 firebase admin,我看不到 ref 和 child 方法在他们所说的官方文档中,不是命名我正在上传的文件的任何其他方法,也不是任何使文件夹进入子目录的方法,当我从计算机上传文件时,它会以相同的名称保存在存储桶根目录中作为文件名,它在我的电脑中,即使我可以手动从 firebase 控制台创建文件夹,但它不能满足我的要求,肯定应该有任何方式以编程方式创建文件夹。

我也尝试使用 google 云存储库,const {Storage} = require('@google-cloud/storage'); 但结果证明 firebase admin 和 gogole 云库共享相同的文档,并且至少在上传文件部分具有相同的界面。

好吧,我花了一整天的时间(因为是凌晨 4 点 46 分,所以晚上也是如此)尝试不同的库并深入研究他们的文档,我也发现这些文档几乎没有组织和缺乏代码示例。

任何帮助将不胜感激,到目前为止我的代码片段来自他们的文档并正确上传文件:

import "firebase/firestore"

admin.initializeApp({
    credential: admin.credential.cert("./../path-to-service account-cert.json"),
    databaseURL: 'gs://bilal-assistant-xxxxx.appspot.com'
});
const quran_bucket = admin.storage().bucket("quran-bucket");

quran_bucket.upload("./my_computer_path/fatiha.mp3", {
    gzip: true,
    metadata: {
        cacheControl: 'public, …
Run Code Online (Sandbox Code Playgroud)

node.js google-cloud-storage firebase firebase-storage firebase-admin

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

使用 Firebase Cloud Functions 更新用户

我想通过电话号码查找用户并displayName使用 Admin SDK 在 Firebase Cloud Functions 中更新他们。例如,当我尝试运行此代码时:

import * as admin from 'firebase-admin'
admin.auth().getUserByPhoneNumber(phone).then((user) => {
   user.displayName = newName;
}).catch((reason) => console.log(reason['message']));
Run Code Online (Sandbox Code Playgroud)

我收到以下消息:

无法分配给对象“#UserRecord”的只读属性“displayName”

虽然我不明白这个例外,但我想不出不同的方法来做到这一点。任何的想法?

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

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

Firebase - 在管理员中设置自定义用户声明不起作用

我有一个 Firebase 云功能,可以对从给定电子邮件中找到的 Firebase 用户设置自定义声明。

这是函数代码:

export const addAdmin = functions.https.onRequest(async (request, response) => {
  // Setting policies
  response.set("Access-Control-Allow-Origin", "*");
  response.set("Access-Control-Allow-Methods", "POST");
  response.set("Access-Control-Allow-Headers", "Content-Type");

  try {
    let details = JSON.parse(request.body);
    let user = await admin.auth().getUserByEmail(details.email);

    if (details.master !== "************") throw Error("Wrong Password");

    admin
      .auth()
      .setCustomUserClaims(user.uid, { admin: true })
      .then(() => {
        response.send(
          `User with uid ${user.uid} was set with claims - ${JSON.stringify(
            user.customClaims
          )}`
        );
      })
      .catch(error => {
        console.error(error);
        response.status(400).send(error);
      });
  } catch (error) {
    console.error(error);
    response.status(400).send(error);
  } …
Run Code Online (Sandbox Code Playgroud)

node.js firebase firebase-authentication firebase-admin

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

Firebase 处理多个自定义声明

所以我有一个用例,用户可能需要多个自定义声明,但在应用程序的不同点添加,即用户可以既是店主又是店主,或者他们可能只是店主或只是用户。

我通过文档了解到,当您分配新的自定义声明时,它会覆盖原始声明,因此我需要阅读用户当前拥有的声明。这就是我被卡住的地方......在我收到索赔后,我如何将它们重新写回给用户?

exports.onGameManagement = functions.database.ref("Core/CoreGames/{game}/teams/committee").onCreate((snapshot,context)=>{
    const position = snapshot.key;
    const uid = snapshot.val();
    const game = context.params.game;
    if(position=="gLead"||position=="depGameLead"){
        //NEEDS ADMIN RIGHTS
        //ADD TOKEN WRITE RIGHTS. - check for current claims
        admin.auth().getUser(uid).then((userRecord)=>{
            //got the users claims
            console.log(userRecord.customClaims);
            //how do i add this array of claims to the setCustomUserClaims() method?
            admin.auth().setCustomUserClaims(uid, {gameAdmin: true, userRecord.customClaims}).then(() => {
                // The new custom claims will propagate to the user's ID token the
                // next time a new one is issued.
              });
        })

    }else{

    }

}) …
Run Code Online (Sandbox Code Playgroud)

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

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

Firebase 删除数组项

我想从 Firestore 中的数组中删除一个值。我正在使用 firebase 函数并在删除用户后更新此字段。我尝试过更新数组,尝试过 arrayRemove 以及其他各种行。因为每次我想运行测试时都必须进行部署,所以它很耗时,而且每次都很难构建和删除数据。

所以我希望有人可以帮助我在这里找到这个解决方案:

我想遍历一个 ID 列表(数据库中的用户)并提取他们的匹配项,并从他们的匹配项列表中删除一个特定的 ID。

当我运行它时,它不知道是什么firebase.firestore。所以我不确定如何使用这种类型的FieldValue.delete(). 这部分的目标是什么?“admin.FieldValue.delete()”?

admin.firestore()
.collection("Users")
.doc(matches[i])
.update({
  [userId]: firebase.firestore.FieldValue.delete(),
});
Run Code Online (Sandbox Code Playgroud)

我也试过这个:

admin
.firestore()
.collection("Users")
.doc(matches[i])
.update({
  matches: admin.firebase.firestore.FieldValue.arrayRemove(userId),
});
Run Code Online (Sandbox Code Playgroud)

但它又不知道是什么firebase.firestore。从数组中删除一个值的正确方法是什么?

另外,我担心在 for 循环中进行标注,但我没有找到解决方法。有没有人有什么建议?这些不需要是异步的,因为所有事务都不相互依赖。

我在 firebase 函数中收到的错误消息:

ReferenceError:firebase 未定义

javascript firebase firebase-admin google-cloud-firestore

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

构造函数 FirebaseOptions.Builder() 已弃用

Firebase 让您能够将 Firebase Admin SDK 添加到您的服务器

FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(GoogleCredentials.getApplicationDefault())
.setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
.build();

FirebaseApp.initializeApp(options);
Run Code Online (Sandbox Code Playgroud)

以前,我使用了以下代码,但是,我现在在 Eclipse 中收到一条消息“不推荐使用构造函数 FirebaseOptions.Builder()”。

InputStream serviceAccount = context.getResourceAsStream("/WEB-INF/[my-web-token].json");
    try {
        options = new FirebaseOptions.Builder() // <--DEPRECATED
            .setCredentials(GoogleCredentials.fromStream(serviceAccount))
            //.setDatabaseUrl(FIREBASE_DATABASE_URL)
            .build();
        } catch(Exception e) {
            e.printStackTrace();
        }

        firebaseApp = FirebaseApp.initializeApp(options);
Run Code Online (Sandbox Code Playgroud)

果然,Firebase建议

Builder() 此构造函数已弃用。改用 builder() 。

构造函数现在看起来像这样

公共静态 FirebaseOptions.Builder 构建器 ()

这是如何实现的?如果我只是更换

FirebaseOptions options = FirebaseOptions.Builder()
...
Run Code Online (Sandbox Code Playgroud)

与新的建设者...

FirebaseOptions options = FirebaseOptions.builder()
...
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

FirebaseOptions.builder 无法解析为类型

并且该文件将无法编译。

有人可以告诉我如何使用新的构造函数或指向我更新的 Firebase 文档吗?我找不到。

java firebase firebase-admin

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