React Native

SignIn with Google for React Native

Introduction

In the last tutorial, you built a User login/logout feature to your App using the Parse.User class. Now you will learn how to use Google Sign-in to retrieve user data from Google and log in, sign up or link existent users with it. You will also install and configure react-native-google-signin lib to achieve that.

The Parse.User.linkWith method is responsible for signing up and logging in users using any third-party authentication method, as long as you pass the right parameters requested by each different provider. After linking the user data to a new or existent Parse.User, Parse will store a valid user session in your device. Future calls to methods like currentAsync will successfully retrieve your User data, just like with regular logins.

At any time, you can access this project via our GitHub repositories to checkout the styles and complete code.

Prerequisites

To complete this tutorial, you will need:

Goal

To build a User LogIn feature using Google Sign-in on Parse for a React Native App.

Step 1 - Installing dependencies

The most popular way to enable Google Sign-in on React Native is using react-native-google-signin to handle it. Since this library configuration depends on your development environment, target platform, and preferences, set it up following the official docs.

After that, make sure that your app main file (App.js or App.tsx) is correctly initializing and configuring GoogleSignin like this:
App.tsx/App.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Other imports
import {GoogleSignin} from '@react-native-community/google-signin';

// Parse initialization configuration goes here
// ...

// GoogleSignIn initial configuration
// iosClientId is required for iOS platform development and
// webCLientId for Android. Use only what is suitable to you
GoogleSignin.configure({
  iosClientId:
    'GOOGLE_IOS_CLIENT_ID',
  webClientId:
    'GOOGLE_ANDROID_WEB_CLIENT_ID',
});

// ...

Step 2 - Usign Google Sign-in with Parse

Let’s now create a new method inside the UserLogIn component calling Google Sign-in authentication modal with GoogleSignin.signIn. If the user signs in with Google, this call will retrieve the user data from Google and you need to store the id, idToken, and Google email for later.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const doUserLogInGoogle = async function () {
  try {
    // Check if your user can sign in using Google on his phone
    await GoogleSignin.hasPlayServices({showPlayServicesUpdateDialog: true});
    // Retrieve user data from Google
    const userInfo = await GoogleSignin.signIn();
    const googleIdToken = userInfo.idToken;
    const googleUserId = userInfo.user.id;
    const googleEmail = userInfo.user.email;
  } catch (error) {
    Alert.alert('Error!', error.code);
    return false;
  }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const doUserLogInGoogle = async function (): Promise<boolean> {
  try {
    // Check if your user can sign in using Google on his phone
    await GoogleSignin.hasPlayServices({showPlayServicesUpdateDialog: true});
    // Retrieve user data from Google
    const userInfo: object = await GoogleSignin.signIn();
    const googleIdToken: string = userInfo.idToken;
    const googleUserId: string = userInfo.user.id;
    const googleEmail: string = userInfo.user.email;
  } catch (error) {
    Alert.alert('Error!', error.code);
    return false;
  }
};

After that, you can use Parse.User.linkWith on a new Parse.User object to register a new user and log in. Note that if your user had already signed up using this Google authentication, linkWith will log him in using the existent account.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const doUserLogInGoogle = async function () {
  try {
    // Check if your user can sign in using Google on his phone
    await GoogleSignin.hasPlayServices({showPlayServicesUpdateDialog: true});
    // Retrieve user data from Google
    const userInfo = await GoogleSignin.signIn();
    const googleIdToken = userInfo.idToken;
    const googleUserId = userInfo.user.id;
    const googleEmail = userInfo.user.email;
    // Log in on Parse using this Google id token
    const userToLogin = new Parse.User();
    // Set username and email to match google email
    userToLogin.set('username', googleEmail);
    userToLogin.set('email', googleEmail);
    return await user
      .linkWith('google', {
        authData: {id: googleUserId, id_token: googleIdToken},
      })
      .then(async (loggedInUser) => {
        // logIn returns the corresponding ParseUser object
        Alert.alert(
          'Success!',
          `User ${loggedInUser.get('username')} has successfully signed in!`,
        );
        // To verify that this is in fact the current user, currentAsync can be used
        const currentUser = await Parse.User.currentAsync();
        console.log(loggedInUser === currentUser);
        // Navigation.navigate takes the user to the screen named after the one
        // passed as parameter
        navigation.navigate('Home');
        return true;
      })
      .catch(async (error) => {
        // Error can be caused by wrong parameters or lack of Internet connection
        Alert.alert('Error!', error.message);
        return false;
      });
  } catch (error) {
    Alert.alert('Error!', error.code);
    return false;
  }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const doUserLogInGoogle = async function (): Promise<boolean> {
  try {
    // Check if your user can sign in using Google on his phone
    await GoogleSignin.hasPlayServices({showPlayServicesUpdateDialog: true});
    // Retrieve user data from Google
    const userInfo: object = await GoogleSignin.signIn();
    const googleIdToken: string = userInfo.idToken;
    const googleUserId: string = userInfo.user.id;
    const googleEmail: string = userInfo.user.email;
    // Log in on Parse using this Google id token
    const userToLogin: Parse.User = new Parse.User();
    // Set username and email to match google email
    userToLogin.set('username', googleEmail);
    userToLogin.set('email', googleEmail);
    return await user
      .linkWith('google', {
        authData: {id: googleUserId, id_token: googleIdToken},
      })
      .then(async (loggedInUser: Parse.User) => {
        // logIn returns the corresponding ParseUser object
        Alert.alert(
          'Success!',
          `User ${loggedInUser.get('username')} has successfully signed in!`,
        );
        // To verify that this is in fact the current user, currentAsync can be used
        const currentUser: Parse.User = await Parse.User.currentAsync();
        console.log(loggedInUser === currentUser);
        // Navigation.navigate takes the user to the screen named after the one
        // passed as parameter
        navigation.navigate('Home');
        return true;
      })
      .catch(async (error: object) => {
        // Error can be caused by wrong parameters or lack of Internet connection
        Alert.alert('Error!', error.message);
        return false;
      });
  } catch (error) {
    Alert.alert('Error!', error.code);
    return false;
  }
};

Add this function to your UserSignIn component and assign it to your Google button onPress parameter. Go ahead and test your new function. Note that the user will be redirected to your home screen after successfully registering and/or signing in.

React Native Back4App

Step 3 - Verifying user sign in and session creation

To make sure that the Google sign-in worked, you can look at your Parse dashboard and see your new User (if your Google authentication data didn’t belong to another user), containing the Google authData parameters.

React Native Back4App

You can also verify that a valid session was created in the dashboard, containing a pointer to that User object.

React Native Back4App

Step 4 - Linking an existing User to Google Sign-in

Another linkWith possible use is to link an existing user with another auth provider, in this case, Google. Add this function that calls linkWith the same way you did in UserLogIn to your HelloUser component or directly to your home screen. The only difference here is that instead of calling the method from an empty Parse.User, you will use it from the logged-in user object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const doUserLinkGoogle = async function () {
  try {
    // Check if your user can sign in using Google on his phone
    await GoogleSignin.hasPlayServices({showPlayServicesUpdateDialog: true});
    // Retrieve user data from Google
    const userInfo = await GoogleSignin.signIn();
    const googleIdToken = userInfo.idToken;
    const googleUserId = userInfo.user.id;
    const authData = {
      id: googleUserId,
      id_token: googleIdToken,
    };
    let currentUser: Parse.User = await Parse.User.currentAsync();
    // Link user with his Google Credentials
    return await currentUser
      .linkWith('google', {
        authData: authData,
      })
      .then(async (loggedInUser) => {
        // logIn returns the corresponding ParseUser object
        Alert.alert(
          'Success!',
          `User ${loggedInUser.get(
            'username',
          )} has successfully linked his Google account!`,
        );
        // To verify that this is in fact the current user, currentAsync can be used
        currentUser = await Parse.User.currentAsync();
        console.log(loggedInUser === currentUser);
        return true;
      })
      .catch(async (error) => {
        // Error can be caused by wrong parameters or lack of Internet connection
        Alert.alert('Error!', error.message);
        return false;
      });
  } catch (error) {
    Alert.alert('Error!', error.code);
    return false;
  }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const doUserLinkGoogle = async function (): Promise<boolean> {
  try {
    // Check if your user can sign in using Google on his phone
    await GoogleSignin.hasPlayServices({showPlayServicesUpdateDialog: true});
    // Retrieve user data from Google
    const userInfo: object = await GoogleSignin.signIn();
    const googleIdToken: string = userInfo.idToken;
    const googleUserId: string = userInfo.user.id;
    const authData: object = {
      id: googleUserId,
      id_token: googleIdToken,
    };
    let currentUser: Parse.User = await Parse.User.currentAsync();
    // Link user with his Google Credentials
    return await currentUser
      .linkWith('google', {
        authData: authData,
      })
      .then(async (loggedInUser: Parse.User) => {
        // logIn returns the corresponding ParseUser object
        Alert.alert(
          'Success!',
          `User ${loggedInUser.get(
            'username',
          )} has successfully linked his Google account!`,
        );
        // To verify that this is in fact the current user, currentAsync can be used
        currentUser = await Parse.User.currentAsync();
        console.log(loggedInUser === currentUser);
        return true;
      })
      .catch(async (error: object) => {
        // Error can be caused by wrong parameters or lack of Internet connection
        Alert.alert('Error!', error.message);
        return false;
      });
  } catch (error) {
    Alert.alert('Error!', error.code);
    return false;
  }
};

Assign this function to a Google button onPress parameter on your home screen. Test your new function, noting that the Parse.User object authData value will be updated with the new auth provider data. Verify if the user has indeed updated in your Parse server dashboard.

React Native Back4App

Conclusion

At the end of this guide, you learned how to log in, sign up or link existing Parse users on React Native using Google Sign-in with react-native-google-signin. In the next guide, we will show you how to perform useful user queries.