设置安全规则有困难
数据结构-- books (collection)
-- bookId (autogenerated Id - doc)
-- {chapter: text}, {chapter: text},
userBooks
-- email (email of user logged in - doc)
-- books (sub collection)
-- bookId (referencing bookId doc on collection book)
-- role: admin or read
用例如下,具有admin角色的用户是唯一被允许共享图书的用户,允许他在其他用户的图书中添加条目。
创建了一个函数,试图达到这个目的,但它没有成功通过
我是登录用户与电子邮件userWantsToShare@gmail.com。当用户试图将他的书分享给addUser@gmail.com时我提出以下请求:
userWantsToShare@gmail.com请求在addUser@gmail.com集合下写。
final role = {'role': 'edit'};
await FirebaseFirestore.instance
.collection('userBooks')
.doc("addUser@gmail.com")
.collection('books')
.doc('9KHYZJVBY3BNAlYPYYoA')
.set(role);
当来到firebase
这应该转换为/userBooks/addUser@gmail.com/books/9KHYZJVBY3BNAlYPYYoA数据{'role': 'edit'}.
match /userBooks/{emailId}/books/{bookId} {
allow write: if isSharedEmail(bookId);
}
//here im verifying the user that wants to share has admin role and therefore is authorised to write in another user book subcollection
function isSharedEmail(bookId){
//this should translate to /userBooks/userWantToShare@gmail.com/books/9KHYZJVBY3BNAlYPYYoA
get(/databases/$(database)/documents/userBooks/$(request.auth.token.email)/books/$(bookId)).data.role == "admin" ;
}
由于userWantToShare@gmail.com在该路径admin角色下,它应该允许插入。但很可能我遗漏了一些东西,因为它根本不起作用。
我错过了什么?
Thanks in advance
好的,对于那些和我犯同样愚蠢错误的人。当调用函数时,isSharedEmail在上下文之外。
意味着通过将函数移动到上下文中的作用域就足以使其工作
Before: not working
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /userBooks/{email} {
allow write: if ( isAppShared())
allow read: if true;
}
}
}
function isAppShared() {
return get(/databases/$(database)/documents/userBooks/$(request.auth.token.email)).data.bookId == request.resource.data.bookId;
}
工作后:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /userBooks/{email} {
allow write: if ( isAppShared())
allow read: if true;
}
function isAppShared() {
return get(/databases/$(database)/documents/userBooks/$(request.auth.token.email)).data.bookId == request.resource.data.bookId;
}
}
}