Google Cloud Firestore 安全规则允许您控制对数据库中文档和集合的访问。这些规则允许您创建匹配任何内容的规则,从对整个数据库的所有写入到对特定文档的操作。这还取决于您在 Cloud Firestore 中构建数据的方式。
问题:正如您的问题中所述,我假设您需要实施 Firestore 安全规则,以便匿名用户只能回答一次任何问题。
因此,考虑到您的要求,为每个问题收集问题和子收集答案将是您数据库的理想方法。还有另一个集合,用于存储每个用户的浏览器指纹,可用于显示基于用户的统计信息。数据库的架构如下所示。
问题集
Questions
-question1
-Answers (subcollection)
-answer1
-answer
-userId //unique id for each anonymous user
-answer2
-answer
-userId
-question2
-Answers (subcollection)
-answer1
-answer2
用户集合
Users
-user1
-userId //Unique browser fingerprint or any uniqueId to distinguish anonymou users
-answeredQuestions // Array of questionIds of answered questions
解决方案:现在我们知道给定问题的现有答案,如果用户拥有唯一的答案,我们可以为答案子集合编写限制创建新答案的安全规则在用户集合中他/她的用户文档的已回答问题数组中已经存在 questionId。
service cloud.firestore {
match /databases/{database}/documents {
match /Questions/{questionId}/Answers/{answerId} {
//Only restricting new answers
allow create: if (! questionId in getUserData(request.resource.data.userId).answeredQuestions;
}
//Function to get the user information
function getUserData(userId){
return get(/databases/$(database)/documents/Users/$(userId)).data;
}
}
}
注意:请确保您不要将匿名用户限制在他尚未回答的其他问题上。
希望这些指点有所帮助。