Jonah Snider
Jonah Snider

Reputation: 374

Per field rules in Firestore Security Rules

I have a bunch of documents that contain a few fields each. How can I write rules that only apply to a specific field in each document?

For example, if my documents looked like this:

{
  "displayName": "John Doe", // read and write
  "accessLevel": 3 // read only
}

How could I make it so that you can

I've gone through a lot of videos and Firestore docs and haven't found anything that shows how you would exercise this per-field control.

Upvotes: 1

Views: 77

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

What you're looking for is to make a field non-modifiable. You do that by checking in your rules that the value of the field is the same after the request as before it.

I have a simple helper function for this in my rules:

function isUnmodified(key) {
  return request.resource.data[key] == resource.data[key]
}

I then call this function from within my write (or create and update) rules:

  allow update: if isAdmin() || isUnmodified('name');

So in my example above, any admin (as determined by my isAdmin function) can modify the name field, but other users can't.

Upvotes: 1

Related Questions