Error method sendAll() in nodejs using firebase-admin - node.js

I use firebase-admin for nodejs(version 7.3.0) for sending push
notifications. For 40k distinct messages sending with method sendAll often server received this error:
"Credential implementation provided to initializeApp() via the "credential"
property failed to fetch a valid Google OAuth2 access token with the
following error: "Error fetching access token: Error while making request:
socket hang up. Error code: ECONNRESET".
Sometimes it works well but not all the time.
var admin = require('firebase-admin');
serviceAccount = require('/path_json_adminsdk/yyyyyyyyyy.json');
var defaultApp = admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://api-project-yyyyyy'
});
var k = 42000;
var contorMessages = 0;
var messages = [];
for(var i=0;i <em><</em> k; i++){
//.......
contorMessages = contorMessages + 1;
var tmp = {
alert: body.alert,
payload: body.payload
};
//form the array to be sent
messages.push({
data: {"body": JSON.stringify(tmp)},
token: body.token
});
if(contorMessages == 100){
SEDispatcher.emit('sendMessageFirebaseMulticast',messages);
contorMessages = 0;
messages = [];
}
}
SEDispatcher.on('sendMessageFirebaseMulticast', function(messages){
var dryRun = true;
admin.messaging().sendAll(messages, dryRun)
.then(function(response) {
//console.log("response:",response);
//responses = response.responses;
//.......
})
.catch((error) => {
console.log(' +++ Error sending message:', error);
});
});
the error that occurs sometimes:
+++ Error sending message: { Error: Credential implementation provided to initializeApp() via the "credential" property failed to fetch a
valid Google OAuth2 access token with the following error: "Error
fetching access token: Error while making request: socket hang up.
Error code: ECONNRESET".
at FirebaseAppError.Error (native)
at FirebaseAppError.FirebaseError [as constructor] (/opt/node/test/node_modules/firebase-admin/lib/utils/error.js:42:28)
at FirebaseAppError.PrefixedFirebaseError [as constructor] (/opt/node/test/node_modules/firebase-admin/lib/utils/error.js:88:28)
at new FirebaseAppError (/opt/node/test/node_modules/firebase-admin/lib/utils/error.js:122:28)
at /opt/node/test/node_modules/firebase-admin/lib/firebase-app.js:121:23
at process._tickCallback (internal/process/next_tick.js:103:7) errorInfo: { code: 'app/invalid-credential',
message: 'Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2
access token with the following error: "Error fetching access token:
Error while making request: socket hang up. Error code: ECONNRESET".'
}, codePrefix: 'app' }

const messaging = getMessaging(defaultApp);
Need to be load

let serviceAccount = require('./google.json');
function messaging() {
const defaultApp = initializeApp({
credential: admin.credential.cert(serviceAccount)
});
const messaging = getMessaging(defaultApp);
const topic = 'highScores';
const message = [
{
data: {
score: '850',
time: '2:45'
},
topic: topic
}
];
messaging
.sendAll(message, true)
.then(function (response) {
console.log('response:', response);
})
.catch((error) => {
console.log(' +++ Error sending message:', error);
});
}
Assuming that the JSON is the file that contains your private key that is generated when registering the project

Related

Internal Error to send FCM notification to web application

I'm developing an internal client for triggering firebase cloud messaging push notifications.
With android devices it works without problems. however, when I try to send a notification to a pwa I get the message: FirebaseMessagingError: An internal error has occurred. Please retry the request
This is the code of the function I'm developing:
import admin from '../classes/FirebaseNotification.js';
const priority = 'high';
class FormatNotificationAndroid {
static sendNotification = (data) => {
let registrationTokens = data.devices;
let message = {
notification: {
title: data.notification.title,
body: data.notification.message,
}
};
let options = {
priority: priority,
timeToLive: data.notification.time_to_live
};
console.log(registrationTokens);
console.log(message);
console.log(options);
admin.messaging().sendToDevice(registrationTokens, message, options)
.then(response => {
console.log(response.results);
})
.catch(error => {
console.log(error);
});
}
}
export default FormatNotificationAndroid;
The error trace:
error: FirebaseMessagingError: An internal error has occurred. Please retry the request.
at FirebaseMessagingError.fromServerError (C:\projetos\firebase-send-message\node_modules\firebase-admin\lib\utils\error.js:254:16)
at C:\projetos\firebase-send-message\node_modules\firebase-admin\lib\messaging\messaging.js:93:65
at Array.forEach (<anonymous>)
at mapRawResponseToDevicesResponse (C:\projetos\firebase-send-message\node_modules\firebase-admin\lib\messaging\messaging.js:89:26)
at C:\projetos\firebase-send-message\node_modules\firebase-admin\lib\messaging\messaging.js:344:24
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
errorInfo: [Object],
codePrefix: 'messaging'

Adding firebase firestore entry failed : 7 PERMISSION_DENIED

I'm trying to use a Firebase Cloud Function to create a document within the Firestore database from my Node js environment with Express js, but it fails with below error on the function logs.
Error: Process exited with code 16
at process.on.code (/layers/google.nodejs.functions-framework/functions-framework/node_modules/#google-cloud/functions-framework/build/src/invoker.js:275:22)
at process.emit (events.js:198:13)
at process.EventEmitter.emit (domain.js:448:20)
at process.exit (internal/process/per_thread.js:168:15)
at Object.sendCrashResponse (/layers/google.nodejs.functions-framework/functions-framework/node_modules/#google-cloud/functions-framework/build/src/logger.js:37:9)
at process.on.err (/layers/google.nodejs.functions-framework/functions-framework/node_modules/#google-cloud/functions-framework/build/src/invoker.js:271:22)
at process.emit (events.js:198:13)
at process.EventEmitter.emit (domain.js:448:20)
at emitPromiseRejectionWarnings (internal/process/promises.js:140:18)
at process._tickCallback (internal/process/next_tick.js:69:34)
firebase.ts file :
import * as admin from 'firebase-admin'
import * as functions from 'firebase-functions'
admin.initializeApp({
credential: admin.credential.cert({
privateKey: functions.config().private.key.replace(/\\n/g, '\n'),
projectId: functions.config().project.id,
clientEmail: functions.config().client.email
}),
databaseURL: 'https://app-id.firebaseio.com'
})
const db = admin.firestore()
export { admin, db }
controller.ts :
import { Response } from 'express'
import { db } from './config/firebase'
type EntryType = {
title: string,
text: string,
}
type Request = {
body: EntryType,
params: { entryId: string }
}
const addEntry = async (req: Request, res: Response) => {
const { title, text } = req.body
try {
const entry = db.collection('entries').doc()
const entryObject = {
id: entry.id,
title,
text,
}
await entry.set(entryObject).catch(error => {
return res.status(400).json({
status: 'error',
message: error.message
})
})
return res.status(200).json({
status: 'success',
message: 'entry added successfully',
data: entryObject
})
} catch(error) {
console.log(error);
return res.status(500).json(error.message)
}
}
Im receiving below response from this trigger :
{
"status": "error",
"message": "7 PERMISSION_DENIED: Invalid project number: 113102533737774060828"
}
Is this related to the Cloud Firestore rules in the Google cloud? Im fairly new to Google cloud functions.
Any suggestions would be appreciated.
This typically means that the credentials you're using are not for the project you're trying to use them on.
Check your functions.config().private.key to ensure it is indeed for the project you run this code on.

proxy setting in adal-node package

I am trying to generate token to authenticate to Azure AD in my node server using adal-node package().Its working on my local machines but when trying to run on virtual machines its giving below error:
{
Error: getaddrinfo EAI_AGAIN login.microsoftonline.com login.microsoftonline.com:443
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:57:26)
errno: 'EAI_AGAIN',
code: 'EAI_AGAIN',
syscall: 'getaddrinfo',
hostname: 'login.microsoftonline.com',
host: 'login.microsoftonline.com',
port: 443` }
sample code snippet
var authorityUrl = 'https://login.microsoftonline.com/53d652a4-6f71-416f-971f-*****'
var applicationId = '26915ab6-22fc-4017-8741-***************'; // Application Id of app registered under AAD.
var clientSecret = '2NZtB5mIX1xZaXZ_I6I~-*********'; // Secret generated for app. Read this environment variable.
var resource = 'https://**************.com'; // URI that identifies the resource for which the token is valid.
var context = new AuthenticationContext(authorityUrl);
context.acquireTokenWithClientCredentials(resource, applicationId, clientSecret, function(err, tokenResponse) {
if (err) {
console.log('well that didn\'t work: ' + err.stack);
console.log(err);
res.json(err.stack);
} else {
console.log(tokenResponse.accessToken);
}
Analysis:It looks like proxy issue but unable to figure out how to set proxy url using adal-node package.Kindly suggest the way forward.
If you want to use the proxy server in your application, please refer to the following code
const { AuthenticationContext, Logging } = require("adal-node");
const proxy = require("node-global-proxy").default;
proxy.setConfig({
http: "",
https: ""
});
proxy.start();
const context = new AuthenticationContext(
"https://login.microsoftonline.com/const { AuthenticationContext, Logging } = require("adal-node");
const proxy = require("node-global-proxy").default;
proxy.setConfig({
http: "http://149.28.43.184:8080",
});
proxy.start();
const context = new AuthenticationContext(
"https://login.microsoftonline.com/e4c9ab4e-bd27-40d5-8459-230ba2a757fb"
);
Logging.setLoggingOptions({
log: function (level, message, error) {
console.log(message);
if (error) {
console.log(error);
}
},
loggingWithPII: false,
level: Logging.LOGGING_LEVEL.VERBOSE,
});
var applicationId = ""; // Application Id of app registered under AAD.
var clientSecret = ""; // Secret generated for app. Read this environment variable.
var resource = "";
context.acquireTokenWithClientCredentials(
resource,
applicationId,
clientSecret,
function (err, tokenResponse) {
if (err) {
console.log("well that didn't work: " + err.stack);
} else {
console.log(tokenResponse);
}
}
);
proxy.stop()

Unable to connect to Realm Object Server using NodeJs

I've installed Realm Object Server using the docker container method on a VM on the google cloud platform. The container is running and I am able to connect in a browser and see the ROS page. I am able to connect to it using Realm Studio and add a user.
I have a nodeJS app running locally on a Mac and I'm trying to use that to sign in and write to realm on the server. When I run the app I get an error and the user returned is an empty object. Not sure what I'm doing wrong.
I'm new to NodeJS.
Code:
var theRealm;
const serverUrl = "http://xx.xx.xx.xx:9080";
const username = "xxxx";
const password = "xxxx";
var token = "long-token-for-enterprise-trial";
Realm.Sync.setFeatureToken(token);
console.log("Will log in user");
Realm.Sync.User.login(serverUrl, username, password)
.then(user => {
``
// user is logged in
console.log("user is logged in " + util.inspect(user));
// do stuff ...
console.log("Will create config");
const config = {
schema:[
schema.interventionSchema,
schema.reportSchema
],
sync: {
user: user,
url: serverUrl
}
};
console.log("Will open realm with config: " + config);
const realm = Realm.open(config)
.then(realm => {
// use the realm instance here
console.log("Realm is active " + realm);
console.log("Will create Realm");
theRealm = new Realm({
path:'model/realm_db/theRealm.realm',
schema:[
schema.interventionSchema,
schema.reportSchema
]
});
console.log("Did create Realm: " + theRealm);
})
.catch(error => {
// Handle the error here if something went wrong
console.log("Error when opening Realm: " + error);
});
})
.catch(error => {
// an auth error has occurred
console.log("Error when logging in user: " + error);
});
Output:
Will log in user
Server is running...
user is logged in {}
Will create config
Will open realm with config: [object Object]
TypeError: Cannot read property 'token_data' of undefined
at performFetch.then.then (/pathToProject/node_modules/realm/lib/user-methods.js:203:49)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
TypeError: Cannot read property 'token_data' of undefined
at performFetch.then.then (/pathToProject/node_modules/realm/lib/user-methods.js:203:49)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
Error # user-methods.js:203:49
const tokenData = json.access_token.token_data;
json is:
{ user_token:
{ token: 'xxxxxxxx',
token_data:
{ app_id: 'io.realm.Auth',
identity: 'xxxxxxx',
salt: 'xxxxxxxx',
expires: 1522930743,
is_admin: false } } };
So json.access_token.token_data is undefined but json. user_token.token_data would not be.
I would suggest you to try the ROS connection with realm studio in that u can check logs as well which will help you to fix the error. If your still not able to fix then you can contact Realm support team even they helped me to fix the issue of ROS connection in Xamarin Forms using Docker.

twilio-node unable to reach host "api.twilio.com" TLSWrap.onread

I am getting the following error when using the twilio node module
{ Error: read ECONNRESET
at exports._errnoException (util.js:1026:11)
at TLSWrap.onread (net.js:569:26) code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
{ status: 'ECONNRESET',
message: 'Unable to reach host: "api.twilio.com"' }
I am able to send SMS messages through Postman and their console interface but when trying it through NodeJS I get the error.
The code that I have is this:
var express = require('express');
var app = express();
var twilio = require('twilio');
var accountSid = 'ACXXXXXXXXXXXXXXX';
var apiKey = 'XXXXXXXXXXXXXXXXXXX';
var apiSecret = 'XXXXXXXXXXXXXX';
var twilioClient = new twilio.RestClient(accountSid, apiSecret);
//var account = twilioClient.accounts(accountSid);
//Send an text message
twilioClient.messages.create({
body: 'Hello from Node',
to: '+my_num', // Text this number
from: '+twilio_num' // From a valid Twilio number
}, function(err, message) {
if (err) {
console.log(err);
}
else {
console.log(message);
}
});
I found a similar problem here and followed the posted solution but that didn't work. I am guessing this is an entirely different error.

Resources