0

All I am really trying to do here is allow a user to create an object such that only that user can see and change it. So, for example: I have code that looks similar to this:

    function createAccount(email, pass){
       firebase.auth().createUserWithEmailAndPassword(email,pass).catch(function(error) {
            var errorCode = error.code;
            var errorMessage = error.message;
            console.log(errorCode+":"+errorMessage);
       });
    }

I also have a function that I call createAccountHome() that I am hoping to be structured like:

    function createAccountHome(){
        firebase.database().ref().child('Profiles').push({
            // user id : something to link object solely to this user
            // data: data
        });
    }

I am hoping that by the end of this phase, I can create an account, and then have a profile generated automatically for the user so that the user only has write access to his/her own information.

  • 1
    Instead of push you can use the user uid like this: firebase.database().ref().child('Profiles').child(user.uid).set({data:data}) – André Kool Sep 16 '16 at 09:48
  • @AndréKool that's indeed the idiomatic way to do this. Do you want to write an answer? Otherwise I'm quite sure there are duplicates that explain this already. – Frank van Puffelen Sep 16 '16 at 13:33
  • See http://stackoverflow.com/questions/32151178/how-do-you-include-a-username-when-storing-email-and-password-using-firebase-ba/32151335#32151335 – Frank van Puffelen Sep 16 '16 at 13:39

1 Answers1

1

The most common way to archieve this is to save user data under their user id. So instead of using push() you use set() like this:

firebase.database().ref().child('Profiles').child(user.uid).‌​set({
  //data:data
})

And to make sure users can only see and edit their own profile you use these security rules:

{
  "rules": {
    "Profiles": {
      "$uid": {
        ".read": "auth != null && auth.uid ==$uid",
        ".write": "auth != null && auth.uid ==$uid"
      }
    }
  }
}

And for some reading: link to old docs explaining more about storing user data.

André Kool
  • 4,880
  • 12
  • 34
  • 44