问题
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