You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase规则编写最佳实践咨询:用户专属节点权限隔离场景

Firebase Security Rules Best Practices for Your User-Building-Department Hierarchy

Great question! Let's walk through the optimal Firebase Security Rules setup for your scenario, focusing on tight access control, maintainability, and alignment with your permission hierarchy.

First, let's start with a clean data structure that aligns with your permission model. This makes writing secure, scalable rules much easier:

users/
  {userId}/  // Matches the authenticated user's UID
    profile: { 
      name: "John Doe",
      email: "john@example.com"
    }
    buildings/
      {buildingId}/  // Auto-generated or custom ID
        name: "Headquarters",
        address: "123 Main St"
        depts/
          {deptId}/
            name: "Product Development",
            floor: 3

Core Security Rules

Here's the rule set that enforces your exact permission requirements—users only have full read/write access to their own user node, all their buildings, and all departments under those buildings:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Default rule: Deny all access by default (critical security practice)
    match /{document=**} {
      allow read, write: if false;
    }

    // Grant full access to the user's own profile node
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;

      // Extend full access to all buildings under this user
      match /buildings/{buildingId} {
        allow read, write: if request.auth != null && request.auth.uid == userId;

        // Extend full access to all departments under this building
        match /depts/{deptId} {
          allow read, write: if request.auth != null && request.auth.uid == userId;
        }
      }
    }
  }
}

Key Explanations

  • Default Deny: Starting with a blanket denial ensures we only explicitly grant access where needed—this prevents accidental data exposure from unforeseen paths.
  • User ID Matching: By using request.auth.uid == userId, we tightly tie each resource to the authenticated user. No extra database queries are needed here, keeping rules fast and efficient.
  • Nested Rules: The nested structure mirrors your permission hierarchy (User → Building → Department), making the logic intuitive and easy to modify later.

Additional Best Practices

  • Validate Write Data (Optional): To ensure incoming data meets your schema (e.g., building names are strings, department floors are numbers), add validation clauses:

    match /buildings/{buildingId} {
      allow read, write: if request.auth != null && request.auth.uid == userId
        && request.resource.data.name is string
        && request.resource.data.address is string;
    }
    
  • Consider Flat Data (If Future Scaling Requires): If you ever need to query buildings across users (unlikely in your current scenario), you could flatten the structure and use a userId field to associate resources. The rule would look like this:

    match /buildings/{buildingId} {
      allow read, write: if request.auth != null 
        && (request.resource.data.userId == request.auth.uid 
            || resource.data.userId == request.auth.uid);
    }
    

    This still enforces that users only access their own buildings, but keeps the data structure flexible for cross-user operations.

  • Test Rules Thoroughly: Use Firebase's built-in Rules Playground to simulate read/write operations from different user contexts. This helps catch edge cases before deploying to production.

This setup will perfectly enforce your requirements: users can create as many buildings and departments as needed, and only have access to their own resources. It's secure, maintainable, and ready to grow with your application.

内容的提问来源于stack exchange,提问作者Joao Alves Marrucho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:48:39