如何在React Native中使用Firebase检测登录用户是现有用户还是新用户。我已经使用 Google auth 来创建身份验证,但不幸的是我没有得到任何名为 isNewUser 的字段作为回报承诺。
下面是我的代码...
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
对象中,该对象仅在调用signInWithCredential
后才可用。
const credentialPromise = auth().signInWithCredential(googleCredential);
credentialPromise.then((credential) => {
console.log(credential.additionalUserInfo.isNewUser);
})
您可以通过将用户的创建时间戳与上次登录进行比较来确定用户是否是来自身份验证状态侦听器的新用户:
function onAuthStateChanged(user) {
if (user) {
if (user.metadata.creationTime <> user.metadata.lastSignInTime) {
...
}
}
}
另请参阅:
To check if a user exists or is a new user in Firebase Authentication using Google Sign-In, the essential part of the code focuses on fetching the sign-in methods associated with the email address and checking if any method exists.
const checkIfUserExists = async () => {
try {
// Check for Play Services and sign in with Google
await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true });
const { idToken, user } = await GoogleSignin.signIn();
const email = user?.email;
if (email) {
// Check if any sign-in method exists for this email
const signInMethods = await auth().fetchSignInMethodsForEmail(email);
if (signInMethods.length > 0) {
// User exists, sign in with Google credentials
const googleCredential = auth.GoogleAuthProvider.credential(idToken);
const userCredential = await auth().signInWithCredential(googleCredential);
console.log('Existing user:', userCredential.user);
return 'existing';
} else {
// User does not exist
console.log('No user found with this email.');
return 'new';
}
}
} catch (error) {
console.error('Error checking user:', error);
}
};