Firebase functions with AdminSdk and RealtimeDatabase not working - javascript

I'd like to create, edit, read and delete on the RealTime Database using the firebase functions. Looking at other similar questions I saw that the AdminSdk has to be used, and so I did.
I basically copy/pasted the code provided by the same firebase guides.
const admin = require("firebase-admin");
const functions = require("firebase-functions");
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});
const db = admin.database();
db.ref("devices")
.once("value")
.then(snapshot => console.log("Snapshot: ",snapshot.val())
.catch(error => console.log(error))
});
In the initialization I set the credential with applicationDefault() as I previously set the GOOGLE_APPLICATION_CREDENTIALS env variable with my service_account_key.json path.
I tried anyway to set it with the cert method and the result didn't change. As 3 accounts are showed in the Service account section I tried with all of them as well.
This said,when starting the functions from console with 'firebase serve' the log is not showed and no error either.
Is there anything I'm missing? Some further configuration or whatever error you might be aware of?
Thank you in advance!

Update following your comments:
You want to "create, edit, read and delete on the Realtime Database using Cloud Functions", as indicated in your question, mimicking the behaviour of a Client SDK but from a server that you control. You should use one or more Cloud Functions that you call directly from this server. The most appropriate (based on your comments) would be to use an HTTPS Cloud Function.
For example you could have an HTTPS Cloud Function like the simple one below, to write to a specific node of the Realtime Database, as follows:
exports.writeToNode = functions.https.onRequest((req, res) => {
cors(req, res, () => {
const dbNode = req.body.nodeRef;
const objToWrite = req.body.nodeValue;
return admin.database().ref(dbNode).push(objToWrite)
.then(() => {
return res.send("Node " + dbNode + " updated!");
})
.catch(err => {
//please watch the official video https://www.youtube.com/watch?v=7IkUgCLr5oA&t=1s&list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSM&index=3
});
});
});
You would call it by issuing a POST to the following URL https://us-central1-YOURPROJECTID.cloudfunctions.net/writeToNode, with a body like:
{
nodeRef: 'theNode',
nodeValue: {
firstName: 'John',
lastName: 'Doe'
}
}
Initializing the Admin SDK:
If you want to interact, from a Cloud Function, with the Realtime Database that is in the same Firebase project, you just need to initialize the Admin SDK without any parameter (i.e. admin.initializeApp();)
This way, the Admin SDK will use the Project's default service account, and will have full access to the Realtime Database (i.e. bypassing all the security rules).
So, initialize as follows:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
///// Additional thought /////
Note that you could maybe use the REST API exposed by the Realtime Database, instead of developing an entire set of CRUD endpoints through Cloud Functions. See https://firebase.google.com/docs/database/rest/start
REMAINING PART OF THE CONTENT OF THE INITIAL ANSWER, about background triggered Cloud Functions
You then need to declare a Cloud Function, as shown in the example below, by:
Selecting an "event handler";
Specifying the database path where it will listen for events and;
Executing the desired logic (normally using the data that was written at the path, or indicating that the node was deleted, etc...)
exports.makeUppercase = functions.database.ref('/devices/{pushId}/original')
.onCreate((snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
const original = snapshot.val();
console.log('Uppercasing', context.params.pushId, original);
const uppercase = original.toUpperCase();
// You must return a Promise when performing asynchronous tasks inside a Functions such as
// writing to the Firebase Realtime Database.
// Setting an "uppercase" sibling in the Realtime Database returns a Promise.
return snapshot.ref.parent.child('uppercase').set(uppercase);
});
This code snippet, copied from the documentation, will listen to any new node created under the devices node and will create an uppercase node the value of the original node in uppercase.
Note that this is a background triggered Cloud Function which is triggered when something "happens" at the specific path.
If you want to "create, edit, read and delete on the RealTime Database", as indicated in your question, mimicking the behaviour of a Client SDK, you may define one or more Cloud Functions that you call directly from your App. See the Callable Cloud Functions documentation.
You may alse read the following documentation items https://firebase.google.com/docs/functions/get-started and https://firebase.google.com/docs/functions/database-events and also watch the video series: https://firebase.google.com/docs/functions/video-series

Related

Create multiple Firebase Instances for the same project in Node.js

I have a Node.js server, inside which I want to have two firebase instances.
One instance should use the JavaScript SDK and will be used to provide authentication - login/register. The other instance should use the Admin SDK and will be used to read/write from the Realtime Database. I want to use this approach, so that I don't have to authenticate the user before each request to the Realtime DB.
I've read how we're supposed to initialize Firebase instances for multiple projects, but I'm not sure if my issue isn't coming from the fact that both instances are for the same project.
My issue is that I can use the JS SDK without any issue and I can login/register the user, but for some reason I can't get the Admin SDK to work.
Here's how I'm instantiating the apps:
const admin = require("firebase-admin");
const { applicationDefault } = require('firebase-admin/app');
admin.initializeApp({
credential: applicationDefault(),
databaseURL: 'my-database-url'
}, 'adminApp');
const firebase = require("firebase/app");
firebase.initializeApp(my-config);
Now I can use the JS SDK without an issue, but not the Admin SDK. I've created a test endpoint to just get data from my Realtime DB:
app.get("/api/test", (req, res) => {
const uid = 'my-user-UID';
admin.database().ref(`users/${uid}`)
.once('value', (snapshot) => {
if(snapshot) {
console.log('data');
} else {
console.log('no data');
}
});
});
Now here as an approach to getting the data from the Realtime DB, I tried all possible described approaches. Using get with child and all sorts of possible combinations. Here's an example of another approach I used:
get(child(ref(admin.database()), `users/${uid}`)).then((snapshot) => {
if (snapshot.exists()) {
// retrieved data
} else {
// No data
}
}).catch((error) => {
console.error(error);
});
For the first approach I wasn't getting any response at all, like the once wasn't executing. For the second one I think I was getting - typeerror: pathstring.replace is not a function firebase. At some point I was getting a no firebase app '[default]' has been created . These errors don't worry me as much, but since I saw the last error I moved my focus to the initialization of the apps, but still to no avail.
I just need a direction of where my issue might be coming from.
Update:
The solution is to not pass a second argument (app name) to any of the Firebase initializations. Looks like it's not needed in case you're referencing the same project.

How To Setup Custom Claims In My React Website For a Login Page

I want to set up custom claims to a certain number of users let's say 5 users would be admins on my website. I want these 5 users to be able to log in through the login page which would redirect them to the dashboard.
but I still don't fully understand the concept of the custom claims and how to use them and firebase documentation is limited with examples.
In their example they show that I can pass a uid that I want to assign a custom claim to, but how is this supposed to be a variable when i want certain users uid's from my firestore database Users collection to be admins and have a custom claim, in other words, where would I put this code or how would I assign a custom claim to more than one user at a time and how and where would this code be executed.
if anyone can give me an example of how I would make this work.
here is what I did:
created a firebaseAdmin.js file:
var admin = require("firebase-admin");
// lets say for instance i want these two users to be admins
//2jfow4fd3H2ZqYLWZI2s1YdqOPB42
//2jfow4vad2ZqYLWZI2s1YdqOPB42 what am i supposed to do?
admin
.auth()
.setCustomUserClaims(uid, { admin: true })
.then(() => {
// The new custom claims will propagate to the user's ID token the
// next time a new one is issued.
});
I honestly don't know what to do from here.
Custom Claims can only be set from a privileged server environment via the Firebase Admin SDK. The easiest ways are either using a Node.js script (running the Admin SDK) or a Cloud Function (which also uses the Admin SDK).
Let's look at the example of a Callable Cloud Function that you call from your front-end (and in which you could check the UID of the user who is calling it, i.e. a Super Admin).
exports.setAdminClaims = functions.https.onCall(async (data, context) => {
// If necessary check the uid of the caller, via the context object
const adminUIDs = ['2jfow4fd3H2ZqYLWZI2s1YdqOPB42', '767fjdhshd3H2ZqYLWZI2suyyqOPB42'];
await Promise.all(adminUIDs.map(uid => admin.auth().setCustomUserClaims(uid, { admin: true })));
return { result: "Operation completed" }
});
A Node.js script would be similar:
#!/usr/bin/node
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.cert(".....json") // See remark on the private key below
});
const adminUIDs = ['2jfow4fd3H2ZqYLWZI2s1YdqOPB42', '767fjdhshd3H2ZqYLWZI2suyyqOPB42'];
Promise.all(adminUIDs.map(uid => admin.auth().setCustomUserClaims(uid, { admin: true })))
.then(() => {
console.log("Operation completed")
})
You must generate a private key file in JSON format for your service account , as detailed in the doc.
Then, when the Claims are set, you can access these Claims in your web app, and adapt the UI (or the navigation flow) based on the fact the user has (or not) the admin claim. More detail here in the doc.

sending push notification using firebase functions every time a new child is added in firebase realtime database is not working

I am trying to send a push notification every time a child is created with no success.
I am creating a child with 2 token names with a question mark between them and trying to send to those tokens the notification.
to get the tokens from the phones I am using
new FirebaseMessaging().getToken() .
here is the firebase functions code
`
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Cloud Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
exports.onNewMessage = functions.database.
ref('/messages/{pushId}')
.onCreate((snapShot,context)=>{
var str = snapShot.key();
var res = str.split("?");
// Notification details.
const payload = {
notification: {
title: 'title!',
body: `body!`,
click_action: 'FLUTTER_NOTIFICATION_CLICK'
}
};
// Send notifications to all tokens.
admin.messaging().sendToDevice(res[0], payload);
admin.messaging().sendToDevice(res[1], payload);
});` .
This may have many if-thens, but I will describe here the most common sources of errors
1) Did not grant permissions for notifications for iOS/Android platform. For Android it is fine, and relatively easy to receive notifications, but for iOS you need Developer account to do that (on December 2019 it was 99$ per year)
2) I would recommend using topic subscription instead of tokenization (i.e. .getToken()) as it removes burden of following every single sent message manually
For example:
final fbmsg = FirebaseMessaging();
fbmsg.requestNotificationPermissions();
fbmsg.configure(onMessage: (msg) {
print(msg);
return;
}, onLaunch: (msg) {
print(msg);
return;
}, onResume: (msg) {
print(msg);
return;
});
fbmsg.subscribeToTopic('chats');
You can configure onLaunch, onResume, and onMessage behaviors on your own demand
For (1) and (2), a great place to start is following documentation of firebase_messaging library
3) I am not sure about this, but I think a better way to use index.js file could be using the snapshot that you receive (or at least try console.log() of whatever you get to check validity). But if it works for you, just ignore this step :) Below I attach the code from my app with working notifications
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.myFunction = functions.firestore
.document('chats/{message}')
.onCreate((snapshot, context) => {
return admin.messaging().sendToTopic('chats', {
notification: {
title: snapshot.data().username,
body: snapshot.data().text,
clickAction: 'FLUTTER_NOTIFICATION_CLICK'
},
});
});
4) I had hard time with establishing this Firebase Functions feature, also check installation steps for them as well
5) Check how you are trying to send the notification, first try to simulate it from the console, make sure that receiving part works, and then try to create an automated one
Hope it helped!

How to access multiple Realtime Database instances in Cloud Functions for Firebase

I'm using multiple databases in a Firebase project. Cloud functions for the main (default) database work great, however, I cannot make them work for a secondary database. For example I want to make a read request on a node with admin privileges:
//this works
admin.database().ref(nodePath).once('value')...
This works in the main database, however, if I want to execute the command on another database, it doesn't work:
//this doesn't work
admin.database(secondaryDatabaseUrl).ref(nodePath).once('value')...
Although the functions are deployed, I get an error on the console when trying to execute the cloud function.
Here's the code for the cloud function with an https trigger:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const secureCompare = require('secure-compare');
exports.testFunction= functions.https.onRequest((req, res) => {
const key = req.query.key;
// Exit if the keys don't match
if (!secureCompare(key, functions.config().cron.key)) {
console.error('keys do not match');
res.status(403).send('error1');
return;
}
//test read request
//the line below crashes the function
return admin.database('https://secondary_db_url.firebaseio.com').ref(`/testNode`).once('value').then(dataSnapshot=> {
console.log('value', dataSnapshot.val());
return;
}).catch(er => {
console.error('error', er);
res.status(403).send('error2');
});
});
Below is the error log in the Firebase console:
TypeError: ns.ensureApp(...).database is not a function
at FirebaseNamespace.fn (/user_code/node_modules/firebase-admin/lib/firebase-namespace.js:251:42)
at exports.testFunction.functions.https.onRequest (/user_code/index.js:16:16)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:26:41)
at /var/tmp/worker/worker.js:671:7
at /var/tmp/worker/worker.js:655:9
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
If I don't specify the secondary database URL, the function will make the read request on my main database which works great:
//this works
return admin.database().ref(`/testNode`).once('value').then(dataSnapshot=> {
...
I'm using the latest SDK versions: "firebase-admin": "^5.5.1" and "firebase-functions": "^0.7.3"
So, how do I get an instance of a secondary database in cloud functions using admin privileges?
Here's how to access database by URL using Admin SDK:
let app = admin.app();
let ref = app.database('https://secondary_db_url.firebaseio.com').ref();
Here's an example from Admin SDK integration tests: https://github.com/firebase/firebase-admin-node/blob/master/test/integration/database.js#L52
With cloud functions > 1.1 now, here is the documentation link that saved my life on this issue.
https://firebase.google.com/docs/database/usage/sharding#connect_your_app_to_multiple_database_instances
So, it looks like this at the top of my my cloud function index.js :
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const dev = admin.initializeApp({
databaseURL: "https://appdev.firebaseio.com"
}, 'dev');
const v2 = admin.initializeApp({
databaseURL: "https://appv2.firebaseio.com"
}, 'v2');
and then, in my clond functions functions code I can do :
//will change stuff on default database
admin.database().ref().child(`stuff/${stuffId}`).set(myStuff)
//will change stuff on my dev database
admin.database(dev).ref().child(`stuff/${stuffId}`).set(myStuff)
//will change stuff on my v2 database
admin.database(v2).ref().child(`stuff/${stuffId}`).set(myStuff)
So it looks like you are trying to access multiple databases using the javascript web client API. Passing the URL of the database to the API like this doesn't work with the Admin SDK:
admin.database('https://secondary_db_url.firebaseio.com').ref(`/testNode`)
Instead, you have to initialize a second app, give it a name, and pass that app around to the Admin SDK APIs. Here's a complete sample that writes the same data to two different database instances in the same project:
const functions = require('firebase-functions')
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)
const otherConfig = Object.assign({}, functions.config().firebase)
otherConfig.databaseURL = 'https://your-other-db.firebaseio.com/'
const otherApp = admin.initializeApp(otherConfig, 'otherAppName')
exports.foo = functions.https.onRequest((req, res) => {
const data = { foo: 'bar' }
const p1 = admin.database().ref('data').set(data)
const p2 = admin.database(otherApp).ref('data').set(data)
Promise.all([p1, p2]).then(() => {
res.send("OK")
})
.catch(error => {
res.status(500).send(error)
})
})
Updating this while on Firebase Functions v3.14.0. None of this answers worked for me so I implemented this solution
instance Registers a function that triggers on events from a specific Firebase Realtime Database instance
functions.database.instance('my-app-db-2').ref('/foo/bar')
Use the name of the database instance and it works, no need for the url. functions.database.ref used without instance watches the default instance for events.
So if both the answers doesn't work.
What happened with me is both the method worked without any error but second instance of database was not getting updated.
I updated npm and firebase CLI it worked.
Also #Dough Stevenson you Passing the URL of the database to the API like this **does** work with the Admin SDK
And this is a good blog from Firebase about the same
Firebase Blog : Easier scaling with multi-database support!

How to write a cloud function for firebase that will change data based on time

My firebase database structure looks like this:
-events
-uniqueEventId
-endTimeStamp: 1507949100
-active: true
-uniqueEventId2
-endTimeStamp: 1807949100
-active: true
-uniqueEventId3
-endTimeStamp: 1900949100
-active: true
How do I cloud function which can get all the events with timestamps before the current time and set their active to false.
I'm not sure how you want Cloud Functions to be triggered in this case. I'll assume you want a HTTP trigger, so that you can simply call it from the browser or a web hook.
That means you start with a basic HTTP-triggered function:
exports.updateStatus = functions.https.onRequest((req, res) => {
// ...
res.status(200).send("done");
});
Next up you'll need to access the Realtime Database within this function. To do that you'll use the Firebase Admin SDK, which gives you easy administrative access within your code:
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.updateStatus = functions.https.onRequest((req, res) => {
// ...
res.status(200).send("done");
});
Then we get to the actual code to change the data. This is standard database access code and has little to do with Cloud Functions. In this case you want to query for timestamp, loop over the results, and set the active property:
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.updateStatus = functions.https.onRequest((req, res) => {
let now = Date.now();
let query = admin.database().ref("events").orderByChild("timestamp").startAt(now);
query.once("value").then(function(snapshot) {
var promises = [];
snapshot.forEach(function(child) {
promises.push(child.ref.update({ active: false }));
})
Promise.all(promises).then(function() {
res.status(200).send("done");
});
});
});
That last code is a bit tricky, since it deals with many asynchronous write operations. Cloud Functions will terminate your function after your send the response to the client, so it's important that you only send a response back after all those asynchronous writes are done. I use a Promise.all() for that. For more information on this asynchronous nature, read the documentation, this blog post, and watch this video.
For more info, I'd recommend studying the documentation for the Firebase Admin SDK.

Categories

Resources