skip to Main Content

Below code works if I have collection (in this case suppliers)

function isNotRestrictedinSuppliers(){
  let value=3;
  let suppliers=get(/databases/$(database)/documents/users/$(request.auth.uid)/settings/suppliers);
  return suppliers.data.suppliers_array.size() < value;
  //return true;
}
 match /suppliers/{document=**}{        
    allow read,update, delete: if isSignedIn() && isValidUser();
    //above is the same like allow write;
    allow create: if isSignedIn() && isValidUser() && (isPremium() || isNotRestrictedinSuppliers());  
}
match /suppliers/{supplier}{        
    allow read,update, delete: if isSignedIn() && isValidUser();
    //above is the same like allow write;
    allow create: if isSignedIn() && isValidUser() && (isPremium() || isNotRestrictedinSuppliers());  
}

Unfortunately, if there is no collection "suppliers" it doesn’t work.
What I want to do is restrict creation of suppliers but create if no supplier exists

2

Answers


  1. I think there is no way to read a collection in sercurity rules. This is what document says:

    The get() and exists() functions both expect fully specified document paths.

    But you can count documents with aggregation queries via client sdk.

    Login or Signup to reply.
  2. Firebase Security Rules won’t allow users to create if/else conditions. So basically you need to create another function to check if supplier documents exist and return true if it doesn’t exist

    function notExists(){
      let suppliers=exists(/databases/$(database)/documents/users/$(request.auth.uid)/settings/suppliers);
      return !suppliers
    }
    

    This would cost one additional read per security check

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search