A Webster
A Webster

Reputation: 55

Firestore rules to access collection that matches Auth uid

I am attempting to set up my security rules so that users can have full access to one specific document(named after their UID) and all subdocuments within this 'parent' document.

I have created the below rule to do so, however I am getting the error 'The caller does not have permission' when I attempt to read/write to the subdocuments or the parent.

I though the wildcard syntax would have me covered here. There's clearly a gap in my understanding.

service cloud.firestore {
  match /databases/{database}/documents {
    match /User/{document=**} {
      allow read, write: if request.auth.uid == document
    }
  }
}

DB layout

User

Code that interfaces with backend

db.collection("User")
   .doc(uid1) //this is set as a prop via auth UID of user, parent
   .collection(randomDocumentName) // this is the child document
   .add({
         name:'test'
       })

Upvotes: 1

Views: 1695

Answers (2)

A Webster
A Webster

Reputation: 55

Solved this problem after using the rules playground.

First I didn't have permission to look at the parent document at all, then I gave specific document permission to each user to access the specific child document. If I add a new child document I will need to add a rule.

service cloud.firestore {
  match /databases/{database}/documents {
    match /UserData/{ID}{
    allow read, write :if request.auth  != null && request.auth.uid == ID;
    // allow users to create and access their parent document
    }
  
    match /UserData/{userId}/randomDocumentName/{doc=**} {
      allow read, write :if request.auth != null && request.auth.uid == userId; // allow read and write to the documents they own
    }
  }
}

Upvotes: 1

Kundan
Kundan

Reputation: 1952

This might work

service cloud.firestore {
  match /databases/{database}/documents {
    match /User/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

Upvotes: 1

Related Questions