Home > Software design >  Is there a way to add an aditional restriction to all firebase security rules (not one by one)? Alte
Is there a way to add an aditional restriction to all firebase security rules (not one by one)? Alte

Time:10-03

I want to use an aditional restriction to access all my collections and documents (write, read...). For example Only be able to do anything if the user has one parameter = true. Ej active=true, or handsom = true.

I could add a restriction to each of the conditions, but i was hoping to create an adittional restriction that applies to every existing rule

 match /projects/{document} {
      allow create: if true;
      allow read: if request.auth != null;
      allow write: if request.auth != null;
      allow delete: if request.auth != null;
    }
match /cities/{city} {
  allow update: if request.resource.data.population > 0
                && request.resource.data.name == resource.data.name;
}
 match /{path=**}/objetives/{document} {
      allow read: if true;
    }

One of the reasons I would like to do that is to be able to disable users with an update document call.

The rule i think it would be:

&& get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true

being "admin" the name of my parameter (data.handsome or data.active).

CodePudding user response:

No, you would have to add that to all the required rules separately. You can use a function so you don't have to repeat it as shown below:

function hasRole(userId, role) {
  return get(/databases/$(database)/documents/users/$(userId)).data[role] == true;
}


// example 
match /projects/{document} {
  allow create: if true;
  // pass the required role in the function 
  allow read: if request.auth != null && hasRole(request.auth.uid, "user");
  allow delete: if request.auth != null && hasRole(request.auth.uid, "admin");
}
  • Related