Firestore 安全规则,用于检查字符用户名是否已存在 [英] Firestore security rule to check if character username already exists
问题描述
我的数据库(firestore)中有以下字符集合结构
I have following character collection structure in my database (firestore)
/characters/{uid}
- username: string
- clan: string
- mana: number
- health: number
etc...
我正在尝试使用以下逻辑为 /characters/{uid}
找出安全规则
I am trying to figure out a security rule for /characters/{uid}
with following logic
service cloud.firestore {
match /databases/{database}/documents {
// Characters
match /characters/{characterID} {
allow create: if isValidUsername();
}
}
}
这里的函数 isValidUsername
检查各种内容,如长度、特殊字符等......但我无法弄清楚的一件事是如何检查函数内部的内容
here function isValidUsername
checks for various things like length, special characters etc... but one thing I can't figure out is how to check following inside of the function
确保 request.resource.data.username
是唯一的,即不存在于 /characters
集合的任何其他文档中.
Make sure that request.resource.data.username
is unique i.e. not present inside any other document of /characters
collection.
推荐答案
TL;DR:只有通过创建额外的集合才能强制执行唯一性.
TL;DR: Enforcing uniqueness is only possible by creating an extra collection.
在您当前的结构中,要了解用户名是否唯一,您需要阅读每个文档.这是非常低效的,而且在安全规则中是不可能的,因为它们每个规则只能读取几个文档.
In your current structure, to know if a username is unique, you will need to read each document. This is incredibly inefficient, and on top of that it isn't possible in security rules, since they can only read a few documents per rule.
诀窍是创建一个额外的集合usernames
,其中每个用户都有一个文档,但现在每个文档的键/ID 是用户名.有了这样的集合,就可以检查某个文档是否存在,这是安全规则中的一个原始操作.
The trick is to create an extra collection usernames
, where you also have a document for each user, but now the key/ID of each document is the username. With such a collection, you can check for the existence of a certain document, which is a primitive operation in the security rules.
另见:
这篇关于Firestore 安全规则,用于检查字符用户名是否已存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!