Ojasa Mirai

Ojasa Mirai

Cloud

Loading...

Learning Level

๐ŸŸข Beginner๐Ÿ”ต Advanced
๐Ÿ”ง Firebase Project Setup๐Ÿ”‘ Firebase Authentication๐Ÿ” Firestore Security Rules๐Ÿ” Firestore Advanced Queriesโšก Realtime Database๐Ÿ“ Firebase Storageโšก Firebase Functions Advanced๐Ÿงช Firebase Emulator๐Ÿ“Š Firebase Analyticsโšก Firebase Performance๐Ÿ“ฌ Firebase Cloud Messaging๐Ÿš€ Firebase Hosting Advanced
Cloud/Firebase Integration/Firestore Security Rules

๐Ÿ” Firestore Security Rules

Introduction

Firestore Security Rules are critical for protecting your database. They define who can access what data and under what conditions, enabling you to build secure applications without backend servers.

Key Learning Outcomes

By the end of this lesson, you'll understand:

  • Basic security rules structure and syntax
  • Authentication-based access control
  • Document-level and collection-level rules
  • Validation of incoming data
  • User-specific data access patterns
  • Role-based access control
  • Common security patterns

Basic Rule Structure

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Rules here
    match /collection/{document=**} {
      allow read, write: if condition;
    }
  }
}

Authentication-Based Access

Allow Only Authenticated Users

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /posts/{document=**} {
      allow read: if request.auth != null;
      allow write: if request.auth != null;
    }
  }
}

Allow Only Specific User

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read: if request.auth.uid == userId;
      allow write: if request.auth.uid == userId;
    }
  }
}

Document Validation

Validate Data Structure

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /posts/{postId} {
      allow create: if request.resource.data.title is string &&
                       request.resource.data.title.size() > 0 &&
                       request.resource.data.title.size() <= 100 &&
                       request.resource.data.author == request.auth.uid;
      
      allow update: if request.resource.data.author == resource.data.author;
      
      allow delete: if resource.data.author == request.auth.uid;
    }
  }
}

Role-Based Access Control

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    function userRole() {
      return get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role;
    }

    match /admin/{document=**} {
      allow read, write: if userRole() == 'admin';
    }

    match /posts/{postId} {
      allow read: if true;
      allow create: if request.auth != null;
      allow update: if resource.data.author == request.auth.uid || userRole() == 'moderator';
      allow delete: if resource.data.author == request.auth.uid || userRole() == 'admin';
    }
  }
}

User-Specific Collections

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId}/{document=**} {
      allow read, write: if request.auth.uid == userId;
    }

    match /users/{userId}/posts/{postId} {
      allow read: if true;
      allow write: if request.auth.uid == userId;
    }
  }
}

Public and Private Data

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /profiles/{userId} {
      allow read: if true;  // Public profile
      allow write: if request.auth.uid == userId;
    }

    match /settings/{userId} {
      allow read, write: if request.auth.uid == userId;  // Private settings
    }
  }
}

Batch Operations with Rules

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /comments/{commentId} {
      allow create: if request.auth != null &&
                       request.resource.data.author == request.auth.uid &&
                       request.resource.data.postId is string &&
                       request.resource.data.text is string;
      
      allow update: if resource.data.author == request.auth.uid;
      
      allow delete: if resource.data.author == request.auth.uid;
    }
  }
}

Testing Security Rules

Deploy and Test Locally

# Start Firestore emulator
firebase emulators:start --only firestore

# Deploy rules to production
firebase deploy --only firestore:rules

Test Rules in Console

// In Firestore console with emulator
// Test unauthenticated access
firebase.firestore().collection('posts').get();

// Test with authenticated user
// Sign in first, then try again

Common Security Patterns

Timestamp Validation

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /posts/{postId} {
      allow create: if request.resource.data.createdAt == request.time;
      allow update: if request.resource.data.updatedAt == request.time &&
                       resource.data.author == request.auth.uid;
    }
  }
}

Rate Limiting Pattern

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId}/rateLimits/{limit} {
      allow read: if request.auth.uid == userId;
      allow write: if request.auth.uid == userId;
    }

    match /comments/{commentId} {
      allow create: if request.auth != null &&
                       get(/databases/$(database)/documents/users/$(request.auth.uid)/rateLimits/comments).data.count < 10;
    }
  }
}

Key Takeaways

  • **Security Rules** are the foundation of database protection
  • **`request.auth`** provides access to authenticated user information
  • **Validation rules** prevent invalid data from being saved
  • **Role-based access** enables flexible permission management
  • **User-specific collections** protect private data
  • **Batch rules** apply consistently across operations
  • **Testing locally** prevents security issues in production
  • **Nested permissions** allow hierarchical data protection

Next Steps

Explore Firestore Advanced Queries for efficient data retrieval, or implement Firebase Storage rules for file access control.


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep โ€ข Build Real โ€ข Verify Skills โ€ข Launch Forward

Courses

PythonFastapiReactJSCloud

ยฉ 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn