I was hoping to get some help writing a security rule. It is pretty straight forward but every variation I write for the message rule seems to get rejected. I am looking to say "give read/write access only if you are the sender or receiver of the message".
the basic rules I want to cover with this security:
error message:
[Unhandled promise rejection: FirebaseError: Missing or insufficient permissions.]
What I have so far:
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);
}
}
}
the message data structure is like so:
id: ""
createdAt:""
index: 1
key: ""
receiver:
[0: receiverIDgoeshere]
message: ""
user:
{_id: ""}
query:
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();
there is also a listener for incoming messages:
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));
});
and when we add a chat:
const fs = config.db;
const doc = fs.collection(messages).doc();
await doc.set(chat);
The query must be updated as follows:
let query = config.db
.collection(messages)
.where("key", "==", uid)
.where("user._id", "==", uid)
.orderBy("index", "desc");
//rest is same
I don't see any problem with the listener's query.
I found that my security rules are fine, I was trying to get too granular with it. All is covered with the above security rules.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.