Firebase实时数据库验证用户名和电子邮件 [英] Firebase realtime database validation username and email

查看:86
本文介绍了Firebase实时数据库验证用户名和电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近发现可以设置数据库规则来验证数据库是否已经具有相同的数据,但是当前它只接受要插入的相同数据,但是如何验证和防止相同的用户名和电子邮件输入?

Recently found out the database rules can be set to validate whether the database already have the same data but currently it just accepted same data to insert but how to validate and prevent same input of username and email?

{
"rules": {
        ".read": true,
    ".write": true,
        "username":{
       ".validate": "!root.child('username').child(newData.val()).exists()"
        },
        "email":{
        ".validate": "!root.child('email').child(newData.val()).exists()"
      }

        }
  }

根子级是通过电子邮件身份验证uid创建的,其余子级将位于同一节点下.

The root child is created by email authentication uid and the rest will be under the same nodes.

如何防止用户输入相同的用户名和电子邮件?

How to prevent user enter same username and email?

推荐答案

您的规则将验证是否存在单个属性/username 并具有与您要写入的新数据相同的值.您的用例似乎有所不同:您想确保所有用户的唯一用户名.

Your rules validate if a single property /username exists and has the same value as the new data you're writing. Your use-case seems different: you want to ensure a unique user name across all users.

您不能在Firebase的安全规则中的多个节点上确保唯一值.相反,您需要将用户名作为键存储在单独的集合中,即

You cannot ensure a unique value across many multiple nodes in Firebase's security rules. You instead will need to store the user names as keys in a separate collection, i.e.

usernames
  "rexyou0831": "ik3sf...."

以上数据结构表明用户 ik3sf ... 声明了名称 rexyou0831 .有了这样的结构,就可以保证用户名是唯一的,因为键在定义上必须是唯一的.您可以使用以下方法确保用户只能写新名称或删除自己的名称:

The above data structure indicates that user ik3sf... claimed name rexyou0831. With such a structure in place, user names are guaranteed to be unique since keys must by definition be unique in a collection. You can ensure that users can only write new names or delete their own name with:

{
  "rules": {
    "usernames": {
      "$name": {
        ".write": "!data.exists() || newData.val() === data.val()"
      }
    }
  }
}

要同样强制电子邮件地址的唯一性,您将需要为它们创建一个类似的集合.

To enforce uniqueness of the email addresses too, you will need to create a similar collection for those.

有关更多解释,请阅读先前涉及同一主题的问题之一:

For more explanation read one of the previous questions covering this same topic:

这篇关于Firebase实时数据库验证用户名和电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆