Firebase realtime database validation username and email

北慕城南 提交于 2021-02-15 07:40:21

问题


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

        }
  }

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?


回答1:


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.

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...."

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 android : make username unique
  • Enforcing unique usernames with Firebase simplelogin
  • Firebase Database Rules for Unique Usernames
  • How do you prevent duplicate user properties in Firebase?


来源:https://stackoverflow.com/questions/46056025/firebase-realtime-database-validation-username-and-email

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