Daniel T.
Daniel T.

Reputation: 489

How to read collection only if UID matches collection name in Firebase Firestore?

I created a Collection of user IDs for each user and I want to set the database rules to read the collection item only if the user ID matches the collection item name. I tried something like:

 service cloud.firestore {
    match /databases/{database}/documents {
      match /{document=**} {
        allow read: if request.auth != null;
      }
      match /{userId} {
        allow read: if belongsTo(userId);
      }
      function belongsTo(userId) {
        return request.auth.uid == userId
      }
    }
    }

Upvotes: 0

Views: 515

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

Firestore reads documents. There is no concept of reading a collection. So your rules must provide access to documents.

To grant access to all documents in the collection named after the user's UID:

  match /{userId}/{document} {
    allow read: if belongsTo(userId);
  }

Upvotes: 2

Related Questions