Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase: How to prevent writing a specific field in firestore? [duplicate]

The ruleset protects the user's entry like follows:

  • only him or an admin can read his data
  • only an admin can update a user's permissions
  • a user can update all his data, unless he sets the permissions object

The rule looks like:

match /users/{userId} {
  allow read: if isCurrentUser(userId) || isAdmin();
  allow write: if (isCurrentUser(userId) && !isModifyingPermissions()) || isAdmin();

  function isModifyingPermissions(){
    return request.resource.data['permissions'] != null;
  }
}

I'm stuck with the isModifiyingPermissions() function. It properly refuses a write in case the request has a value for the permissions property. However, the rule crashes if no permissions property is provided, stating the following:

Error: simulator.rules line [19], column [15]. Property permissions is undefined on object.

How can one write "check presence of a property on request resource" ?

like image 621
Jem Avatar asked Aug 09 '18 14:08

Jem


People also ask

How do I stop duplicates in firestore?

There is no way to check for duplicates in the entire collection in security rules, as that would require Cloud Firestore to read all documents in the collection (which would become very expensive at scale). The above only allows creating a document, it does not allow updating it.

How do you make a field unique in firestore?

You can use Firestore queries to get the document ID which corresponds to the field you want to keep unique. If the query returns null , that would mean that the database doesn't contain that value., ergo, the username , in this case, is available or vice versa.

How do I add a rule to firestore?

Use the Firebase console To set up and deploy your first set of rules, open the Rules tab in the Cloud Firestore section of the Firebase console. Write your rules in the online editor, then click Publish.

What is a Subcollection in Firebase?

A subcollection is a collection associated with a specific document. Note: You can query across subcollections with the same collection ID by using Collection Group Queries. You can create a subcollection called messages for every room document in your rooms collection: collections_bookmark rooms. class roomA.


1 Answers

Ok, here's the solution:

  function isModifyingPermissions(){
    return request.resource.data.keys().hasAny(["permissions"]);
  }
like image 189
Jem Avatar answered Sep 25 '22 08:09

Jem