How to Link Each User to Their Data in Firebase

How do I link each user to their data in Firebase?

First of all i suggest you spend some time getting familiar with firebase by reading the Firebase Guide (Link to old Firebase Guide). Everything you need to know to answer your own question is available there. But for simplicity i will put an example here:

Lets start with security, here are the basic firebase rules you need for this example: (source: Understanding Security) (old source: Understanding Security)

{
"rules": {
"users": {
"$user_id": {
".write": "$user_id === auth.uid"
}
}
}
}

I will skip the actual user creation and logging in and focus on the question about storing and retrieving user data.

Storing data: (source: Firebase Authentication) (old source: User Authentication)

// Get a reference to the database service
var database = firebase.database();
// save the user's profile into Firebase so we can list users,
// use them in Security and Firebase Rules, and show profiles
function writeUserData(userId, name, email, imageUrl) {
firebase.database().ref('users/' + userId).set({
username: name,
email: email
//some more user data
});
}

The resulting firebase data will look like this:

{
"users": {
"simplelogin:213": {
"username": "password",
"email": "bobtony"
},
"twitter:123": {
"username": "twitter",
"email": "Andrew Lee"
},
"facebook:456": {
"username": "facebook",
"email": "James Tamplin"
}
}
}

And last but not least the retreiving of the data, this can be done in several ways but for this example i'm gonna use a simple example from the firebase guide: (source: Read and Write data) (old source: Retreiving Data)

//Get the current userID
var userId = firebase.auth().currentUser.uid;
//Get the user data
return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {
//Do something with your user data located in snapshot
});

EDIT: Added example of return data

So when you are logged in as user twitter:123 you will get a reference to the location based on your user id and will get this data:

"twitter:123": {
"username": "twitter",
"email": "Andrew Lee"
}

How to link Firebase's Authentication to Realtime Database?

From the code you are writing I expect you are using react-native-firebase? If not - you should use it :-)

Solution for react-native-firebase:

As soon as you are registered or logged in you can use the firebase.auth().currentUser Object. This object includes a uid (currentUser.uid). You can then push some data to the database under the uid with something like firebase.database().ref('users/' + firebase.auth().currentUser.uid + "/profile").set(); For example in your register like this:

    register () {
const validate = this.refs.form.getValue();
if(this.validate) {
const errorHandler = ((e)=>{
console.log(e);
if(e.code == 'auth/email-already-in-use'){
Toast.show({ text: `${Strings.ST36}`, position: 'bottom', buttonText: `${Strings.ST33}` })
} else {
Toast.show({ text: `${Strings.ST32}`, position: 'bottom', buttonText: `${Strings.ST33}` })
}
})
firebase.auth().createUserWithEmailAndPassword(validate.email,validate.password).then((response) => {
firebase.auth().currentUser.updateProfile({
displayName : validate.name,
}).then(()=>{
firebase.database().ref('users/' + firebase.auth().currentUser.uid + "/profile").set(firebase.auth().currentUser);
}).catch(errorHandler);
}).catch(errorHandler)
}}

Security:

I do not recommend to set the whole user data in your database, since you do not need it there. Use the database to save user progress or something similar.

Security 2:

You should set the security rules of your database, that only the user can read and write in his db node. Use something like:

{
"rules": {
".read": false,
".write": false,
"users":
{
"$userId":
{
".read": "auth.uid === $userId",
".write": "auth.uid === $userId"
}
}
}
}

Edit 1:
Please try to remove push since it generates a unique key, which has nothing to do with the user. It will be hard to find your user data again.
And do not use set twice since it won't work.
Sample Image

Edit 2:
You have to set the nodes you want to be readable/writable to true like this:

{
"rules": {
".read": false,
".write": false,
"users":
{
"$userId":
{
".read": "auth.uid === $userId",
".write": "auth.uid === $userId"
}
},
// readable node
"messages":
{
".read": true
},
// readable and writable node
"messages":
{
".read": true,
".write": true
}
}
}


Related Topics



Leave a reply



Submit