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屋!