Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Firestore prevent client side creation of fields in a document

I am struggling to find a solution to prevent clients from just creating random fields with values in a document where they have write access to in Firestore. Since you cannot restrict access to single fields in Firestore like you could with the realtime database, this seems hard to achieve.

A solution would maybe be to not allow creation of fields and just letting clients update fields, but this would mean you would have to precreate the fields for documents which is not really a good solution in my opinion, especially if you have documents per user, which are dynamically created and having to use cloud functions to precreate fields in a document just seems unjustified.

Does anyone have a better solution?

like image 524
Luis Avatar asked Mar 07 '23 15:03

Luis


1 Answers

As said in the Firebase Firestore documentation, you actually can prevent or allow writes or reads in certain fields. This can be achieved by adding a rule similar to this:

match /collection/{doc} {
  allow update: if request.resource.data.field == resource.data.field;
}

Which would basically check if that specific field will have the exact same value after the update. You can also add rules to check if the requested value is between a range or equals to (your predefined value).

allow update: if request.resource.data.field > 0 && request.resource.data.field > 100;
like image 132
Alejandro Bertinelli Avatar answered Mar 09 '23 04:03

Alejandro Bertinelli