Firebase Auth and Database

How to link between Authenticated users and Database in Firebase?

After authentication, create a child with the UID given by Firebase, and set its value to your user class:

//get firebase user
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

//get reference
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(USERS_TABLE);

//build child
ref.child(user.getUid()).setValue(user_class);

USERS_TABLE is a direct child of root.

Then when you want to retrieve the data, get a reference to the user by its UID, listen for addListenerForSingleValueEvent() (invoked only once), and iterate over the result with reflection:

//get firebase user
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

//get reference
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(USERS_TABLE).child(user.getUid());
//IMPORTANT: .getReference(user.getUid()) will not work although user.getUid() is unique. You need a full path!

//grab info
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final Profile tempProfile = new Profile(); //this is my user_class Class
final Field[] fields = tempProfile.getClass().getDeclaredFields();
for(Field field : fields){
Log.i(TAG, field.getName() + ": " + dataSnapshot.child(field.getName()).getValue());
}
}

@Override
public void onCancelled(DatabaseError databaseError) {
}
});

edit:

Or without reflection:

@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final Profile p = dataSnapshot.getValue(Profile.class);
}

Does Firebase's UI Auth connect with Realtime Database?

No,firebase does not do such a thing.You must add users to a realtime database by yourself.
Once signed in,you can access user properties for example(username and email). After that,you have the freedom how do you want to manage your users.


EDIT:

//you initialize app with fierebase config
app.initializeApp(firebaseConfig);
this.auth=app.auth();

//this line return a Promise
this.auth.signInWithEmailAndPassword(email,password).then(
authUser=>{ /*

Here you add user to firebase
you want to use authUser.user.id as document id
You also can access email and password
*/


});

Here is a link that might be helpful:
https://firebase.google.com/docs/auth/web/manage-users

Can I use firebase for only auth and any other SQL database to store other user data?

Firebase Authentication isn't related in any way to Cloud Firestore. You can authenticate your users with Firebase and save the data in any database you want, even in an SQL database. However, Cloud Firestore has some benefits. So I recommend you check the official docs.

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