I need to add a match database for a collection of documents without authentication. What is the correct way to do this? This is the current security rule:
service cloud.firestore {
match /databases/{database}/documents {
function authenticated() { return request.auth.uid != null }
match /users/{userId} {
allow get: if authenticated() && request.auth.uid == userId;
allow create: if authenticated() && request.auth.uid == userId;
allow update, delete: if authenticated() && request.auth.uid == userId;
}
match /users/{userId}/products/{productId} {
allow get: if authenticated() && request.auth.uid == userId;
allow list: if authenticated() && request.auth.uid == userId;
allow create: if authenticated() && request.auth.uid == userId;
allow update, delete: if authenticated() && request.auth.uid == userId;
}
}
}
I tried adding this but I still get a Firestore insufficient permissions error:
function notAuthenticated() {
return request.auth == null;
}
match /share/{id}/documents {
allow get: if notAuthenticated();
allow create: if notAuthenticated();
allow read: if notAuthenticated();
This is the JS code for adding a "share" to the Firestore.:
const db = firebase.firestore()
const docRef = db.collection('share').doc(val)
docRef
.get()
.then(doc => {
if (doc.exists) {
console.log('Document data:', doc.data().id)
} else {
console.log('No such document!')
}
})
.catch(error => {
console.log('Error getting document:', error)
})
enter code here
Your current code specifically only allows users that are not signed in to Firebase Authentication. So it rejects operations from users that are signed in.
It sounds like you want anyone to be able to read that specific collection, no matter whether they are signed in to Firebase Authentication or not.
The simplest rules for that would be:
match /share/{id}/documents {
allow get: if true;
allow create: if true;
allow read: if true;
I'd definitely recommend adding some validation to the create
rule in this case, as with the above anyone can write (which is what you want) whatever data they feel like (which you probably don't want) to your database.