Firebase Email Authentication and Write Database to Transaction

I am using Firebase web SDK v4.0.0 and I am trying to keep only unique usernames (user-selected string) in the database. I have configured email / password authentication and it works fine. I've also set up rules to ensure that the username is unique. The database entry depends on the authentication passed since the user was created. However, when a collision occurs during the database write phase (that is, the selected username is not unique), the user has already been created.

It looks like the right thing to do is a transaction involving user creation / authentication and database writing, but I cannot find any information on this in the docs. Has anyone solved this situation before?

Here is my rules file:

{
  "rules": {
     "users": {
       "$userID": {
         "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()"
       }
     }
   }
}

      

and the corresponding bit of my registration code:

var ref = firebase.database().ref();
var userData = {};
userData["usernames/" + username] = firebase.auth().currentUser.uid;
userData["users/" + firebase.auth().currentUser.uid] = {
  username: username,
  signupdate: firebase.database.ServerValue.TIMESTAMP,
  uid: firebase.auth().currentUser.uid, // store it here for easy comparison later
  displayname: displayname,
  email: email
};
// Do a deep-path update
ref.update(userData, function(error) {
  if (error) {
    console.log("Error updating data:");
    console.log(error);
  }
});

      

BTW I am doing client side validation before the form is submitted to prevent reuse of usernames in my web form. This server-side approach is to try to prevent a malicious user from using the console to bypass my check and send "useless" duplicates.

+3


source to share





All Articles