Google email offline access using react native expo app

622 views Asked by At

I am creating one app using react native expo, which allow end user to login by their google account , and then applicaton try to save the access_token so that server based applicatin can use this to send the email on their behalf ,

But when using google sing in , i am not getting refresh token and not able to send the email ,

Here is code example which i am using

I tried below method to get the access request

const [request, response, promptAsync] = Google.useIdTokenAuthRequest({
    clientId: "XXXXXXX",
      androidClientId:"XXXXXXX",
      iosClientId:"XXXXXXX"
  });
  const [initializing, setInitializing] = useState(true);
  const [user, setUser] = useState();
  const sendNotification=useNotification()
  //console.log(sendNotification)
  useEffect(() => {
    if (response?.type === "success") {
      const { id_token } = response.params;
      const auth = getAuth();
      const credential = GoogleAuthProvider.credential(id_token);
      signInWithCredential(auth, credential);
      let decoded = jwt_decode(id_token);
      socialLogin(decoded)
    }
  }, [response]);

And on server using this code to sending email

const { google } = require('googleapis');
const path = require('path');
const fs = require('fs');
const credentials = require('./credentials.json');
// Replace with the code you received from Google
const code = 'XXXXXXX';
//const code="XXXXXXX"
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
oAuth2Client.getToken(code).then(({ tokens }) => {
  console.log('first')
  const tokenPath = path.join(__dirname, 'token.json');
  fs.writeFileSync(tokenPath, JSON.stringify(tokens));
  console.log('Access token and refresh token stored to token.json');
}).catch(err=>console.log(err));
1

There are 1 answers

1
Hari Haran On
async function signInWithGoogleAsync() {
  try {
    const result = await Google.logInAsync({
      androidClientId: YOUR_CLIENT_ID_HERE,
      scopes: ["profile", "email"],
    });
    if (result.type === "success") {
      onSignIn(result);
      return result.accessToken;
    } else {
      return { cancelled: true };
    }
  } catch (e) {
    return { error: true };
  }
}