avatar
Integrating Google One Tap with Vue Vue

• Take advantage of using concept of composables that generally involves creating small, reusable functions or modules that encapsulate specific pieces of functionality. 

» GoogleOneTab.js

import axios from 'axios';
import { ref } from 'vue';

export default function() {
  const CLIENT_ID = "<client id>"
  const CLIENT_URL = "<client url>"
  const API_URL = "http://localhost:8080"

  const userData = ref()

  const googleOptions = {
            client_id: CLIENT_ID, 
            auto_select: false, 
            cancel_on_tap_outside: true, 
            context: 'signin',
        };

      const googleOneTap = ({ client_id, auto_select = false, cancel_on_tap_outside = false, context = 'signin' }, callback) => {
        const contextValue = ['signin', 'signup', 'use'].includes(context) ? context : 'signin';
        const googleScript = document.createElement('script');
        googleScript.setAttribute('src', 'https://accounts.google.com/gsi/client');
        document.head.appendChild(googleScript)
        googleScript.onload = () => {
          if (client_id) {
            window.google.accounts.id.initialize({
              client_id: client_id,
              callback: callback,
              auto_select: auto_select,
              cancel_on_tap_outside: cancel_on_tap_outside,
              context: contextValue
            });
            window.google.accounts.id.prompt();
          } else {
            console.error('client_id is missing');
          }
        };
      }
      
    const oneTapSignin = (options) => {
    googleOneTap(options, (res) => {
      const axiosOptions = {
        headers: { "Access-Control-Allow-Origin": CLIENT_URL }
      }

      axios.post(`${API_URL}/verify-token`, res, axiosOptions)
        .then(res => {
          userData.value = res.data
        })
        .catch(error => {
          console.log(error);
        });

      });
  }

  return { googleOptions, oneTapSignin, userData }
}

» SampleAuthentication.vue

<template>
    // TODO
</template>
<script>
import googleOneTapSignin from '~/composables/GoogleOneTab' 
import { onMounted, ref, watch } from 'vue'

export default {
  props: {
    msg: String
  },
  setup(){
    const googleUserData = ref({
      name: '',
      email: '',
      email_verified: '',
      picture: ''
    })
    
    onMounted(() => {
      const { googleOptions, oneTapSignin, userData } = googleOneTapSignin()
      oneTapSignin(googleOptions)

      watch(userData, () => {
        googleUserData.value = userData.value
      })
    })
    return { googleUserData }
  }
}
</script>

• Create OAuth Client ID credentials is an important step in setting up authentication and security in Google Cloud Platform (GCP). 

To avoid the error 'The given origin is not allowed for the given client ID (GSI)' it's best to use 'localhost' for development and your actual domain ('www') for production.

» .htaccess

# Enforce www in the URL
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

• Verify a Google ID token on your server side after a one-tap sign-in. If you are using PHP 7 and want to interact with Google APIs, including verifying Google ID tokens, you can use the google/apiclient library. 

» package.json

"google/apiclient": "2.12.1",

» PHP script

use Google_Client;
use Google_Exception;

$client = new Google_Client(['client_id' => 'YOUR_CLIENT_ID']);
try {
    $payload = $client->verifyIdToken($idToken);
    if ($payload) {
        // Token is valid, and you can use the user's information.
        $userId = $payload['sub'];
        $userName = $payload['name'];
        $userEmail = $payload['email'];
        echo json_encode(['message' => 'Token verified successfully']);
    } else {
        echo json_encode(['error' => 'Invalid token']);
    }
} catch (Google_Exception $e) {
    echo json_encode(['error' => 'An error occurred while verifying the token']);
}

Note: You can refer to the URL https://developers.google.com/identity/gsi/web/guides/verify-google-id-token to find detailed implementations for verifying Google ID tokens.

You need to login to do this manipulation!