aryaxt
aryaxt

Reputation: 77596

Firestore role based rule

I have the following rules which should allow me to read a document, but I get insufficient permission error. Any advice?

The current user has a document under a collection named users with a field named role that has the value admin

service cloud.firestore {
  match /databases/{database}/documents {
  
    match /users/{userId}/tickets/{ticketId} {
        allow update, delete, create: if false
        allow read: if get(/users/$(request.auth.uid)).data.role == "admin"
    }
  
    match /users/{userId} {
        allow delete: 
        if false
      
        allow read, write: 
        if request.auth != null && request.auth.uid == userId
      
      allow update: 
        if resource.data.points == request.resource.data.points && request.auth != null && request.auth.uid == userId
    }

iOS code fetching data

    func fetchTickets(contestId: String) -> SignalProducer<[Ticket], FetchError> {
        Firestore.firestore()
            .collection("users/*/tickets")
            .whereField("contest.id", isEqualTo: contestId)
            .getDocuments()
    }

users collection

{
    "role": "admin"
}

users.{userId}.tickets collection

{
    "contest": {
         "id": ""asdasd
    }
}

Upvotes: 0

Views: 34

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317342

First of all, wildcards are not supported in Firestore queries. You will need to either identify a single user's tickets and query only that one subcollection. Or, you will need to perform a collection group query on tickets to query all subcollections named tickets. If you use a collection group query, you will need completely different rules to support that.

Second of all, security rules are not filters. Be sure to read that documentation carefully. You can't have a rule filter out some documents based on the get() of another document. This simply does not scale the way that Firestore requires. The client must be able to formulate the filter in the query, and that requires that the data to filter with must be in the documents in the collection being queried (they can't be in other documents).

Upvotes: 2

Related Questions