Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

175
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda