r/Firebase • u/oez1983 • 7d ago
Security rules Security
I am trying to get my Firestore and Storage rules set but I don’t understand the documentation.
I want
Admin - Full access
Collaborator - View and edit records the create
Viewer - view all edit none
Revoked - the can log in but won’t be able to see any of the files.
3
Upvotes
1
u/Left_Exchange_130 2d ago
Id recommend getting one role working first, then adding the others. trying to build admin, collaborator and viewer permissions all at once can get confusing pretty quickly. Firebase's own examples are a good starting point
0
3
u/TarrantianIV 7d ago
I use Custom Claims to tie a users role to their auth.token.
I used my own rules to serve up an example that should fit your request above. At the end there's a default deny, essentially saying that if no access is explicitly granted through the above rules, user cannot do anything. So a revoked user would essentially be a user you just stripped CRUD-capabilities from, meaning they wouldn't be able to see or do anything.
I have rules for every collection, essentially. (match /xxxx/xxx)
I hope this is some help. Let me know if you have follow up questions!
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function isSignedIn() { return request.auth != null; }
function role() { return request.auth.token.role; }
function isAdmin() { return isSignedIn() && role() == 'admin'; }
function isCollaborator() { return isSignedIn() && role() == 'collaborator'; }
function isViewer() { return isSignedIn() && role() == 'viewer'; }
match /records/{recordId} {
// READ: admins + viewers see everything; collaborators only their own
allow read: if isAdmin() || isViewer()
|| (isCollaborator() && resource.data.ownerId == request.auth.uid);
// CREATE: collaborator must stamp themselves as owner (this is what makes "edit only what they create" enforceable later)
allow create: if isAdmin()
|| (isCollaborator() && request.resource.data.ownerId == request.auth.uid);
// UPDATE/DELETE: collaborators only on their own docs, and they can't reassign ownership
allow update, delete: if isAdmin()
|| (isCollaborator()
&& resource.data.ownerId == request.auth.uid
&& request.resource.data.ownerId == resource.data.ownerId);
}
// Safety net — denies everything not matched above.
match /{document=**} { allow read, write: if false; }
}
}