0
votes

My Firestore database creates a new Collection whenever a new user Signs Up to my app. The name of the Collection is the username of the new user. I wanted to make the documents inside this collection to have restricted write access.

service cloud.firestore {
  match /databases/{database}/documents {

    match /User1/{info} {
      allow read: if signedIn();
      allow write: if isOwner(User1);
    }

    function signedIn() {
        return request.auth != null;
    }

    function isOwner(userId) {
      return request.auth.uid == userId;
    }    
  }
} 

This works if the current user is User1 but is not applicable to any new user that signs up. How do I add this Firestore Security Rule to every new user?

1
It's probably not a good idea to have a collection per user. Consider instead using a document per user using their uid, then subcollections under that as needed.Doug Stevenson
The only problem is that I am using Flutter for my app and I can't figure out how to access a subcollection in Flutter.Laksh22
You should be able to reach into a subcollection using some method on DocumentReference, probably called collection().Doug Stevenson

1 Answers

4
votes

I notice that the first rule matches to /User1/{info}, meaning it will match any path in the collection User1. Instead, if you use brackets, this value becomes a wildcard, meaning the match will work for any value. Check out the examples in the guide for more information.

service cloud.firestore {
  match /databases/{database}/documents {

    match /{username}/{info} {
      allow read: if signedIn();
      allow write: if isOwner(username);
    }

    function signedIn() {
        return request.auth != null;
    }

    function isOwner(userId) {
      return request.auth.uid == userId;
    }    
  }
}