【发布时间】:2021-12-20 07:20:48
【问题描述】:
我正在尝试在我的 react 本机应用程序中使用带有 JavaScript 的 Google 登录进行身份验证,但我的 onSignIn() 函数中出现错误:
“googleUser.getAuthResponse 不是函数”
我不确定是什么原因造成的,或者为什么我似乎没有获得正确的凭据,有人可以解释如何消除这个错误。
import React, { Component } from "react";
import { View, Text, StyleSheet, Button } from "react-native";
import firebase from "firebase";
import {
getAuth,
onAuthStateChanged,
signInWithCredential,
GoogleAuthProvider,
getAuthResponse,
} from "firebase/auth";
import * as Google from "expo-google-app-auth";
class LoginScreen extends Component {
isUserEqual(googleUser, firebaseUser) {
if (firebaseUser) {
var providerData = firebaseUser.providerData;
for (var i = 0; i < providerData.length; i++) {
if (
providerData[i].providerId ===
firebase.auth.GoogleAuthProvider.PROVIDER_ID &&
providerData[i].uid === googleUser.getBasicProfile().getId()
) {
return true;
}
}
}
return false;
}
onSignIn(googleUser) {
console.log("Google Auth Response", googleUser);
// We need to register an Observer on Firebase Auth to make sure auth is initialized.
let unsubscribe = firebase.auth().onAuthStateChanged((firebaseUser) => {
unsubscribe();
// Check if we are already signed-in Firebase with the correct user.
if (!this.isUserEqual(googleUser, firebaseUser)) {
// Build Firebase credential with the Google ID token.
const credential = firebase.auth.GoogleAuthProvider.credential(
googleUser.getAuthResponse().id_token
);
console.log("Credential", credential);
// Sign in with credential from the Google user.
firebase
.auth()
.signInWithCredential(credential)
.catch((error) => {
// Handle Errors here.
let errorCode = error.code;
let errorMessage = error.message;
// The email of the user's account used.
let email = error.email;
// The firebase.auth.AuthCredential type that was used.
let credential = error.credential;
console.log(errorCode, errorMessage, email);
});
console.log("WORKED");
} else {
console.log("User already signed-in Firebase.");
}
});
}
signInWithGoogleAsync = async () => {
const result = await Google.logInAsync({
androidClientId: `ANDROID CLIENT ID`,
iosClientId: `IOS CLIENT ID`,
scopes: [
"profile",
"email",
"https://www.googleapis.com/auth/calendar",
"https://www.googleapis.com/auth/calendar.events",
],
});
if (result.type === "success") {
//console.log("Restult ", result);
this.onSignIn(result);
return result.accessToken;
} else {
return { cancelled: true };
}
};
render() {
return (
<View style={styles.container}>
<Button
title="Sign In With Google"
onPress={() => this.signInWithGoogleAsync()}
/>
</View>
);
}
}
export default LoginScreen;
【问题讨论】:
标签: javascript reactjs firebase react-native firebase-authentication