Search code examples
firebasegoogle-cloud-firestorefirebase-security

Get role in every rule Firebase security


Hello so I have a role in my user collection and I wanted to write the rules depending on the role so if the role is the teacher you can have access to a little more stuff than the parent role. Now my question is there a possibility that I can access the role and use it for every collection, not only the user collection. Like a function that just checks every time what your role is? I'm doing this for the first time and I'm not pretty sure if I understand everything right, so far.

This is what I have in my rules so far:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
  
  function isSignedIn() {
      return request.auth != null;
    }

   function isOneOfRoles(rsc, array) {
      return isSignedIn() && ((getRole() in array) || rsc.data.openWorld == true);
}
    function getRole() {
    return get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 'pädagoge';
}
   
      
    match /posts/{userPosts} {
      allow read: if isSignedIn();
      allow create: if isOneOfRoles(resource, ['pädagoge']);
    }
     match /messages/{messages} {
      allow read, write: if isSignedIn();
      
    }
  }
}

UPDATE

enter image description here

enter image description here

enter image description here

enter image description here


Solution

  • I've tried your security rules in the Firestore "Rules playground". You can see below that you need to do isOneOfRoles(request.resource, ['pädagoge']);: with only resource, the rule engine cannot check the value of the field openWorld beacause the future state of the document is contained in the request.resource variable, not in the resource one. See the doc for more details.

    You also need to have a corresponding user in the users collection with a role field with the value pädagoge: in my example the user's UID is A1 (i.e. the ID of the Firestore doc in the users collection). See on the second and third screenshots below how we use this value in the Firebase UID field in the "Rules playground" simulator.

    enter image description here

    enter image description here (same screenshot as above, only the left pane was scrolled down to show the Firebase UID field)


    enter image description here