I want to check if the username already is in use. This function gets called when the current user does not have a child of "username":
func createUsername()
{
let userID = FIRAuth.auth()?.currentUser?.uid
FIRDatabase.database().reference().updateChildValues([
"users/\(userID!)/username": username.text!,
"usernames/\(username.text!)": userID!
], withCompletionBlock: { (error, reference) in
if (error != nil) {
print("disallowed")
// Write was disallowed because username exists
}
})
}
In combination with this rules:
{
"rules": {
"users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid",
"username": {
".read": true,
".write": "!data.exists() && newData.exists()",
".validate": "newData.isString()"
}
}
},
"usernames": {
"$username": {
".read": true,
".write": "!data.exists() && newData.exists()",
".validate": "newData.isString() && newData.val() == root.child('users/' + auth.uid + '/username').val()"
}
}
}
}
I got the answer from: https://groups.google.com/forum/#!topic/firebase-talk/dA1Lkykd-tk I get this error message:
[Firebase/Database][I-RDB03812] updateChildValues: at / failed: permission_denied
I am not sure why this wont work. I also tried this answer: Firebase android : make username unique But this did not work for me. There is something wrong with the rules but I dont know what.
Update, little change in rules, still same error:
{
"rules": {
"users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid",
"username": {
".read": true,
".write": "!data.exists() && newData.exists()",
".validate": "newData.isString()"
}
}
},
"usernames": {
"$username": {
".read": true,
".write": "!data.exists() && newData.exists()",
".validate": "newData.isString() && newData.val() == newData.parent().parent().child('users/' + auth.uid + '/username').val()"
}
}
}
}
I also changed the parent() things, but it wouldn't work aswell. I changed to 4 parents, and 0 parents. Same error.