Home > Blockchain >  Using Firebase Google Authentication with React Native
Using Firebase Google Authentication with React Native

Time:02-05

I have been encountering an error when trying to use Firebase's SignIn With google auth method. So far I have:

  1. Enabled the google auth method in my admin console
  2. Looked at the docs for it and implemented the requirements
  3. Enabled, and correctly got the Email/Password auth to work

I am trying to use the signInWithPopup method instead of a redirect.

Here is the SignIn.js code file:

import React, { useState } from 'react';
import { StyleSheet, Text, View, Button, TextInput, Pressable } from 'react-native';
import tw from 'tailwind-react-native-classnames';
import { signInWithEmailAndPassword, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
import { auth, provider } from "../firebaseConfig";
import { Ionicons } from '@expo/vector-icons';
import { Feather } from '@expo/vector-icons';


import SignInHeader from '../components/SignInHeader';


export default function SignIn({ navigation }) {

    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");


    let signInWithGoogle = () => {
        signInWithPopup(auth, provider)
            .then((result) => {
                const credential = GoogleAuthProvider.credentialFromResult(result);
                const token = credential.accessToken;
                const user = result.user;
                navigation.navigate("Home");
                console.log(user);
            })
            .catch((error) => {
                const errorCode = error.code;
                const errorMessage = error.message;
                const email = error.customData.email;
                const credential = GoogleAuthProvider.credentialFromError(error);
                console.log(errorCode, errorMessage, email, credential);
            });
    }


    let signIn = () => {
        signInWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
                const user = userCredential.user;
                navigation.navigate("Home");
                console.log(user);
            })
            .catch((error) => {
                const errorCode = error.code;
                const errorMessage = error.message;
                console.log(errorCode, errorMessage);
                switch (errorCode) {
                    case "auth/invalid-email":
                        alert("Please Enter a valid email address");
                        break;
                    case "auth/user-not-found":
                        alert("User not found");
                        break;
                    case "auth/wrong-password":
                        alert("Incorrect Password. Try again.");
                        break;
                    case "auth/internal-error":
                        alert("Please enter a valid password");
                        break;
                }
            });
    }



    return (
        <>
            <SignInHeader />
            <View style={{ alignItems: 'center', marginTop: '25%', paddingTop: 10 }}>
                <View style={styles.searchSection}>
                    <Ionicons name="mail-outline" size={20} color="black" style={styles.searchIcon} />
                    <TextInput
                        style={styles.input}
                        placeholder="Email"
                        onChangeText={text => setEmail(text)}
                        value={email}
                        clearButtonMode="always"

                    />
                </View>
                <View style={{ padding: 25 }}>
                    <View style={styles.searchSection}>
                        <Feather name="lock" size={20} color="black" style={styles.searchIcon} />
                        <TextInput
                            style={styles.input}
                            placeholder="Password"
                            onChangeText={text => setPassword(text)}
                            value={password}
                            secureTextEntry={true}
                            clearButtonMode="always"
                        />
                    </View>
                </View>
                <Pressable style={{ marginLeft: '55%', marginTop: -10 }} onPress={() => navigation.navigate("ResetPassword")}>
                    <Text style={{ color: '#cdcdcd' }}>Forgot Password?</Text>
                </Pressable>

                <Pressable onPress={signIn} style={({ pressed }) => [
                    {
                        backgroundColor: pressed
                            ? '#34AE65'
                            : '#64DA93'
                    },
                    styles.notPressed,
                ]}>
                    <Text style={{ fontFamily: "OpenSans_600SemiBold", fontSize: 20, color: 'white' }}>Log In</Text>
                </Pressable>

                <Pressable onPress={signInWithGoogle} style={({ pressed }) => [
                    {
                        backgroundColor: pressed
                            ? '#34AE65'
                            : '#64DA93'
                    },
                    styles.notPressed,
                ]}>
                    <Text style={{ fontFamily: "OpenSans_600SemiBold", fontSize: 20, color: 'white' }}>Log In with Google</Text>
                </Pressable>

                <Pressable onPress={() => navigation.navigate("SignUp")}>
                    <Text style={{ flex: 1, color: '#cdcdcd', marginTop: 20, flexDirection: 'row' }}>Don't have and account?<Text style={{ color: 'grey' }}> Sign Up</Text></Text>
                </Pressable>

            </View >
        </>
    );
}

const styles = StyleSheet.create({
    searchSection: {
        flexDirection: 'row',
        alignItems: 'center',
        width: 360,
        height: 45,
        borderBottomColor: '#64DA93',
        borderBottomWidth: 2,
    },
    searchIcon: {
        padding: 1,

    },
    input: {
        flex: 1,
        paddingTop: 10,
        paddingRight: 10,
        paddingBottom: 10,
        paddingLeft: 10,
    },
    notPressed: {
        height: 45,
        width: 360,
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 10,
        marginTop: 50
    }
});

Next, which is important is my firebaseConfig.js code file:

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAuth, GoogleAuthProvider } from "firebase/auth";

const firebaseConfig = {
    apiKey: "xx",
    authDomain: "xx",
    projectId: "xx",
    storageBucket: "xx",
    messagingSenderId: "xx",
    appId: "xx",
    measurementId: "xx"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth();
const provider = new GoogleAuthProvider();
export { auth, provider };

This is the error:

ERROR TypeError: (0, _auth.signInWithPopup) is not a function. (In '(0, _auth.signInWithPopup)(_firebaseConfig.auth, _firebaseConfig.provider)', '(0, _auth.signInWithPopup)' is undefined)

Thanks for the help.

CodePudding user response:

signInWithPopup is not supported in React Native. Use auth().signInWithCredential(googleCredential) instead.

Upon successful sign-in, any onAuthStateChanged listeners will trigger with the new authentication state of the user.

Consider using this library instead as the one you are using is really meant for the web

  • Related