According to Allowing write access only to Cloud Functions for Firebase in order to set user uid and other auth info for database rules your function should be like this:
var functions = require('firebase-functions');
var admin = require('firebase-admin');
exports.foo = functions.database.ref('/bar')
.onWrite(event => {
var firebaseConfig = functions.config().firebase;
firebaseConfig.databaseAuthVariableOverride = {
uid: 'some-uid',
foo: true,
bar: false
};
admin.initializeApp(firebaseConfig);
...
}
But when we run this code in our function we get the following error:
The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once. But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name.
So what is wrong in this code? Is this the right way to set uid? Or is there an (un)documented uid for functions or another way to set a rule that only allows writes from cloud functions?
UPDATE - SOLVED
We got this solved, the problem was that the referenced answer is (I guess) for Google Cloud Functions and we are writing a Cloud Function for Firebase.
In Cloud Functions for Firebase, event.data
is a DeltaSnapshot object which has ref
and adminRef
properties. ref
has the same access as the user who triggered the event while adminRef
has unrestricted read/write privilegies. So in order to allow only the function to write to a path the write action must be denied in rules and the function must write using adminRef
.
This was solved thanks to the answer given for Some Firebase security rules apply for admin in Cloud Functions and Google documentation for DeltaSnapshot.