noriktal
noriktal

Reputation: 93

Firestore Security Rules- enforcing timestamp type when field may be missing

I have a firestore collection whose documents contain two optional date fields (not all documents contain them). I am not sure how to use the security rules to enforce the fields content type although they may be missing.

  1. Currently, these date fields are created with firebase.firestore.Timestamp.fromDate() . I think I can write a statement that looks roughly like this*:

allow write: if request.resource.data.get("RecordDate", ?) is timestamp;

but I am not sure what could be the second argument for get() in this case (the "?").

*(based on the documentation here: https://firebase.google.com/docs/firestore/security/rules-fields#enforcing_types_for_optional_fields)

  1. I might be changing the method for the creation of these fields to firebase.firestore.FieldValue.serverTimestamp(). In that case, how is it possible to use the following rule (or an equivalent), but still allow for missing fields?

allow write: if request.resource.data.recordDate == request.time;

Hope the questions are clear enough- pls bear with me, I am a newbe.

Upvotes: 3

Views: 680

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 599571

You can use a simple or condition like this:

if !("RecordDate" in request.resource.data.keys) 
  ||(request.resource.data["RecordDate"] is timestamp)

Upvotes: 1

DIGI Byte
DIGI Byte

Reputation: 4162

Firebase Security Rules cannot modify or change the values requested, you can only allow or deny a request. If you want to ensure a certain field is of a timestamp, you can only compare it to the valid types that are listed in the reference documentation:

Firestore Security Rules: Types - Timestamp

To allow for missing fields you can use an OR operator || and wrap conditions inside () to group their logic together.

request.auth.uid != null || (resource.data.visibility == 'public' && request.auth.uid == resource.data.owner);

Upvotes: 0

Related Questions