oth man
oth man

Reputation: 303

How to limit in Cloud Firestore security rules

I'm making a charity app that uses the Firebase SDK to directly talk to Cloud Firestore from within the application

Anyone (user or not) can create a charity, every charity is located in a city.

If the user adds a new one, I want to stop the other users from creating a new charity for 30 minutes in the city he created the charity in.

And I think this is the way to implement the 30 minute duration but how can I make it in each city

match /charity/{document=**} {
  allow create: if isCalm(); 
  request.time > resource.data.timestamp + duration.value(30, 'm');
 }
}

If you didn't understand here's an example : let's say i have 3 cities (A B and C) , if the user create a charity in city A i want to stop anyone from creating charities in city A for 30 minutes ..

Upvotes: 0

Views: 112

Answers (2)

Ben Butterworth
Ben Butterworth

Reputation: 28492

I have not tried this myself.

If you have 1 collection, called Cities, and in that, a subcollection called charities. Then, when you access your specific charity subcollection to go and write a new charity document, a security rule can ensure that parent (city) field meets your condition of at least 30 minutes. You would have to create a new field, lastModified or lastCharityCreatedAt in the city document. This way, you don't need cloud functions.

In summary: keep track of the last write, in a parent document so you can check it when you need to.

Upvotes: 1

Milvintsiss
Milvintsiss

Reputation: 1448

I'm not sure you can handle this with rules... And if you can when an user will try to create a new charity it will trown an exception witch is not a good practice... You're better to add a TimeStamp to your Firestore document, get the document and verify if 30 minutes have past

Upvotes: 1

Related Questions