代码之家  ›  专栏  ›  技术社区  ›  Paul

云Firestore安全规则文档示例

  •  0
  • Paul  · 技术社区  · 7 年前

    本文档页: Writing conditions for Cloud Firestore Security Rules ,说:

    另一种常见模式是确保用户只能读写自己的数据

    并提供了以下示例:

    service cloud.firestore {
      match /databases/{database}/documents {
        // Make sure the uid of the requesting user matches name of the user
        // document. The wildcard expression {userId} makes the userId variable
        // available in rules.
        match /users/{userId} {
          allow read, update, delete: if request.auth.uid == userId;
          allow create: if request.auth.uid != null;
        }
      }
    }
    

    我不明白为什么 create 规则的定义条件与其他规则不同, if request.auth.uid == userId ,但定义为 if request.auth.uid != null .据我所知,根据这条规则,任何用户都可以在其中创建任何文档 users ,但除非它与他的uid匹配,否则无法对其执行任何操作。那为什么要允许呢?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Angus    7 年前

    让我们来谈谈 基本的 可以实现的安全规则(通过用户身份验证):

    allow read, update, delete: if request.auth.uid != null;
    allow create: if request.auth.uid != null;
    

    任何用户都可以删除其他人创建的文档。因此,为了限制/控制它,我们实现了所提供的代码片段。

    service cloud.firestore {
      match /databases/{database}/documents {
        // Make sure the uid of the requesting user matches name of the user
        // document. The wildcard expression {userId} makes the userId variable
        // available in rules.
        match /users/{userId} {
          allow read, update, delete: if request.auth.uid == userId;
          allow create: if request.auth.uid != null;
        }
      }
    }
    

    代码片段只是一个示例用例,它使用不同的条件作为参考,因为这是一个教程/指南,所以Firebase团队尝试为代码片段提供尽可能多的条件。

    你当然可以 allow create: if request.auth.uid == userId; 严格限制该特定用户。

    我希望它能给你一些想法!