user6735919
user6735919

Reputation:

Using JavaScript and Firebase, how can I create user specific objects?

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.

Upvotes: 0

Views: 753

Answers (1)

André Kool
André Kool

Reputation: 4978

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.

Upvotes: 1

Related Questions