I want to make a simple Form to collect user emails on my website deployed on Firebase. I want to prevent bots thus I enabled an 'App Check' with ReCaptchaV3. User must be able to post only one submission and since my website doesn't have registration I implemented an anonymous authentication so that ID is automatically set for each user.
How do I check that user is authenticated and captcha is passed in Firestore rules?
Here is code for a function to write a submission
export const writeUserData = async (email) => {
const db = getFirestore();
const uid = auth.currentUser?.uid
const docRef = await addDoc(collection(db, `newsletter/${uid}/entries`), {
email: email
});
console.log(docRef);
}
Here is Firestore ruleset
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
allow read: if false;
match /newsletter/{userId}/entries {
allow write: if request.auth != null;
}
}
}
What do I get:
Uncaught (in promise) FirebaseError: Missing or insufficient permissions.
I end up with the following rule set
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /newsletter/{userId}/entries/{document=**} {
allow write: if request.auth != null && request.auth.uid == userId;
}
}
}
It works only if I add {document=**}
to the collection I want edit