Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
Firebase relatime database add google authenticated users

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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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)
  }
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda