创建变量以在 Firestore 规则中重用

问题描述 投票:0回答:1

在复杂的产品中,您经常必须使用相同的规则条件,例如,如果用户是管理员:

match /games/{game} {
  allow read: if true;
  allow write: if request.auth != null && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true
}
match /locations/{location} {
  allow read: if true;
  allow write: if request.auth != null && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true
}

有没有办法将条件存储在变量中以重用它(而不是每次都写入)?例如:

const isAdmin = request.auth != null && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true;    

match /games/{game} {
  allow read: if true;
  allow write: if isAdmin
}
match /locations/{location} {
  allow read: if true;
  allow write: if isAdmin
}

我不知道 Firestore 规则背后的语言是什么以及我能够使用什么样的资产。

firebase google-cloud-platform google-cloud-firestore firebase-security
1个回答
3
投票

是的,您可以使用自定义函数,如doc中所述。

在你的情况下,它将是以下内容(未经测试):

function isAdmin() {
  return request.auth != null && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true;    
}
match /games/{game} {
  allow read: if true;
  allow write: if isAdmin();
}
match /locations/{location} {
  allow read: if true;
  allow write: if isAdmin();
}

请注意,安全规则“层次结构”中功能的位置很重要。请观看这个官方视频了解更多详情。

© www.soinside.com 2019 - 2024. All rights reserved.