在复杂的产品中,您经常必须使用相同的规则条件,例如,如果用户是管理员:
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 规则背后的语言是什么以及我能够使用什么样的资产。
是的,您可以使用自定义函数,如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();
}
请注意,安全规则“层次结构”中功能的位置很重要。请观看这个官方视频了解更多详情。