Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Security Rules for Firestore to allow access to all subcollections based on UID

So trying to setup my firestore database and I have a collection called Users that stores the users information. I also have subcollections of Towers for each user. My users documents have a playerUid field that I use for security settings. Here are my current security rules:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read: if request.auth.uid != null;
    }
    match /users/{user=**}{
        allow read, create: if request.auth.uid != null;
      allow update: if request.auth.uid == resource.data.playerUid;
    }
  }
}

this allows users to read, create both their user document and the subcollection of tower documents, but they cant edit the subcollection. There is no playerUid in the tower documents. Is there a way to use the playerUid in the user document to authenticate for updating the towers? Or do I need to add a playerUid field to the tower documents to authenticate against

like image 218
DRing Avatar asked Mar 22 '18 03:03

DRing


2 Answers

You can get the user document in the rules of the Towers subcollection as shown in the Firestore documentation on accessing other documents:

allow delete: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true

Alternatively you can indeed include the UID if the user in the documents of the subcollection. That will prevent needing an extra document read in the rules.

like image 115
Frank van Puffelen Avatar answered Oct 16 '22 18:10

Frank van Puffelen


This snippet may be able to help you

    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read: if request.auth.uid != null;
        }
        match /users/{user=**}{
            allow read, create: if request.auth.uid != null;
          allow update: if request.auth.uid == user; // <== THIS LINE
        }
      }
    }

Wouldn't this match the 'user' path with the 'uid'? I will try test this when I have some time. It would save a get call if it does work.

like image 27
Matthew Berends Avatar answered Oct 16 '22 18:10

Matthew Berends