Day 3: Adding User Authentication with Firebase (Google, Facebook Login)


Today, you’ll set up user authentication for your e-commerce app using Firebase Authentication. You’ll implement Google and Facebook login options, allowing users to sign in easily.

What You Will Do Today:

  1. Configure Google and Facebook sign-in in Firebase.
  2. Set up authentication providers in Firebase Console.
  3. Implement Google and Facebook login in the app.

Step 1: Configure Firebase Authentication Providers

  1. Go to the Firebase Console and open your project.
  2. Navigate to Authentication > Sign-in method.
  3. Enable Google and Facebook providers:
  • For Google, just click Enable and save.
  • For Facebook, follow these steps:
    • Go to the Facebook Developer Console.
    • Create a Facebook App and get your App ID and App Secret.
    • In Firebase, enter the App ID and App Secret and save.

Step 2: Install Dependencies for Google and Facebook Login

  1. Install React Native Google Sign-In and Facebook SDK:
   npm install @react-native-google-signin/google-signin react-native-fbsdk-next
  1. Link the dependencies for iOS (skip this step if using React Native 0.60+ with auto-linking):
   cd ios
   pod install
   cd ..

Step 3: Set Up Google Sign-In

  1. Configure Google Sign-In by adding the following in App.js:
   import { GoogleSignin } from '@react-native-google-signin/google-signin';

   GoogleSignin.configure({
     webClientId: 'YOUR_GOOGLE_WEB_CLIENT_ID',
   });

Replace YOUR_GOOGLE_WEB_CLIENT_ID with your Google OAuth 2.0 client ID from Firebase Console under Project Settings > General > Web client ID.

  1. Add Google Sign-In function in AuthService.js:
   // src/AuthService.js
   import { GoogleSignin } from '@react-native-google-signin/google-signin';
   import auth from '@react-native-firebase/auth';

   export async function googleSignIn() {
     try {
       await GoogleSignin.hasPlayServices();
       const { idToken } = await GoogleSignin.signIn();
       const googleCredential = auth.GoogleAuthProvider.credential(idToken);
       return auth().signInWithCredential(googleCredential);
     } catch (error) {
       console.error('Google Sign-In Error:', error);
       throw error;
     }
   }

Step 4: Set Up Facebook Login

  1. Add Facebook login to AuthService.js:
   // src/AuthService.js
   import auth from '@react-native-firebase/auth';
   import { LoginManager, AccessToken } from 'react-native-fbsdk-next';

   export async function facebookSignIn() {
     try {
       const result = await LoginManager.logInWithPermissions(['public_profile', 'email']);
       if (result.isCancelled) throw 'User cancelled the login process';

       const data = await AccessToken.getCurrentAccessToken();
       if (!data) throw 'Something went wrong obtaining access token';

       const facebookCredential = auth.FacebookAuthProvider.credential(data.accessToken);
       return auth().signInWithCredential(facebookCredential);
     } catch (error) {
       console.error('Facebook Sign-In Error:', error);
       throw error;
     }
   }

Step 5: Implement Sign-In Buttons in the App

  1. Create a new screen LoginScreen.js in the screens folder.
   // screens/LoginScreen.js
   import React from 'react';
   import { View, Text, Button, StyleSheet } from 'react-native';
   import { googleSignIn, facebookSignIn } from '../AuthService';

   function LoginScreen({ navigation }) {
     const handleGoogleSignIn = async () => {
       try {
         await googleSignIn();
         navigation.replace('ProductList');
       } catch (error) {
         console.error('Google Sign-In Error:', error);
       }
     };

     const handleFacebookSignIn = async () => {
       try {
         await facebookSignIn();
         navigation.replace('ProductList');
       } catch (error) {
         console.error('Facebook Sign-In Error:', error);
       }
     };

     return (
       <View style={styles.container}>
         <Text style={styles.title}>Login</Text>
         <Button title="Sign in with Google" onPress={handleGoogleSignIn} />
         <Button title="Sign in with Facebook" onPress={handleFacebookSignIn} />
       </View>
     );
   }

   const styles = StyleSheet.create({
     container: {
       flex: 1,
       justifyContent: 'center',
       alignItems: 'center',
       padding: 20,
     },
     title: {
       fontSize: 24,
       fontWeight: 'bold',
       marginBottom: 20,
     },
   });

   export default LoginScreen;
  1. Update the navigation stack in App.js to include LoginScreen:
   // App.js
   import React from 'react';
   import { NavigationContainer } from '@react-navigation/native';
   import { createStackNavigator } from '@react-navigation/stack';
   import LoginScreen from './screens/LoginScreen';
   import ProductList from './screens/ProductList';
   import ProductDetail from './screens/ProductDetail';

   const Stack = createStackNavigator();

   export default function App() {
     return (
       <NavigationContainer>
         <Stack.Navigator>
           <Stack.Screen name="LoginScreen" component={LoginScreen} options={{ title: 'Login' }} />
           <Stack.Screen name="ProductList" component={ProductList} options={{ title: 'Products' }} />
           <Stack.Screen name="ProductDetail" component={ProductDetail} options={{ title: 'Product Details' }} />
         </Stack.Navigator>
       </NavigationContainer>
     );
   }
  1. Set LoginScreen as the default screen, so users start on the login page.
See also  Part 8 : PHP tutorial for kids and beginners

Step 6: Testing Google and Facebook Login

  1. Run your app with npx react-native run-android or npx react-native run-ios.
  2. On the Login Screen, use the Sign in with Google and Sign in with Facebook buttons.
  3. After a successful login, users should be navigated to the Product List screen.

Summary

Today, you implemented user authentication with Google and Facebook login using Firebase Authentication. This setup allows users to sign in with their social accounts, making it convenient for them to access your app.

Tomorrow, you’ll add a shopping cart with local storage to allow users to save their selected products.


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.