我希望得到一些编写安全规则的帮助。这很简单,但是我为消息规则编写的每个变体似乎都被拒绝了。我想说的是“仅当您是邮件的发送者或接收者时才授予读/写访问权限。”
此安全性要涵盖的基本规则:
错误消息:
[未处理的承诺被拒绝:FirebaseError:缺少权限或权限不足。]
到目前为止我所拥有的:
service cloud.firestore {
match /databases/{database}/documents {
function isLoggedIn() {
return request.auth != null && request.auth.uid != null;
}
function isSender() {
return resource != null && resource.data.user._id == request.auth.uid;
}
function isReceiver() {
return resource != null && request.auth.uid in resource.data.receiver
}
match /Users/{userId} {
//Only authenticated users can access/write data
allow delete: if request.auth.uid == userId;
allow read, write: if request.auth != null && request.auth.uid == userId;
}
match /messages/{messageId} {
// allow read, write: if isLoggedIn() && (isSender() || isReceiver());
allow read, write: if isLoggedIn() && (resource.data.user._id == request.auth.uid || request.auth.uid in resource.data.receiver);
}
}
}
消息数据结构如下:
id: ""
createdAt:""
index: 1
key: ""
receiver:
[0: receiverIDgoeshere]
message: ""
user:
{_id: ""}
查询:
let query = config.db
.collection(messages)
.where("key", "==", uid)
.orderBy("index", "desc");
if (typeof index === "number") {
query = query.where("index", ">", index);
}
const chats = await query.get();
还有一个传入消息的侦听器:
const listener = config.db
.collection(messages)
.where("key", "==", uid)
.where("receiver", "array-contains", userId)
.onSnapshot((snapshot) => {
const msgs = snapshot.docChanges().map(({doc, type}) => {
if (type === "added") {
return fixData({
id: doc.id,
match,
fromRealTime: true,
...doc.data(),
});
} else {
console.log("type is NOT added...");
}
return null;
});
setMessages(msgs.filter((msg) => msg !== null));
});
以及当我们添加聊天时:
const fs = config.db;
const doc = fs.collection(messages).doc();
await doc.set(chat);
答案 0 :(得分:1)
查询必须更新如下:
let query = config.db
.collection(messages)
.where("key", "==", uid)
.where("user._id", "==", uid)
.orderBy("index", "desc");
//rest is same
我认为侦听器的查询没有任何问题。
答案 1 :(得分:0)
我发现我的安全规则很好,我试图对其进行细化。以上所有安全规则均已涵盖。