I use Firestore v9 in React project. I'm trying to add an item with a creation date. I want to make sure that the date is up to date and the user has not changed it.
My add function:
import { collection, addDoc, Timestamp } from "firebase/firestore";
const startSignal = async () => {
try {
const docRef = await addDoc(collection(db, "signals"), {
active: true,
createdAt: Timestamp.now()
});
console.log(docRef);
} catch (e) {
console.log("error");
console.log(e);
}
}
My firestore rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /signals/{document=**} {
allow write: if request.auth != null && request.resource.data.createdAt == request.time;
}
}
}
When I try to add, I get a refusal. I think that at the time of execution and processing of the request, the time does not match.
How can I make sure that the request has the correct time?
The only value that always equals request.time in security rules is the token returned by serverTimestamp(). serverTimestamp() is discussed in the documentation.
import { serverTimestamp } from "firebase/firestore";
const docRef = await addDoc(collection(db, "signals"), {
active: true,
createdAt: serverTimestamp()
});