0

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.

2 Answers 2

1

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>
    );
  }
};
2
  • @JunaidAhmed Great that you made it work. Keep going!
    – glinda93
    Jul 31, 2020 at 10:57
  • Thank you! this works fine but for expo users see the answer below. Jul 31, 2020 at 10:58
1

The above answer is correct. However, if you're using expo then you may have to link the packages manually. A better solution for expo users:

For Google SignIn

Use: https://docs.expo.io/versions/latest/sdk/google/

'''

import * as Google from 'expo-google-app-auth';

const { type, accessToken, user } = await Google.logInAsync({
  iosClientId: `<YOUR_IOS_CLIENT_ID_FOR_EXPO>`,
  androidClientId: `<YOUR_ANDROID_CLIENT_ID_FOR_EXPO>`,
  iosStandaloneAppClientId: `<YOUR_IOS_CLIENT_ID>`,
  androidStandaloneAppClientId: `<YOUR_ANDROID_CLIENT_ID>`,
});

if (type === 'success') {
  /* `accessToken` is now valid and can be used to get data from the Google API with HTTP requests */
  console.log(user);
}

'''

For Facebook SignIn

Use: https://docs.expo.io/versions/latest/sdk/facebook/

'''

async function logIn() {
  try {
    await Facebook.initializeAsync('<APP_ID>');
    const {
      type,
      token,
      expires,
      permissions,
      declinedPermissions,
    } = await Facebook.logInWithReadPermissionsAsync({
      permissions: ['public_profile'],
    });
    if (type === 'success') {
      // Get the user's name using Facebook's Graph API
      const response = await fetch(`https://graph.facebook.com/me?access_token=${token}`);
      Alert.alert('Logged in!', `Hi ${(await response.json()).name}!`);
    } else {
      // type === 'cancel'
    }
  } catch ({ message }) {
    alert(`Facebook Login Error: ${message}`);
  }
}

'''

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.