簡體   English   中英

如何在反應原生中使用 firebase 檢測 google auth 登錄用戶是否為 NewUser

[英]How to detect whether google auth login user is a NewUser or not using firebase in react native

如何檢測登錄用戶是現有用戶還是使用 firebase in react native 的新用戶。 我已經使用 Google auth 創建了身份驗證,但不幸的是,我沒有得到任何名為 isNewUser 的字段作為返回 promise。

下面是我的代碼...

async function onGoogleButtonPress() {
    // Get the users ID token
    const {idToken} = await GoogleSignin.signIn();

    // Create a Google credential with the token
    const googleCredential = auth.GoogleAuthProvider.credential(idToken);

    // Sign-in the user with the credential
    return auth().signInWithCredential(googleCredential);
  }

  function onAuthStateChanged(user) {
    if (user) {
      firestore()
        .collection('Users')
        .doc(user.uid)
        .set({
          user: user.displayName,
        email: user.email,
        photo: user.photoURL,
        })
        .then(() => {
          console.log('User added!');
        });
    }
    if (initializing) setInitializing(false);
  }


 useEffect(() => {
    const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
    return subscriber; // unsubscribe on unmount
  });

這是我得到的回復。

 {"displayName": "***", "email": "**@gmail.com", "emailVerified": true, "isAnonymous": false, "metadata": {"creationTime": 15960**412290, "lastSignInTime": 15960**65185}, "phoneNumber": null, "photoURL": "**", "providerData": [[Object]], "providerId": "firebase", "uid": "*******"}

我現在的問題是每次用戶成功驗證谷歌登錄方法時,它都會將數據添加到 firebase 數據庫中。 有什么方法可以檢測到用戶是新用戶還是現有用戶?

幫助將是巨大且可觀的:)

isNewUser屬性位於UserCredential object 中,該屬性僅在調用signInWithCredential后才可用。

const credentialPromise = auth().signInWithCredential(googleCredential);
credentialPromise.then((credential) => {
  console.log(credential.additionalUserInfo.isNewUser);
})

可以通過將用戶的創建時間戳與其上次登錄進行比較來確定用戶是否是來自 auth state 偵聽器的新用戶:

function onAuthStateChanged(user) {
  if (user) {
    if (user.metadata.creationTime <> user.metadata.lastSignInTime) {
      ...
    }
  }
}

另見:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM