实时数据库-如何更改安全规则以检查用户名是否存在

克林特

我正在尝试检查数据库中是否已经存在用户名。

这是我为此编写的代码。


 func textFieldDidEndEditing(_ textField: UITextField) {

        //check if username is already taken in the database
        let username = self.usernameTextField.text!
        let reference = Database.database().reference().child("activeUsernames")
        let query = reference.queryOrdered(byChild: "username").queryEqual(toValue: username)

        let banner = StatusBarNotificationBanner(title: " The username \(username) is not available.", style: .danger)

        let successBanner =  StatusBarNotificationBanner(title: "The username \(username) is available.", style: .success)

        query.observe(.value, with: { (DataSnapshot) in

            if DataSnapshot.exists() {

                print("Darn username already exists")
                banner.show()

            } else {
               print("Yes I can use this username")
                successBanner.show()



            }

        }, withCancel: nil)
    }

到目前为止,它的工作方式不一致。有时,如果我输入一个已经存在的用户名,则打印语句"Yes I can use this username"在明显已经被使用时会出现,有时它让我知道它已经被使用。我注意到我在控制台中得到了这个声明

使用未指定的索引。您的数据将在客户端上下载并过滤。考虑将/ activeUsernames处的“ .indexOn”:“用户名”添加到安全规则中,以获得更好的性能

我不确定这是否导致检查不一致。但是,我不确定如何有效地更改或编辑安全规则。

如果有帮助,这是我的活动用户名的数据结构,仅显示用户uid和与该uid关联的用户名。

- activeUsernames
 6GpUz3iLwmWdDrlMtf7tT0yAULw2
 username: 
 8sRfoqa4dKYzUKGdIZAtwE6NQZH2
 username: 
 SRY4xUmRMgXbLL7GfsxosF6sS1y2
 username: 

这也是安全规则

 "rules": {
    ".read": true,
    ".write": true
  }
}
弗兰克·范普菲伦

要摆脱此信息,请将您的规则更改为:不要忘记将它们分开 ,

{
  "rules": {
    ".read": true,
    ".write": true,
    "activeUsernames": {
      ".indexOn": "username"
    }
  } 
}

这告诉Firebase服务器username在下的上添加索引/activeUsernames,这使它可以在服务器而不是客户端上执行排序/过滤。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章