Security Rules

Firestore security rules and data protection

Firestore Security Rules

Because Firebase allows clients to communicate directly with the database, we rely on firestore.rules to enforce access control. Without these rules, any user could modify product prices or read another user's personal data.

Deployment

Rules are deployed using the Firebase CLI:

firebase deploy --only firestore:rules

The Rules File

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
  
    // Helper Functions
    function isAuthenticated() {
      return request.auth != null;
    }
    
    function isAdmin() {
      return isAuthenticated() && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 'admin';
    }
    
    function isOwner(uid) {
      return isAuthenticated() && request.auth.uid == uid;
    }
 
    // Products Collection
    match /products/{productId} {
      allow read: if true; // Anyone can view products
      allow write: if isAdmin(); // Only admins can create/edit/delete
    }
 
    // Users Collection
    match /users/{uid} {
      allow read, write: if isOwner(uid) || isAdmin();
      
      // User Subcollections (Orders, Wishlist, Addresses)
      match /{subcollection=**} {
        allow read, write: if isOwner(uid) || isAdmin();
      }
    }
 
    // Global Orders Collection
    match /orders/{orderId} {
      // Users can only read/write their own orders
      allow create: if isAuthenticated() && request.resource.data.userId == request.auth.uid;
      allow read: if isOwner(resource.data.userId) || isAdmin();
      allow update, delete: if isAdmin();
    }
    
  }
}

Explanation

  1. Helper Functions: We abstract isAuthenticated(), isAdmin(), and isOwner() to make the rules readable.
  2. Role-Based Access: The isAdmin() function actually performs a get() request to read the user's document and check the role field.
  3. Data Isolation: Users can only access the users/{uid} path that matches their own request.auth.uid. They cannot snoop on others.

On this page