【问题标题】:Firebase Security Rules - using get in a functionFirebase 安全规则 - 在函数中使用 get
【发布时间】:2018-12-16 12:31:52
【问题描述】:

我正在尝试为我的 firestore 实例设置安全规则,我有三个基本要求:

  1. 用户必须经过身份验证才能读取
  2. 文档的所有者是唯一的 可以写信给他们的人(在文档上使用一个名为 owner 的字段 验证)
  3. 任何管理员用户也可以写入任何文档

下面的代码实现了所有这些(不包括所有权检查),但确定用户角色的 get 函数仅在与 if 条件在同一行中指定时才有效。在下面的代码中,更新和删除适用于管理员,但不适用于创建。

谁能告诉我为什么 isAdmin() 函数的计算结果不一样?

service cloud.firestore {
  match /databases/{database}/documents {

    // Only 'owners' of data can make changes to data
    match /posts/{post} {    
      allow read: if isAuthenticated();
      allow create: if isAuthenticated() && isAdmin();
      allow update, delete: if isAuthenticated() && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 1;      
    }
  } 

  /// FUNCTIONS ///
  function isAuthenticated() {
     return request.auth.uid != null;
  }

  // function requestIsOwner() {
  //   return request.resource.data.owner == request.auth.uid;
  // }

  // function resourceIsOwner() {
  //   return resource.data.owner == request.auth.uid;
  // }

  function isAdmin() {
    return get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 1
  }
}

【问题讨论】:

  • 您是说它在控制台模拟器中不起作用,还是在实际部署这些规则时?已知控制台模拟器在某些情况下是不正确的。
  • 对我来说,我们在部署过程中看到了与控制台的这种类型的差异,当您试图弄清楚什么有效时,这无济于事

标签: firebase google-cloud-firestore firebase-security


【解决方案1】:

您需要将 database 变量作为参数传递给您的函数,如下所示:

service cloud.firestore {
  match /databases/{database}/documents {

    // Only 'owners' of data can make changes to data
    match /posts/{post} {    
      allow read: if isAuthenticated();
      allow create: if isAuthenticated() && isAdmin(database);
      allow update, delete: if isAuthenticated() && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 1;      
    }
  } 

  /// FUNCTIONS ///
  function isAuthenticated() {
     return request.auth.uid != null;
  }

  // function requestIsOwner() {
  //   return request.resource.data.owner == request.auth.uid;
  // }

  // function resourceIsOwner() {
  //   return resource.data.owner == request.auth.uid;
  // }

  function isAdmin(database) {
    return get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 1
  }
}

【讨论】:

  • 啊,我看到函数实际上超出了匹配块的范围,所以它无法解析 $database 变量
猜你喜欢
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 2021-03-29
  • 2020-06-12
  • 2016-06-27
  • 1970-01-01
  • 2020-08-22
相关资源
最近更新 更多