Ondřej Rehák
Ondřej Rehák

Reputation: 603

Firestore Security Rules: If timestamp (FieldValue.serverTimestamp) equals now

How do I check if user on client sided created document with only firebase.firestore.FieldValue.serverTimestamp()?

I have following:

allow create: if request.resource.data.timestamp == ??

What should I have instead of ??. I have tried serverTimestamp() firebase.firestore.FieldValue.serverTimestamp(), now or now() but it doesn't work.

It is possible to do it in Firebase like this:

".validate": "newData.child('timestamp').val() === now"

I am looking for the same solution. Any ideas? Thanks

Upvotes: 28

Views: 6474

Answers (1)

Mike McDonald
Mike McDonald

Reputation: 15963

You can access the current request timestamp in Security Rules using the request.time attribute (docs), which is the Firestore equivalent to the Realtime Databases's now. You'll therefore want something like:

allow create: if request.resource.data.timestamp == request.time;

For serverTimestamp() this should evaluate to true.

You should always validate client input in Security Rules, even if you're using serverTimestamp(). Security Rules doesn't automatically know the server input the value instead of the client, so without this check, a malicious client could create a different created at time.

Upvotes: 42

Related Questions