Home > Enterprise >  Creating security rule depend on doc data
Creating security rule depend on doc data

Time:06-25

I just added new value to my users collection appVersion

My user collection like:

documents/users/5kwgNgGi3sY6oCbUAg9v

enter image description here

so i just added value versionCode to collection. if user download new app it will be update My rule now:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
          allow read, write: if request.auth !=null
    }
  }
}

what i need as a if else statement

if(request.auth!=null){
firebase().collection('users').where('UID','==',request.auth.uid).get().then(x=>{
    if(x.docs[0].versionCode==4){
      allow
    }
    else{
      deny
    }})
else{
  deny
}

CodePudding user response:

There is no way to perform a query in your security rules, as that would never scale on the backend.

Instead, what you'll want to do is store the user documents with the UID as the document ID, so that the document you show is at path documents/users/xHzKoXbrZqbHZY8DI3wkXnMShF92. Then you can use get() in your rules to load the document, as shown in the documentation on accesing other documents in your rules.

I'd also recommend checking out the documentation on attribute-based and Role-based access, as it covers a pretty similar scenario.

  • Related