Firebase Security Rules - blog posts
2022-04-12
Collection of Firebase Security Rules example snippets for my future use
Hypothetical blog app
posts/post_1
- title: "first post"
- content: "📮"
- owner: "user_1"
users/user_1
- id: "user_1"
- email: "[email protected]"What I want
- All posts can be
readby anyone - A post can be
createdby any authenticated user - A post can only be
updated/deletedby the authenticated user who created the post
Security Rules for above
allow read;// anyoneallow create: request.auth != null;// authenticated userallow update, delete: request.auth != null && request.auth.uid == resource.data.owner;// authenticated user who created the post (owner in this case)
Distinction between request and resource
requestis an incoming request (data) from path matchedresourceis the existing data in Firestore that will be evaluated against the set Security Rules
Put them into functions
function isAuthenticated() {
return request.auth != null
}function isPostOwner() {
return request.auth.uid == resource.data.owner
}Security Rules for blog app
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Match any document in the 'posts' collection
match /posts/{postId} {
allow read;
allow create: if isAuthenticated();
allow update, delete: if isAuthenticated() && isPostOwner();
}
// Match any document in the 'users' collection
match /users/{userId} {
allow read;
allow write: if isAuthenticated() && isSameUser(userId);
}
function isAuthenticated() {
return request.auth != null;
}
// request.resource.data: incoming data
// resource.data: existing data
function isPostOwner() {
return request.auth.uid == resource.data.owner;
}
function isSameUser(userId) {
return request.auth.uid == userId;
}
}
}