Aaron Russell
Aaron Russell

Reputation: 75

Access database reference in firestore rules

I am struggling to access document references in the firestore rules. My database looks like this. (Simplified for brevity):

curriculum 
   session1

roles
   admin
       --- canEditContent
   user
       --- canEditContent

users
   userid
      --- role
          roles/admin <document reference>

I want to access the admin permissions based on the document reference.

I have tried several ways however can't seem to get anywhere. This is my code so far

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    function isSignedIn() {
      return request.auth != null;
    }
    function getUser() {
      return get(/databases/$(database)/documents/users/$(request.auth.uid));
    }
    function getUserRole() {
      let role = get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role;
      return get(role);
    }
    match /curriculum/{curriculum} {
      allow write: if isSignedIn() && getUserRole().data.canEditContent;
    }
    match /users/{userId} {
      allow read, update, delete, write: if request.auth != null && request.auth.uid == userId;
      allow create: if request.auth != null;
    }
  }
}

I have tried many ways and can't seem to solve it.

Thanks in advance

EDIT

Added screenshots below of collections

Users collection showing role as a document ref to a role document in the roles collection. Users collection

Roles collection Roles collection

Upvotes: 0

Views: 186

Answers (1)

l1b3rty
l1b3rty

Reputation: 3660

I can see two issues in your rules:

  1. get needs the full document path, so your function getUserRole wont work. Try this instead:

    function getUserRole() {
      let role = getUser().data.role;
      return get(path("/databases/" + database + "/documents/" + role));
    }
    
  2. Your rule uses the role canEditContent but the data you show uses editContent, is that on purpose?

As already mentioned please provide the complete set of data & query & rules, here we cant see the query you are using. Also note that you can use the Firestore emulator to get information on what rule is failing and where.

Upvotes: 1

Related Questions