I have a firebase firestore document where I store the admin ids in an admins array. How can I create security rules that allows reads and writes if a request userid is in that admins list.
I wonder about 3 cases:
If I have this rule how do I also allow an admin to write and read:
match /users/{uid}{
allow read,write: if request.auth != null;
}
Can I make a function for example isAdmin() inside the securityrules which I can use in every rule to accept admin?
Is it possible to make one (or two) rules that allows the admins to read and write everything in the database, instead of writing a rule for every collection?
I believe the answer is yes to all three questions:
||
operatorI very much so recommend these two videos:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function isAdmin() {
let admins = get(/databases/$(database)/documents/roles/admins);
return request.auth.uid in admins.data.users;
}
function isOwner() {
return request.auth != null && request.auth.uid == userId;
}
match /{document=**} {
allow read, write: if isAdmin();
}
match /users/{userId} {
allow read, write: if isAdmin() || isOwner();
allow create: if request.auth != null;
}
}
}
This rendered success for me in my test db
If you haven't used the rules playground yet, it's a good place to get started: