Reputation: 126824
I want to send the creation time of a Firestore document through the client and verify the time with Firestore Rules to avoid Cloud Functions calls (pricing).
I am testing requests from clients against Firestore rules like this:
allow create: if request.resource.data.TIMEFIELD == request.time;
The request contains a TIMEFIELD
that has a timestamp, just like request.time
.
Apparently the request time and the time I am setting as a field right before sending the request are not equivalent, which makes this comparison impossible.
The following is the defition of request.time
from the documentation.
I wonder if there is a way to set a field in a document equal to request.time
.
I am unable to use server side timestamps because of an issue with Flutter.
Because of that I need to know how I could possibly validate client side timestamps like time.now
with Firestore Rules.
Upvotes: 6
Views: 1771
Reputation: 126824
This has been implemented into the Flutter plugin for Cloud Firestore:
FieldValue.serverTimestamp()
Using this as a field's value will assign a timestamp equal to request.time
to the field, server-side.
You can find out more about it in the API reference for cloud_firestore
.
Upvotes: 2
Reputation: 1159
You can use the Timestamp
to add constraints to the time field (docs).
Here is an example of how to ensure that the change was within a certain amount of seconds:
function withinSeconds(secs) {
return request.resource.data.TIMEFIELD.seconds() - request.time.seconds() <= secs
&& request.resource.data.TIMEFIELD.seconds() - request.time.seconds() >= -secs
}
The above is for setting the value within a threshold of the request.time
.
You can also just use the REST API in the mean time. Just make a write
request that includes an update
and a transform
. The transform
is where you would set the server timestamp. Here is a tool to help understand how to build the requests.
Upvotes: 2
Reputation: 76769
you'd first have to remember the creation (or last updated) timestamp:
firestore().collection("items").add({
....
created: firebase.firestore.FieldValue.serverTimestamp()
});
in order to let the client know of the timestamp, which you are trying to compare later on.
Upvotes: 0