0
votes

I'm building a contact form and understood that a quick way to do it would be to write the data into the firestore and then use the trigger e-mail extension to fire the email.

I've set up the contact form page already and are sending the fields after input validation to the firestore:

let db = firebase.firestore();
db.collection("users").add({
    name: getInputVal('name'),
    email: getInputVal('email'),
    phone: getInputVal('phone'),
    message: getInputVal('message')
})
.then((docRef) => {
    console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
    console.error("Error adding document: ", error);
});

I'm using Firestore only for messages (and everything else is kept in the real-time database, where i've managed to create sufficient security rules). Looks like something is wrong with my permissions?

What i'd like to set-up:

  1. Allow non-authenticated users to write into Firestore messages collection
  2. Allow only admin users to read/delete messages
  3. Set up a validation on db level that the length of any fields wouldn't exceed 200 characters and would only be with a type of String

I tried following the logic from real time database, and have the following rules:

rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
    match /messages/{message}{
        allow write: if true
        allow read: if "request.auth.uid === 'my_user_id'"
    }
}
}

However, I end up catching an error FirebaseError: Missing or insufficient permissions. every time I try to run the code above.

1

1 Answers

1
votes

The following should do the trick:

rules_version = '2';
service cloud.firestore {
   match /databases/{database}/documents {
       match /users/{user}{
         allow create: if true;
         allow read, delete: if request.auth.uid === 'my_user_id';
       }
   }
}

Note that you should not put quotes around request.auth.uid == 'my_user_id';

Note also that you should use more granular operations, i.e. create and delete.


For the requirement "the length of any fields wouldn't exceed 200 characters and would only be with a type of String" you need, for each field, to do:

allow create: if request.resource.data.field1.size() < 200 && request.resource.data.field2.size() < 200;