云功能向Firestore添加数据的权限错误

时间:2019-06-19 20:03:18

标签: firebase google-cloud-platform google-cloud-firestore google-cloud-functions

我正在尝试设置一个Cloud Function,当由Cloud Scheduler运行时,它将某些数据插入我的Firestore数据库。我正在使用创建我的Cloud Function时提供的内联编辑器在Node.js中进行此操作。

我不断收到错误消息:

  

“错误:函数崩溃。详细信息:   7 PERMISSION_DENIED:缺少权限或权限不足。”

在Firebase仪表板上,日志显示了我的功能以及测试我的Cloud Function时遇到的错误,因此,我假设我的功能正在访问数据库,只是不添加正在测试的虚拟数据。 / p>

index.js:

const Firestore = require('@google-cloud/firestore');
const PROJECTID = 'MY_PROJECT_ID';
const firestore = new Firestore({
  projectId: PROJECTID,
  timestampsInSnapshots: true,
});

/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */
exports.helloWorld = (req, res) => {
    return firestore.collection("users").add({
    first: "Ada",
    last: "Lovelace",
    born: 1815
    });
};

Package.json:

{
  "name": "sample-http",
  "version": "0.0.1",
  "dependencies": {
    "@google-cloud/firestore": "0.17.0",
    "semver": "^5.5.1"
  }
}

我的数据库规则也设置为:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
        allow read, write;
    }
  }
}

2 个答案:

答案 0 :(得分:1)

由于@andresmijares,我得以解决我的问题。我进一步研究了quickstart,并如下更改了index.js(特别是helloWorld函数之前的所有内容)。

return

我得到了错误

  

“无法加载文件index.js中的代码。您是否在package.json依赖项中列出了所有必需的模块?详细的堆栈跟踪:错误:找不到模块'firebase-admin'“

我可以通过将“ firebase-admin”依赖项添加到package.json中来进行修复,如下所示:

// Creates a hero object with no properties
let hero = new Hero();

// Creates a hero object with defined properties
let hero = new Hero(1, 'Windstorm');

// Creates a hero object then sets the object property
let hero = new Hero();
hero.id = 1;
hero.name = 'Windstorm';

这也都是在创建Cloud Function时提供的内联编辑器中完成的,因此不需要安装任何东西。

答案 1 :(得分:0)

您需要下载sdk密钥,这是一个json文件,您可以从Firebase控制台Project Overview -> Project Settings -> Services Accounts导出

然后您可以像这样实例化它:

var admin = require("firebase-admin");

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

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

使用firebase admin sdk时,firestore安全规则不适用(它们仅适用于客户端操作)