No longer captures the event from firebase by Admin SDK - node.js

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.

Related

Firebase Functions: Error: Client is offline

I just recently started using Firebase functions for the first time. When I was using Firebase Functions for Firestore, it worked fine but after I switched to Realtime, I've consistently been getting "Error: Client is offline".
It happens when I turn on node.js and run my application for the first time, and I .get() some data from the realtime database.
When I click on the respective line at which the error exists, it shows me this.
This is how I initialized firebase-admin:
admin.initializeApp({
projectId: <project id>,
storageBucket: <bucket url>,
credential: admin.credential.cert(serviceAccount),
databaseURL: <db url>,
});
Is it because I have the FIREBASE_CONFIG and GCLOUD PROJECT environment variables are missing error? I've seen a lot of different posts that other people are getting the same issue, but I haven't come across a proper solution.
If anyone has any solutions or if you need more information, please let me know!
I have a feeling you may be hitting a race condition in the JavaScript implementation of get(). If that is the case, you can work around it by using the once() method, which should work exactly the same in this scenario:
const _dataSnapshot = await admin.database().ref('users').child(req.body.user_uid).once();
...

Firebase Realtime database Connecting issues from NodeJS

I had the same issue in the production environment. Sometimes the node-js server(desktop application) does not connect to firebase's real-time database from starting(installing) then after a few days I try again and it starts working. I don't know what can cause this? I tried disabling the firewall, I have allowed apps through the firewall.
when these issues occur in the production environment I switch my database to MongoDB database it always works really well.
This happed first time on my own laptop today
I was starting a new project so I have written simple code as below but was not able to connect to a real-time database for some reason but no error!
var admin = require("firebase-admin");
var serviceAccount = require("./gerneral/service.json");
admin.initializeApp({
serviceAccountId: admin.credential.cert(serviceAccount),
databaseURL: "databseurl"
});
const db = admin.database();
var ref = db.ref("data");
const connectedRef = admin.database().ref('.info/connected');
connectedRef.on('value', (snap) => {
if (snap.val() === true) {
console.log('connected');
} else {
console.error('not connected');
}
});
ref.set("it is not")
it output only ==> not connected
& not adding any value to firebase real-time database
& no error
I have used mobile JIO internet (good).
I have disabled the firewall
I have double-checked the service account(JSON file) and database URL and rules of the database.
I have a different project(related to the firebase Realtime database) on my PC I run that project and it running perfectly fine.
what can cause this?
how can I solve this issue?
Additional Information:
I try Using this project's database in other firebase-related projects (which is working fine). It shows this project's database connecting and getting data.
so this issue is most probably related to firewall or security but I double-check after disabling the firewall so why not connect to firebase's DB?
Please anyone how to find the cause of the issue?
Thank you in advance.

Deploying firebase cloud function fails when I initialise firebase with a service account key

so very recently I started using google's firebase cloud functions, and loved it immediately! I very quickly restructured a project I was going to work on, and included firebase in it, so I could use the cool features of firestore, in combination with cloud functions.
Up until today, everything went on smoothly; pretty much, until I decided to play with google's FCM (Firebase Cloud Messaging) to send notifications via node js. Before this, I had created some really dense functions and already deployed to my console which were working seamlessly.
The tricky part is, at the time I created and deployed these functions, I initialised my firebase app in node js with admin.initalizeApp().
With this, everything worked fine(both locally & deployed) until I tried to use admin.messaging().sendToDevice... which resulted in a very nasty error, that basically told me I couldnt send notifications if I wasnt authenticated..
The error
(Error: An error occurred when trying to authenticate to the FCM servers. Make sure the credential used to authenticate this SDK has the proper permissions. See https://firebase.google.com/docs/admin/setup for setup instructions. Raw server response: "<HTML>
> <HEAD>
> <TITLE>Unauthorized</TITLE>
> </HEAD>
> <BODY BGCOLOR="#FFFFFF" TEXT="#000000">
> <H1>Unauthorized</H1>
> <H2>Error 401</H2>
> </BODY>
> </HTML>
> ". Status code: 401.)
Following the error, I used a few tips from some other users on stack overflow who had faced this error, and most of them suggested that I download a service key from my console, and initialise my firebase app with admin.initializeApp({credential:admin.credential.cert(serviceAccount)})
This solution worked beautifully, as it allowed me to test my notification without seeing the above error ever again.
However, when all my tests were done, and I was ready to deploy, the new function I had just created to work on notification, as well as all my previously deployed functions could not get deployed. All of a sudden, the old working functions in my console had a red exclamation mark beside them, and I had to get rid of them. Even after I cleared out all of my console and tried to redeploy all my functions, it failed, and failed and failed with no errors(context: I wasted the whole day!!! lool!) Every tip on the internet failed for me, until I reverted back to my old way of initialising my firebase app admin.initializeApp(), then booom! all my functions uploaded successfully, and then again, the authentication error appeared again when I tried to retest my notification function.....
I guess my question is: is there anything I don't know about deploying functions to the firebase console with my app initialised with a service account key I downloaded from my console?
Is there something else I need to do to get my functions to deploy properly every time I init my firebase admin app with a service account key?? Because initialising the app with just .initalizeApp() works fine for all other purposes both locally and when deployed, except when using FCM. Can anyone please help with what is happening here??
I think it can be solved by initializing two apps and using them as objects described here. One with credentials that work for other functions and one for messaging.
If you need it only for one function you can do it even inside it. I have tested it like this:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.applicationDefault()
});
exports.first_app = functions.https.onRequest(async (req, res) => {
res.json(admin.app().name);
})
exports.other_app = functions.https.onRequest(async (req, res) => {
var otherApp = admin.initializeApp({
credential: **<< different credential here >>**
}, "2nd_app");
res.json(otherApp.name);
})
as already mentioned, you should initialize a second app just for the new function you are creating. You should put the initialization code inside the new function like this
export const saveMap = functions.https.onRequest(async (req, response) => {
const serviceAccount = require("./../serviceAccountKey.json");
admin.initializeApp({
projectId: "serviceAccount.project_id",
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://your_project_id_here.firebaseio.com", //update this
storageBucket: "your_bucket_name_here.appspot.com" //update this
}, "2nd_app")
I had the same issue and once I put the second initialization code into the new function, it worked. Note that in this code the serviceAccountKey.json is in the same folder as src and lib.

Firebase admin sdk (node.js) database request freezing

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.

Firebase Server NodeJS failing to connect with Service Account

I have a pretty simple NodeJS server that I'm using to monitor our Firebase Database. My code is basically identical to the sample on the Firebase documentation:
var firebase = require("firebase");
firebase.initializeApp({
databaseURL: 'https://myurl.firebaseio.com/',
serviceAccount: 'path/to/json.json'
})
Now the issue I'm having is when I run this code from within our network, it doens't seem to be connection as a have a block of code right after to read some data and it never gets ran:
var nodeRef = this.db.ref("node");
nodeRef.on("child_added", function (snapshot, prevChildKey) {
// ...
}, function (error) {
console.log(error);
})
If I give everyone write access to the database, I can take out the serviceAccount setting on the initializeApp call, and everything works perfectly. I've tried running Fiddler to see what it might be making a request to that is failing, but I'm not seeing any requests pop up in Fiddler at all. Any ideas what this might be calling that our proxy would need to allow?
Our IT team found what the problem was, I had asked them to open accounts.google.com in our proxy server. It got set to "allow" instead of "tunnel".
According to them, the HSTS headers were causing the SSL decryption on the proxy unless it was set to tunnel, which was causing the "self signed certificate" error I mentioned above in the comments.
For me, disabling Kaspersky got it to work. You can try that.

Resources