Firebase admin sdk (node.js) database request freezing - node.js

In recent days, i have encountered a few problems with my old firebase sdk's in both android and server node js 'firebase' sdk. Sending notifications and retrieving data.
After i updated android dependencies with newest version, notification problem was solved.
But in server side:
Installed firebase admin sdk.
Followed instructions:
https://firebase.google.com/docs/admin/setup
and also checked role of firebase-adminsdk service account.
Problem with the following example:
var admin = require("firebase-admin");
var serviceAccount = require("filepath.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://dbname.firebaseio.com"
});
var db = admin.database();
var ref = db.ref("myval");
ref.once("value",function(snapshot){
console.log(snapshot.val());
});
Example does not return any value or error, just waiting. Sure there is 'myval' child under main database tree.
What wrong may cause the problem?

Solved the problem with help of firebase team.
Enabling the logging before database definition with:
admin.database.enableLogging(true);
var db = admin.database();
helps for debugging. After that I got the error:
Failed to get token: Error: Error fetching access token: invalid_grant (Invalid JWT: Token must be a short-lived token and in a reasonable timeframe)
And according to this:
Authentication on google: OAuth2 keeps returning 'invalid_grant'
my machine timezone was not syncronized appropriately with a ntp server, which is required for new admin authentication in my case.
Then (in ubuntu 14.04) setting the timezone (timezones are here: '$ timedatectl list-timezones') :
$ sudo timedatectl set-timezone desired_timezone
solved the problem!
Thanks for helps.

Related

Firebase - Error: 16 UNAUTHENTICATED: Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid au

Hello I'm using firebase functions and I have created a Node.js project with firebase init, then I selected the options functions, firebase and storage. The project works with the firebase-admin NPM package.
When I deploy the project with firebase deploy everything goes well, but when I run the function on the cloud, it says the following message:
I have tested the entire project with the emulators and it works well.
Project Structure:
What is causing this error? Thanks!
I solved it. The problem was that I had this in the initializeApp:
const serviceAccount = require("../project-name-f3ad6ae0572f.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
storageBucket: BUCKET_NAME,
});
This is incorrect because I was missing the firebase configuration that is given on the Firebase Console -> Project Settings -> Your Apps.
Then, the result has to be like this:
const firebaseConfig = {
apiKey: "xxx-your-api-key-xxx",
authDomain: "project-name.firebaseapp.com",
projectId: "project-name",
storageBucket: "project-name.appspot.com",
messagingSenderId: "xxxxxxxxxxxxxxxx",
appId: "x:xxxxxxxxxxxxxxx:web:xxxxxxxxxxxxxxx",
measurementId: "G-XXXXXXXXX",
};
admin.initializeApp(firebaseConfig);
verify your pc time, i had same problem and resolving when update pc time.
import * as admin from 'firebase-admin';
const serviceAccount = require('./firebase.json');
if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
export const firebaseDB = admin.firestore();
I might be late to this question but I faced a similar issue yesterday (16 October 2022). What I figured is that, when you set your computer's time manually, firebase doesn't work.
So your firebase timestamp rules must match with your current host time.
The code for the function framework is actually public in the GoogleCloudPlatform/functions-framework-nodejs repository (although not advertised anywhere).
In particular you can see there the cases where killInstance is used, which is the one triggering exit code 16:
const killInstance = process.exit.bind(process, 16);
These cases are (at the time of writing):
· uncaughtException
· unhandledRejection
I had the same issue today, if it's only happening in your local environment, there's a 99% chance that your computer's time is wrong.

Realtime DB events don't work when subscribed to from Admin SDK

Operating System: Ubuntu 16.04
Firebase SDK version: 4.8.0
Library version 5.5.1
Node version: 7.8.0
Firebase Product: database
Hey! Yesterday my server with Admin SDK stopped working. After a little investigation it turns out that events don't fire anymore. For example, the following code neither fails or succeedes (the process is running forever). It is run on a local dev server:
const admin = require('firebase-admin')
const config = require('./config')
const signature = require('./signature.json')
admin.initializeApp({
credential: admin.credential.cert(signature),
databaseURL: config.databaseURL
})
admin.database()
admin.database().ref('/config').once('value')
.then(snapshot => console.log(snapshot.val()))
.catch(error => console.log(error))
module.exports = {}
Database events are working when I subscribe to them as a client. Also database is accesible from web console. I've tried generating a new private key (credentials), but it doesn't help. What am I missing? Is there a way to take a closer look at what's going on? Maybe enabling debug mode somehow?
After enabling loggin I was able to figure out what's wrong.
// Enable logging
admin.database.enableLogging(true)
The problem was that the time on my machine was out of sync. After synchronising it the database is working again.

Firebase Admin INVALID_APP_OPTIONS error at initializeApp()

I'm trying to connect Instagram OAuth to Firebase through Node.js back-end. I have successfully retrieved Instagram account data including access_token which I want to exchange with firebase-admin's createCustomToken on my Node.js backend. My objective here is to generate custom token so my Angular app can do signInWithCustomToken(token) into my Firebase app. There is no problem on retrieving data from Instagram as I can print my JSON object on console.
The problem is occurred when I want to exchange my access_token to Firebase Custom Token.
I have followed this guide from Firebase Admin page for Node.js and I'm facing an error message below
throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_APP_OPTIONS, "Invalid Firebase app options passed as the first argument to initializeApp() for the " +
Error: Invalid Firebase app options passed as the first argument to initializeApp() for the app named "[DEFAULT]". The "credential" property must be an object which implements the Credential interface.
Here is my code on related issue.
// authService.js
var fbAdmin = require('firebase-admin');
var serviceAccount = require('./key/key.json');
function createFirebaseToken(instagramID) {
// I copy & pasted this var from other class
var config = {
apiKey: "MY_FIREBASE_APIKEY",
authDomain: "MY_APP.firebaseapp.com",
databaseURL: "https://MY_APP.firebaseio.com",
storageBucket: "MY_APP.appspot.com",
};
console.log(fbAdmin.credential.cert(serviceAccount)); // serviceAccount successfully printed on console
// Error appears when executing this function
fbAdmin.initializeApp({
serviceAccount: fbAdmin.credential.cert(serviceAccount),
databaseURL: config.databaseURL
});
const uid = `instagram:${instagramID}`;
// Create the custom token.
console.log(uid);
return fbAdmin.auth().createCustomToken(uid);
}
It appears that my Node app cannot initialize a connection to firebase-admin but I have no idea the solution as I am a beginner on these technologies. Please advice.
This issue can be resolved by updating firebase-tools, firebase-functions and firebase-admin packages to the latest version.
npm install -g firebase-tools#latest
npm install firebase-functions#latest
npm install firebase-admin#latest
Refer this GitHub page for more details.
Just stumbled upon on Firebase Admin Release Notes at version 5.0.0 on May 2017 stated that serviceAccount has been removed. So instead of forcing to use serviceAccount, I use credential instead.
fbAdmin.initializeApp({
credential: fbAdmin.credential.cert({
projectId: '<APP_ID>',
clientEmail: "foo#<APP_ID>.iam.gserviceaccount.com",
privateKey: "-----BEGIN PRIVATE KEY-----\n<MY_PRIVATE_KEY>\n-----END PRIVATE KEY-----\n"
}),
databaseURL: config.databaseURL
});
Updated Answer
After continuing to work with this, it seems to be able to call admin.initializeApp() without any params, you need to make sure your `/functions nodeJs setup is up to date.
In /functions directory, run this command:
npm i --save firebase-functions#latest
Thanks to:
https://stackoverflow.com/a/49437619/2162226
.. I am still getting familiar with all the nodeJS/npm details - not sure why, but seems I had to run it a few times for everything to get into place. That and the sudo npm install -g firebase-tools updated as well .
According to official docs, we need to be using at least version Firebase 4.12.0 in order to get the latest cloud functions support: https://firebase.google.com/docs/functions/callable
First Answer
I ran into the same error message in trying to set up Cloud Functions for Firebase.
Passing in the argument for admin.initializeApp solved it for my project:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
After a good amount of search, gratefully found this thread with a post where it has that line of code: https://github.com/firebase/firebase-functions/issues/99 .. because so far haven't seen it anywhere in the docs about that parameter
According to the release docs for Jan. 11, 2018:
https://firebase.google.com/support/release-notes/admin/node
The admin.initializeApp() method can now be invoked without any arguments. This initializes an app using Google Application Default Credentials, and other AppOptions loaded from the FIREBASE_CONFIG environment variable.
Kindly use the following snippet, which is mentioned in the Firebase Admin SDK for Node.js. Download the JSON file from the Service Account in the Project Settings and change the path in serviceAccount. Also add your databaseUrl, which is of the form http://app_name/.firebaseio.com
var admin = require("firebase-admin");
var serviceAccount = require("path/to/serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "yourDatabaseUrl"
});
For those having this issue with "firebase-admin": "^11.0.0", you have to construct the certification passed into initializeApp() using cert imported from firebase-admin/app.
Example:
import { initializeApp, cert } from "firebase-admin/app";
const admin = initializeApp({
credential: cert({
projectId: process.env.MY_PROJECT_ID,
clientEmail: process.env.MY_PRIVATE_KEY,
privateKey: process.env.MY_CLIENT_EMAIL,
}),
});
Check what version of firebase-admin module you are using.
As per the release note of version 5.9.1
The admin.initializeApp() method can now be invoked without a credential option. The SDK uses Google Application Default Credentials when initialized this way.
release notes

Electron Firebase: FIREBASE WARNING: Provided authentication credentials are invalid

I've created electron app that uses firebase auth and database.
App uses signInWithCustomToken with token received from remote server.
On my work machine (macOS) it works as expected. But when i've cloned my repo to home machine (windows) i've receive
FIREBASE WARNING: Provided authentication credentials are invalid.
This usually indicates your FirebaseApp instance was not initialized correctly.
Make sure your apiKey and databaseURL match the values provided
for your app at https://console.firebase.google.com/
As i found here in same questions error with firebase-admin. But i'm using client library. Also i've misunderstood how it depends on machine where it runs?
I'm using npm package firebase 4.1.5 packed with webpack into client script
Initialising:
const firebaseConf = {
apiKey: '<api_key>',
authDomain: '<domain>.firebaseapp.com',
databaseURL: 'https://<database>.firebaseio.com',
projectId: '<project_id>',
storageBucket: '<storage>.appspot.com',
messagingSenderId: '<sender_id>',
};
Vue.prototype.$firebase = firebase.initializeApp(firebaseConf);
So on work machine all database operations work fine. But on home machine it shows that warning few times after signInWithCustomToken called and does nothing else
The code is exactly the same. It was cloned from bitbucket
I've spent a whole day trying to figure out the reason but failed.
Sorry for my English
Thank you in advance

No longer captures the event from firebase by Admin SDK

I have installed and run firebase admin on my node server, it has been running well until today, there is no given error to tell what happened, it simply stops working.
var admin = require("firebase-admin");
var serviceAccount = require("mycom-firebase-adminsdk-d1ebt123456.json");
var app = FireBaseAdapter.admin.initializeApp({
credential: FireBaseAdapter.admin.credential.cert(serviceAccount),
databaseURL: "https://xxxx.firebaseio.com"
});
var db = app.database();
var ref = db.ref("messages"); // this node actually exists in my db.
ref.on("value", function(snapshot) {
// this will never be called - which has been working before.
console.log(snapshot.val());
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
I even wrap it in the try catch to print out the error, but there isn't any. I can log into the firebase console in the account and see my database with no change (small database) (although it seems be slower than normal).
Is there something wrong with firebase Admin SDK? Any help is appreciated.
After spending many hours to find out the cause, I found the problem.
Since I couldn't find any way to enable log of firebase-admin, so it was the dead end to troubleshoot the issue while everything runs silently, so I switched to use the firebase package to have the logging
var firebase = require("firebase");
firebase.initializeApp({
databaseURL: "https://xxxxx.firebaseio.com",
serviceAccount: '....'
});
firebase.database.enableLogging(true); // <=== important
My issue is quite similar to this question
then I could see the actual error:
p:0: Failed to get token: Error: Error refreshing access token:
invalid_grant (Invalid JWT: Token must be a short-lived token and in a
reasonable timeframe)
The solution for this issue was explained on this anwser. This issue caused by a poor synchronisation of the computer's clock where the code was executed that had a lag of 5 minutes (due to a faulty battery for the internal clock).
It started working again when I manually changed the internal time of my computer to the correct one (or totally I reset my computer date-time).
In my case, after resetting the datetime&timezone, the firebase automatically works again and I do not need to re-generate another service account.

Resources