Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any possibility to access firebase admin through functions internally?

I need to access firebase admin through Firebase functions. I have a function that is being called through an HTTP trigger, and will create custom auth tokens.

In the Firebase admin documentation, they say that you need to refer to the JSON file containing all the keys (serviceAccount)

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

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://<databaseName>.firebaseio.com"
})

Since i'm already inside my own Firebase functions, will i need to upload these keys or can I access this in any other way?

It feels very unnecessary uploading all my admin keys to Firebase storage just to mint new tokens...

like image 582
Giovanni Palusa Avatar asked Nov 06 '17 10:11

Giovanni Palusa


1 Answers

You can use functions.config().firebase to obtain the Firebase config instance and then pass this directly to the initializeApp() method of the Admin SDK:

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

// Pass the Firebase config directly to initializeApp() to auto-configure
// the Admin Node.js SDK.
admin.initializeApp(functions.config().firebase);

From the use environment configuration to initialize a module documentation:

When you deploy functions using the Firebase CLI, functions.config().firebase is auto-populated with configuration needed to initialize the firebase-admin SDK.

So you can put this in your code:

const functions = require('firebase-functions');   
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

It has been noted that functions.config() is only available within the Cloud Functions hosted environment and therefore not available when emulating functions locally. As a workaround, you can export functions.config() to .runtimeconfig.json by running the following command inside your functions directory:

firebase functions:config:get > .runtimeconfig.json
like image 113
Grimthorr Avatar answered Sep 22 '22 22:09

Grimthorr