Reputation: 195
How could I set rules for Firestore to restrict access only for some users to certain collections documents/collection in the following manner:
//base collection
clients:{
//document
client-1-store:{
users-allowed:[
"user-1-id",
"user-2-id",
"user-3-id",
"user-4-id",
]
}
}
The thing is I'd like to only allow reading and writing to the "client-1-store" document and its documents and sub collections if the current logged in user's id is set inside the users-allowed array of each "store", but I have no idea of how i could do that...
Upvotes: 1
Views: 911
Reputation: 4908
Instead of creating an array of user IDs, create a map of values
//base collection
clients:{
//document
client-1-store:{
users-allowed:{
"user-1-id": true,
"user-2-id": true,
"user-3-id": true,
"user-4-id": true,
}
}
}
match /clients/{storeId=**} {
allow read: if get(/databases/$(database)/documents/clients/$(storeId).data.users-allowed.$(request.auth.uid)) == true;
}
However, this doesn't scale as well as having an allowedUsers sub-collection, with each user ID saved as a document. You can then use the exists
condition, instead. This also allows you to add further granularity to the user's document for detailed CRUD permissions.
Upvotes: 4