Home > Software engineering >  Firebase relatime database add google authenticated users
Firebase relatime database add google authenticated users

Time:12-31

I'm trying to add users to realtime database who are authenticated using google as shown below

document.getElementById("btnGoogleLogin").addEventListener('click', function () {
    signInWithPopup(auth, provider)
        .then((result) => {
            // This gives you a Google Access Token. You can use it to access the Google API.
            const credential = GoogleAuthProvider.credentialFromResult(result);
            const token = credential.accessToken;
           
            // The signed-in user info.
            const user = result.user;
       
            const userId = user.uid;
            const email = user.email;
            const imageUrl = user.photoURL;
            const name = user.displayName;

            const dbRef = ref(database);
            console.log("Current User:"   userId);
            get(dbRef, '/users'   userId).then((snapshot) => {
                if (snapshot.exists()) {
                    console.log(snapshot.val());
                } else {
                    console.log("First time user..Need to add it to db");
                    writeUserData(userId, email, imageUrl, name)
                }
            }).catch((error) => {
                console.error(error);
            });

        }).catch((error) => {
            // Handle Errors here.
            const errorCode = error.code;
            const errorMessage = error.message;
            // The email of the user's account used.
            const email = error.email;
            // The AuthCredential type that was used.
            const credential = GoogleAuthProvider.credentialFromError(error);
            console.log(error);
        });
});


function writeUserData(userId, email, imageUrl, name) {
    set(ref(database, '/'   userId), {
        email: email,
        imageUrl: imageUrl,
        name: name
    })
        .then(() => {
            window.location.href = "https://www.mysite.default.html";
        })
        .catch((error) => {
            // The write failed...
        });
}

The problem is first time it add user under users db and when a new user who login using google is not being added to the existing users db but added in authetication.

I am not sure how to get rid of this.

CodePudding user response:

First as commented by @Frank, there must be a / between 'users' and userId. Then get() takes only 1 parameter of type Query (or a DatabaseReference) but you are passing 2 and hence the get() is querying dbRef which means the entire database. The database might be empty by default and hence the first user gets added but there after snapshot.exists() would always be true and newer users are not added.

Using child() to create a DatabaseReference should resolve this:

import { child, get } from "firebase/database"

const userRef = child(dbRef, 'users/'   userId);

get(userRef).then((snapshot) => {
  if (snapshot.exists()) {
    console.log(snapshot.val());
  } else {
    console.log("First time user..Need to add it to db");
    writeUserData(userId, email, imageUrl, name)
  }
})
  • Related