Recently I Was Working On A Platform Where I Came Across A Problem Where I Want To Compare A Timestamp Stored In The Users Database And The Time Of Request In Firebase Rules. This Is So That One Can Read The Document Only If He/She Requests Only After A Certain Time.
Here Are The Codes I Tried To Use So Far.
Note: The Fieldname strton
refers to a Time Stamp Object In The Document Of The Database.
match /tests/{testsID}{
match /response/{responseID}{
allow read: if get(/databases/$(database)/documents/tests/{testID}).data.strton < request.time;
}
}
match /tests/{testsID}{
match /response/{responseID}{
allow read: if get(/databases/$(database)/documents/tests/{testID}).data.strton.toMillis() < request.time.toMillis();
}
}
Any Help On How I Can Achieve This Is Appreciated.
Updates: Here's The Document Structure(Private Info Has Been Censored) And The Code Which Is Trying To Access It
docRef = doc(db, "tests", testid,"responses",auth.currentUser.uid);
docSnap = await getDoc(docRef);
if (docSnap.exists()) {
testResponseList = docSnap.data()
}else {
await setDoc(doc(db, "tests", testid,"responses",auth.currentUser.uid), {
answers:[]})
One More Thing Is That The Document Which This Code Is Trying To Get Doesnt Exist Right Now. And The Else Statement Is For Making The Document If It doesnt Exist. But the else statement is not executed.
CodePudding user response:
You are using the {wildcard}
expression syntax that is used in document path with /match
in get()
. Instead you should be using $(testsID)
.
Also there are a few spelling errors:
- Your collection name is
responses
but you haveresponse
in rules - It is
testsID
in wilcard but you havetestID
Try refactoring the rules as shown below:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /tests/{testID} {
match /responses/{responseID} {
allow read: if get(/databases/$(database)/documents/tests/$(testID)).data.strton < request.time;
}
}
}
}