Reputation: 668
I would like to write some data into Firebase Firestore from Cloud Functions, however, it was failed and I got following error message.
Missing or insufficient permissions.
Since it looks security rule issue, I changed the Firestore security rule like below. It must be the loosest security rule.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write;
}
}
}
In addition, I wait for a few minutes because it takes time to apply the new security rule. However, still failed...
Following the Cloud functions code.
const admin = require('firebase-admin');
admin.initializeApp()
const firestore = admin.firestore();
exports.sampleAPI = functions.https.onRequest((request, response) => {
const text = request.body.text
writeText(text).then(value => {
console.log("==== Operation DONE ====")
response.status(200).send("OK")
return null
}).catch(error => {
console.error("xxxxxx Operation FAILED xxxxxxx")
console.error(error)
response.status(500).send(error)
})
}
async function writeText(text) {
const textRef = firestore.collection('texts')
return textRef.add({
text: text,
}).then(docRef => {
const id = docRef.id
return id
}).catch(error => {
throw error
})
}
How can I fix this issue ??
Upvotes: 1
Views: 731
Reputation: 6354
You might want to review this documentation.
2 things about your approach:
1) The syntax for the allow line in the security rule doesn't look correct for what you are trying to do as it is missing the if <condition>
clause, based on the examples on that page above it should read:
// Allow read/write access to all users under any conditions
// Warning: **NEVER** use this rule set in production; it allows
// anyone to overwrite your entire database.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
Having tried this, though, omitting this does appear to generate a warning that the database is open to all, so it is unlikely to be the problem.
2) That page also makes clear that cloud functions do not rely on the security rules for the database and instead depend on IAM, so you might want to check the identity that the function is runnning as as well as the roles that identity has. (More here). However, generally the defaults should work here (especially if you are only using firebase and not the regular Google cloud console).
One last thing, in your function code you never actually require the functions module. You need to include a line like this as well:
const functions = require('firebase-functions');
This, of course, should fail during deployment with an error like "ReferenceError: function is not defined" as the javascript will not parse.
If this doesn't help, please provide more information about the error you are getting (when is it being generated -- on deployment? when the function is executed?, is there any stack trace, etc).
Upvotes: 1