Firestore security rule to check if character username already exists

坚强是说给别人听的谎言 提交于 2019-12-11 08:57:14

问题


I have following character collection structure in my database (firestore)

/characters/{uid}
 - username: string
 - clan: string
 - mana: number
 - health: number
 etc...

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();
    }
  }
}

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

Make sure that request.resource.data.username is unique i.e. not present inside any other document of /characters collection.


回答1:


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.

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.



来源:https://stackoverflow.com/questions/52016426/firestore-security-rule-to-check-if-character-username-already-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!