Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 693
Ondřej Rehák Avatar asked Feb 14 '18 09:02

Ondřej Rehák


People also ask

Does firestore have timestamp?

firestore. Timestamp. A Timestamp represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian Calendar which extends the Gregorian calendar backwards to year one.

What is firestore security rules?

Cloud Firestore Security Rules allow you to control access to documents and collections in your database. The flexible rules syntax allows you to create rules that match anything, from all writes to the entire database to operations on a specific document.

What is firestore FieldValue?

firestore. FieldValue. Sentinel values that can be used when writing document fields with set() or update() .


1 Answers

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.

like image 88
Mike McDonald Avatar answered Oct 20 '22 04:10

Mike McDonald