【发布时间】:2020-08-22 21:08:28
【问题描述】:
我希望在编写安全规则时获得一些帮助。这很简单,但是我为消息规则编写的每个变体似乎都被拒绝了。我想说的是“仅当您是消息的发送者或接收者时才授予读/写访问权限”。
我想在此安全性中涵盖的基本规则:
- 用户不能编辑任何其他人的数据
- 用户可以与其他人一起创建和阅读消息
- 未经身份验证的用户无法访问任何数据
错误信息:
[未处理的承诺拒绝: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);
【问题讨论】:
-
您能否也为引发该错误的 firebase 添加查询?
-
@SushanSapaliga 用查询更新了帖子
-
query是给发件人的吗?listener是给接收者的?我说的对吗? -
@SushanSapaliga 是的,你是对的。查询正在为发件人提取所有聊天记录。侦听器用于为接收者列出传入消息。
-
错误来自查询还是监听?规则看起来也不错。尝试调试日志记录值并简化查询。
标签: javascript react-native google-cloud-firestore firebase-security