Search code examples
node.jsreactjsreact-nativeaccess-tokenfacebook-access-token

What is the best way to get Google and Facebook access token for OAuth using React Native?


I'm getting the profile on server side. Just want the Access token on my frontend.

passport.use('google', new GooglePlusTokenStratey ({

clientID: process.env.GCID,
clientSecret: process.env.GCS,


}, async(accessToken, refreshToken, profile, done) => {
console.log("accessToken ",accessToken);
console.log("refreshToken ",refreshToken);
console.log("profile ",profile);

const existingUser = await Social.findOne({ "uid": profile.id });
if (existingUser) {
  return done(null, existingUser);
}

const newUser = new Social({
    method: "google",
    email: profile.emails[0].value,
    name: profile.displayName,
    uid: profile.id  
  });

  await newUser.save();
  done(null, newUser);

}));

I'm calling route now using postman and sending access token in JSON, but want to implement it using react-native.


Solution

  • Google Sign In

    Use @react-native-community/google-signin.

    Common use case:

    import { GoogleSignin, statusCodes } from '@react-native-community/google-signin';
    
    // Somewhere in your code
    const googleLogin = async () => {
        try {
          await GoogleSignin.hasPlayServices();
          const googleUser = await GoogleSignin.signIn();
          const accessToken = googleUser.idToken;
        } catch (e) {
          if (e.code === statusCodes.SIGN_IN_CANCELLED) {
            console.log('User cancelled google login');
          } else if (e.code === statusCodes.IN_PROGRESS) {
            console.log('Sign in in progress');
          } else if (e.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
            console.log('Play service not available');
          } else {
            console.log('Unknown google sign in error');
          }
        }
      };
    

    Facebook Sign In

    Use react-native-fbsdk

    Common use case:

    import React, { Component } from 'react';
    import { View } from 'react-native';
    import { LoginButton, AccessToken } from 'react-native-fbsdk';
    
    export default class Login extends Component {
      render() {
        return (
          <View>
            <LoginButton
              onLoginFinished={
                (error, result) => {
                  if (error) {
                    console.log("login has error: " + result.error);
                  } else if (result.isCancelled) {
                    console.log("login is cancelled.");
                  } else {
                    AccessToken.getCurrentAccessToken().then(
                      (data) => {
                        console.log(data.accessToken.toString())
                      }
                    )
                  }
                }
              }
              onLogoutFinished={() => console.log("logout.")}/>
          </View>
        );
      }
    };