Firebase Admin SDK network app/network-error - node.js

I have the following nodejs script.
const admin = require("firebase-admin")
admin.initializeApp({
credential: admin.credential.cert("./serviceAccountKey.json"),
databaseURL: "https://<ProjectID>.firebaseio.com/"
})
const uid = "5mP5FvjjCKcJ1IBXfV3rpChd3ob2"
admin
.auth()
.setCustomUserClaims(uid, { role: 'admin' })
.then(() => {
// The new custom claims will propagate to the user's ID token the
// next time a new one is issued.
console.log(`Admin claim added to ${uid}`)
})
.catch((err) => console.log(err))
When I run the script I get the following error.
{
errorInfo: {
code: 'app/network-error',
message: 'Error while making request: connect ECONNREFUSED 127.0.0.1:9099. Error code: ECONNREFUSED'
},
codePrefix: 'app'
}
What am I doing wrong here?
Also, my firebase project has the spark plan.

Related

Discord.js Missing Permissions while adding user to role

I am running into an "DiscordAPIError: Missing Permissions " error when trying to add a member to a role. My code is:
const role: Role = await this.getRole(requestingUser, roleId);
const member: GuildMember = await this.getGuildMember(memberId);
await member.roles.add(role);
The client should have the intents it needs. This is the code we use for getting the client instance for the calls:
async getClient () {
if (!this.client) {
// eslint-disable-next-line no-async-promise-executor
this.client = await new Promise(async (resolve, reject) => {
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS,
Intents.FLAGS.GUILD_MESSAGES
]
});
client.on('error', async (error) => {
reject(error);
});
client.on('ready', async () => {
resolve(client);
});
await client.login(this.botToken);
});
}
return this.client;
}
The bot does have have 'manage roles' permission:
The stack trace once it hits discord.js code:
DiscordAPIError: Missing Permissions
at RequestHandler.execute (/usr/src/app/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/usr/src/app/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async GuildMemberRoleManager.add (/usr/src/app/node_modules/discord.js/src/managers/GuildMemberRoleManager.js:124:7)
This is using discord.js 13.6.0 and node.js 16.6.0
Any ideas?
If a role is higher than a user or bot's highest role, it's basically read-only for you, even if you have the ADMINISTRATOR permission. The only thing that bypasses this is being the owner. Either move the bot's role up, the role being given down, or do a check and send an error message if it's higher
if (
role.position >= guild.me.roles.highest.position ||
!guild.me.permissions.has("MANAGE_ROLES")
) return interaction.reply({
content: "I don't have permissions to grant this role!",
ephemeral: true
})

Firebase Functions - FirebaseError: Missing required options (force) while running in non-interactive mode

I have a Firebase Function that deletes a user's collection in a Firestore database when their account is deleted.
const firebase_tools = require("firebase-tools");
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.deleteUser = functions.auth.user().onDelete((user) => {
return firebase_tools.firestore
.delete(`users/${user.uid}`, {
project: process.env.GCLOUD_PROJECT,
token: functions.config().fb.token,
recursive: true,
yes: true
}).catch((error) => {
console.log(error);
throw new functions.https.HttpsError(
"unknown",
"Error deleting user's data"
);
});
});
Whenever a user is deleted and the function is executed, I get the following error in the Functions logs.
FirebaseError: Missing required options (force) while running in non-interactive mode
at prompt (/workspace/node_modules/firebase-tools/lib/prompt.js:16:15)
at promptOnce (/workspace/node_modules/firebase-tools/lib/prompt.js:29:11)
at Command.actionFn (/workspace/node_modules/firebase-tools/lib/commands/firestore-delete.js:69:51)
at Object.delete (/workspace/node_modules/firebase-tools/lib/command.js:190:25)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
The only information I could find related to this is regarding deploying/deleting functions to Firebase and there's not much documentation for firebase-tools that I could find.
Add force: true to the JSON passed to firebase-tools. Worked for me with version 10.1.4
{
project: process.env.GCLOUD_PROJECT,
token: functions.config().fb.token,
recursive: true,
yes: true,
force: true // add this
}
I've reproduced the error that you have encountered.
This error occurs on the latest "firebase-tools": "^10.1.3".
Based on the Delete data with a Callable Cloud Function, the documentation have sample code that still uses "firebase-tools": "9.18.0".
You could downgrade your firebase-tools by modifying the package.json. E.g. below:
"dependencies": {
"firebase": "^9.6.5",
"firebase-admin": "^9.12.0",
"firebase-functions": "^3.16.0",
"firebase-tools": "9.18.0"
}
After downgrading, I'm able to delete the specified document successfully.
You could also use what's #Renaud Tarnec answered by using Admin SDK.
E.g. below:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
db = admin.firestore();
exports.deleteUser = functions.auth.user().onDelete((user) => {
db.collection("users").doc(user.uid).delete()
.then(function(user) {
console.log("Successfully Deleted User:", user.uid)
})
.catch((error) => {
console.log(error);
throw new functions.https.HttpsError(
"unknown",
"Error deleting user's data"
);
});
});

Importing firebase in node.js for cloud functions

I was following a tutorial for writing cloud functions, i tried to import firebase and use firebase.auth() as used in tutorial, but i am getting the below error.
⚠ Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in /home/sankethbk7777/Desktop/React/Projects/social-ape/my-code/social-ape/functions/node_modules/firebase/package.json
at throwExportsNotFound (internal/modules/esm/resolve.js:299:9)
at packageExportsResolve (internal/modules/esm/resolve.js:522:3)
at resolveExports (internal/modules/cjs/loader.js:449:36)
at Function.Module._findPath (internal/modules/cjs/loader.js:489:31)
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:875:27)
at Function.Module._load (internal/modules/cjs/loader.js:745:27)
at Module.require (internal/modules/cjs/loader.js:961:19)
at require (internal/modules/cjs/helpers.js:92:18)
at Object.<anonymous> (/home/sankethbk7777/Desktop/React/Projects/social-ape/my-code/social-ape/functions/index.js:19:18)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
⚠ We were unable to load your functions code. (see above)
code
functions/index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const app = require('express')();
admin.initializeApp();
const config = {
apiKey: 'AIzaSyDMFe1IwnLoui-Meue-FMwNhc1k-MB8vc8',
authDomain: 'socialape-d306c.firebaseapp.com',
projectId: 'socialape-d306c',
storageBucket: 'socialape-d306c.appspot.com',
messagingSenderId: '705972174784',
appId: '1:705972174784:web:1ed87302a774bd1cef1225',
};
const firebase = require('firebase');
firebase.initializeApp(config);
// Signup route
app.post('/signup', (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password,
confirmPassword: req.body.confirmPassword,
handle: req.body.handle,
};
// TODO: validate date
firebase
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.password)
.then((data) => {
return res
.status(201)
.json({ message: `user ${data.user.uid} signed up successfully` });
})
.catch((err) => {
console.log(err);
return res.status(500).json({ error: err.code });
});
});
// To tell firebase cloud functions to use routes on express app
// we have written api because we want all our API URL's to start with /api.
exports.api = functions.https.onRequest(app);
I know import could be little different because of version change (the tutorial is from 2019) but i am not able to fix it. Please help me
You should use the Admin SDK in a Cloud function and not the client. That being said you can remove the const firebase = require("firebase") and firebase.initializeApp(config); along with the client configuration. To create users, you can use the createUser() method:
app.post('/signup', (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password,
confirmPassword: req.body.confirmPassword,
handle: req.body.handle,
};
return admin.auth().createUser({ email, password }).then((userRecord) => {
return res.send(`Created user ${userRecord.uid}`)
})
}
I am not sure what the 'handle' is but you can use Custom Claims or any database to store it.
Do note that creating users in a Cloud function or a server environment won't log the user in automatically. You must redirect users to your login page after returning the response.

Error method sendAll() in nodejs using firebase-admin

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

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.

Resources