Home > database >  Firebase Security Rules allow if datafield is less than x
Firebase Security Rules allow if datafield is less than x

Time:09-08

I have an Events collection and a Users collection. My Event page increments a counter (in Users collection) when an event is uploaded. I want to limit the number of events per user to 10. This what I have so far and it doesn't seem to work as expected:

rules_version = '2';
service cloud.firestore {
    match /databases/collection/Events{
    allow read;
    allow write: if 50 > 
    get(/databases/collection/Users/$(request.auth.uid)).data.numberOfEvents;
  }
}

//Tried this:

rules_version = '2';
service cloud.firestore {
  // Do not change this
  match /databases/{database}/documents {

     // Path to your document
     match /Users/{doc=**} {
     allow read;
     allow write;
     }
    match /Events/{doc=**} { 
        allow read;
      allow write: if get(/databases/$(database)/documents/Users/$(request.auth.uid)).data.numberOfEvents < 50;
    }
  }
}  

Actually the last one seems to work, let me test some more, thanks for all help! It seems to work! Thanks!

CodePudding user response:

I've now tried this:

rules_version = '2';
service cloud.firestore {
  // Do not change this
  match /databases/{database}/documents {

     // Path to your document
    match /Events/{doc=**} { 
        allow read;
      allow write: if get(/databases/$(database)/documents/Users/$(request.auth.uid)).data.numberOfEvents < 50;
    }
  }
}

note: My project is calles flutterLogin and theres a text saying flutterlogin-3adab before my collections

CodePudding user response:

You are not specifying the document path correct. Assuming events and users are both root level collections. Try the following rules:

rules_version = '2';
service cloud.firestore {
  // Do not change this
  match /databases/{database}/documents {

     // Path to your document - collection names are case sensitive
    match /events/{eventId} { 
      allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.numberOfEvents < 10;
    }
  }
}

You should however not allow users to write to numberOfEvents directly from client as they can reduce the number and try to add more events. Firestore triggers for Cloud functions might be useful here to increment/decrement the value securely from backend.

  • Related