Home > front end >  How to restrict access to subdocument based on parent collection in firebase
How to restrict access to subdocument based on parent collection in firebase

Time:02-11

I have a firestore db with 2 top-level collections (Reports, Users). My rules are set up like this:

service cloud.firestore {
  match /databases/{database}/documents {
    match /reports/{report} {
        allow read: if request.auth != null && request.auth.uid == resource.data.userID;
      allow create: if request.auth != null && request.resource.data.userID == request.auth.uid;
      allow delete, update: if request.auth != null &&
      request.auth.uid == resource.data.userID;
    }
    match /users/{user}{
        allow read: if request.auth != null && request.auth.uid == resource.id; 
      allow create: if request.auth != null;
      allow delete: if request.auth != null && request.auth.uid == resource.id;
      allow update: if request.auth != null && request.auth.uid == resource.id;
    }
  }
}

I want to create a sub-collection under the users collection. This would contain that user's default settings. In my head the rules would look like this:

match /users/{user}/defaultSettings/{document} {
   allow read, write: if request.auth != null && user.id == request.auth.uid
}

However, I don't think I can use 2 placeholders (users and document) in my rules. Firestore is complaining about my use of user.id

In other words, I want to have a users collection that anyone who is authenticated to can read and write to because upon signing up I create a User document with that user's info. I also want to create a sub-collection under each user with only one document that holds that user's settings and I want to restrict access to that document to only the user that is represented by the parent (User) document.

How can I do this?

CodePudding user response:

Just change your rule to:

match /users/{user}/defaultSettings/{document} {
   allow read, write: if request.auth != null && user == request.auth.uid
}

And to make your rule on the user collection a bit simpler your can use:

match /users/{user}{
    allow read: if request.auth != null && request.auth.uid == user; 
  allow create: if request.auth != null;
  allow delete: if request.auth != null && request.auth.uid == user;
  allow update: if request.auth != null && request.auth.uid == user;
}
  • Related