Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Database Rules - Get displayName

I added Firebase to my website and created a signup form. When the user clicks the "signup" button it creates a user using "Firebase Authentication", then it updates the user's displayName, and finally adds some data about the user to the database:

firebase.auth().createUserWithEmailAndPassword(email, password).then(function () {

    profile = firebase.auth().currentUser;

    profile.updateProfile({
       displayName: "name-value"
    }).then(function() {

        // Update successful.

        firebase.database().ref("/users/" + profile.uid).set({
            data:{
                country: "country-value",
                city: "city-value"
            }
        });
    });
}).catch(function(error) {
    // Handle Errors here.
});

Everything worked fine until I changed the database rules from:

{
    "rules": {
        ".read": true,
        ".write": true
        }
    }
}

To:

{
    "rules": {
        "users": {
            ".read": true,
            "$user": {
                ".write": "auth.token.name !== null"
            }
        }
    }
}

I used auth.token.name as it is written in the guide to check whether or not the user's displayName exists (I planned to make it check some more things about it later). Somehow "firebase rules" 'thinks' that auth.token.name equals null, even though I set the displayName before. Why is it happening and what can I do to make it work?

Thanks in advance :)

like image 605
Programmer Avatar asked Apr 04 '18 00:04

Programmer


Video Answer


1 Answers

First, Firestore has replaced Realtime Database and should be used for all projects going forward - more features.

Re Realtime DB rules, it's is best practice to check uid variable vs display name. See Variables:

{
  "rules": {
    ".read": true,
    "$comment": {
      ".write": "!data.exists() && newData.child('user_id').val() == auth.uid"
    }
  }
}

Finally, IIF you implement database security rules using Firebase Authentication, you MUST use .onAuthStateChanged to drive your application as your auth() variables WILL BE null for a second on initial page/app load as this is an asynchronous method. So, don't try and write or read anything on DOM ready. You must trigger db conversations within .onAuthStateChanged like below:

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        //USER SIGNED IN. WE ARE READY
    }
    else {
        //USER IS NOT SIGNED IN
    }
});
like image 117
Ronnie Royston Avatar answered Nov 12 '22 14:11

Ronnie Royston