Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore Security - allow only known fields

I can’t figure out how to properly set the ‘.validate’ rule in Firestore. Basically, I want to allow a User document to contain only the fields I know:

user {
 name: "John"
 phone: "2342222"
 address: "5th Avenue"
}

I dont want any other fields besides the 3 above (name, phone, address).

The fields WON’T be saved at the same time. name and phone will be saved first, and address will be saved only when user wants to edit his profile.

I've tried the rules below but don’t seem to work:

allow read: if request.auth.uid == uid;
allow write: if request.auth.uid == uid && 
 request.resource.data.keys() in ["name", "phone", "address"]

Thanks for help.

like image 956
Fabio Berger Avatar asked Oct 06 '17 13:10

Fabio Berger


People also ask

How do I change my security rules on 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.

Is firestore better than Realtime Database?

Cloud Firestore also features richer, faster queries and scales further than the Realtime Database. Realtime Database is Firebase's original database. It's an efficient, low-latency solution for mobile apps that require synced states across clients in realtime.


Video Answer


1 Answers

You can separate your rules to include different create and update (as well as delete) logic:

// allows for creation with name and phone fields
allow create: if request.resource.data.size() == 2
              && request.resource.data.hasAll(['name', 'phone'])
              && request.resource.data.name is string
              && request.resource.data.phone is string;
// allows a single update adding the address field
// OR (||) in additional constraints
allow update: if request.resource.data.size() == resource.data.size() + 1
              && !('address' in resource.data)
              && request.resource.data.address is string;
like image 64
Mike McDonald Avatar answered Sep 30 '22 16:09

Mike McDonald