NT93
NT93

Reputation: 316

Firebase Firestore access rules - Comparing resource data

My model stored in the database is like so:

{
    "ownerUid": <my auth UID>,
    "teamName: "Team 1",
    "teamDescription: "Team 1 desc"
}

And my initial access rule is like so:

service cloud.firestore {
    match /databases/{database}/documents {    
        match /teams/{teamId} {
            allow read: if resource.data.ownerUid == request.auth.uid;
            allow write: if true; //ignore this
        }
    }
}

The query I run to get the teams is as follows:

Query query = FirebaseFirestore.getInstance()
              .collection("teams")
              .orderBy("teamName")

Running this query will always result in "PERMISSION DENIED", and I'm quite unsure what the cause of this is.

I've tried the following rules as well, for testing purposes:

allow read: if true; //Works
allow read: if request.auth.uid != null; //Works
allow read: if request.auth.uid == <my auth uid>; //Works
allow read: if resource.data.ownerUid != null; //Fails

On the rules that succeeded, I can see the ownerUid in the returned teams, and see that it is not null, and it matches with .

Upvotes: 1

Views: 617

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600131

In your current code you're trying to read from the collection teams. Since you don't have access to that full collection, the read is rejected.

If you want to allow the user to query documents that they created, you'll need to do two things:

  1. Use a query that retrieves only documents they created.
  2. Write your security rules so that they allow this query.

You have done #2, but are not doing #1. To make things work, use a query like this:

String uid = FirbaseAuth.getInstance().getCurrentUser().getUid();
Query query = FirebaseFirestore.getInstance()
          .collection("teams")
          .whereEqualTo("ownerUid", uid)
          .orderBy("teamName")

Also see the documentation section on Secure and query documents based on auth.uid.

Upvotes: 1

Related Questions