Oauth2 google login

Hello, i’m trying to mage a google login so i have an handler.js that load an html page, but i can’t understand how to do it, i have tried do make so many variant actually i have this one that don’t find the onSignIn function

<html>
<head>
<?php 
header("Access-Control-Allow-Origin: *");
?>
<meta name="google-signin-scope" content="profile email">
    <meta name="google-signin-client_id" content="1004535083510-o2jlo3597890iqoqj4c0p3ibeljdn80i.apps.googleusercontent.com">
    <script src="https://apis.google.com/js/platform.js" async defer></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
    
$(document).ready(function(){
   
   $('#content').load("new.html");

});
</script>
</head>
<body>
<div class="row" align="center" width="100%">
  <div class="col-md-3" align="center" width="100%">
      <a class="btn btn-outline-dark" onClick="onSignIn()" role="button" style="text-transform:none">
      <img width="20px" style="margin-bottom:3px; margin-right:5px" alt="Google sign-in" src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Google_%22G%22_Logo.svg/512px-Google_%22G%22_Logo.svg.png" />
      Login with Google
    </a>
      <script>
      function onSignIn(googleUser) {
  var profile = googleUser.getBasicProfile();
  console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
  console.log('Name: ' + profile.getName());
  console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
          $('#profileinfo').append("<h2>name- "+profile.getName()+"</h2");
          $('#profileinfo').append("<p>your email is- "+profile.getEmail()+"</p>");
}
      </script>
      <!--<a id="gp_login" href="javascript:void(0)" onclick="javascript:googleAuth()">Login using Google</a>-->
  </div>
</div>
    <div id="profileinfo">
    </div>
    <link   rel="stylesheet" 
        href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" 
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" 
        crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" 
        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" 
        crossorigin="anonymous">
</script>
</body>
</html>

where is the error?

Hi @ayrin,

The code you posted is meant to be served by a web server that supports PHP. You will have to find a client-side example that can work directly with the google servers for it to work with Playcanvas. Without involving a server of your own.

Check the google docs on that:

https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow

Tnx @Leonidas, yes i already reached that page but there is something unclear to me
this is the full example code, should i put it inside the html file or what

<script>
  var GoogleAuth;
  var SCOPE = 'https://www.googleapis.com/auth/drive.metadata.readonly';
  function handleClientLoad() {
    // Load the API's client and auth2 modules.
    // Call the initClient function after the modules load.
    gapi.load('client:auth2', initClient);
  }

  function initClient() {
    // In practice, your app can retrieve one or more discovery documents.
    var discoveryUrl = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';

    // Initialize the gapi.client object, which app uses to make API requests.
    // Get API key and client ID from API Console.
    // 'scope' field specifies space-delimited list of access scopes.
    gapi.client.init({
        'apiKey': 'YOUR_API_KEY',
        'clientId': 'YOUR_CLIENT_ID',
        'discoveryDocs': [discoveryUrl],
        'scope': SCOPE
    }).then(function () {
      GoogleAuth = gapi.auth2.getAuthInstance();

      // Listen for sign-in state changes.
      GoogleAuth.isSignedIn.listen(updateSigninStatus);

      // Handle initial sign-in state. (Determine if user is already signed in.)
      var user = GoogleAuth.currentUser.get();
      setSigninStatus();

      // Call handleAuthClick function when user clicks on
      //      "Sign In/Authorize" button.
      $('#sign-in-or-out-button').click(function() {
        handleAuthClick();
      });
      $('#revoke-access-button').click(function() {
        revokeAccess();
      });
    });
  }

  function handleAuthClick() {
    if (GoogleAuth.isSignedIn.get()) {
      // User is authorized and has clicked "Sign out" button.
      GoogleAuth.signOut();
    } else {
      // User is not signed in. Start Google auth flow.
      GoogleAuth.signIn();
    }
  }

  function revokeAccess() {
    GoogleAuth.disconnect();
  }

  function setSigninStatus() {
    var user = GoogleAuth.currentUser.get();
    var isAuthorized = user.hasGrantedScopes(SCOPE);
    if (isAuthorized) {
      $('#sign-in-or-out-button').html('Sign out');
      $('#revoke-access-button').css('display', 'inline-block');
      $('#auth-status').html('You are currently signed in and have granted ' +
          'access to this app.');
    } else {
      $('#sign-in-or-out-button').html('Sign In/Authorize');
      $('#revoke-access-button').css('display', 'none');
      $('#auth-status').html('You have not authorized this app or you are ' +
          'signed out.');
    }
  }

  function updateSigninStatus() {
    setSigninStatus();
  }
</script>

<button id="sign-in-or-out-button"
        style="margin-left: 25px">Sign In/Authorize</button>
<button id="revoke-access-button"
        style="display: none; margin-left: 25px">Revoke access</button>

<div id="auth-status" style="display: inline; padding-left: 25px"></div><hr>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script async defer src="https://apis.google.com/js/api.js"
        onload="this.onload=function(){};handleClientLoad()"
        onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

So you will have to rework that example to work exclusively in JS, so you can add it either on your project custom splash screen or on a regular Playcanvas script.

First make sure to include the google SDK to your Playcanvas external libraries. Then follow the source code, first initializing the SDK (the code at the end with the library load script) and then add the functions/logic.

1 Like

So i have added https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js into the external scripts, is that correct?

So now i have made the oauth2.js file like this

var Oauth2 = pc.createScript('oauth2');

// initialize code called once per entity
Oauth2.prototype.initialize = function() {
    var GoogleAuth;
    var SCOPE = 'https://www.googleapis.com/auth/drive.metadata.readonly';
};

// update code called every frame
Oauth2.prototype.update = function(dt) {
    
};

Oauth2.prototype.handleClientLoad = function() {
    // Load the API's client and auth2 modules.
    // Call the initClient function after the modules load.
    gapi.load('client:auth2', initClient);
 };

Oauth2.prototype.initClient =function() {
    // In practice, your app can retrieve one or more discovery documents.
    var discoveryUrl = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';

    // Initialize the gapi.client object, which app uses to make API requests.
    // Get API key and client ID from API Console.
    // 'scope' field specifies space-delimited list of access scopes.
    gapi.client.init({
        'apiKey': 'cjPe-2I-TLjlQjtuD3FE9-Hm',
        'clientId': '1004535083510-o2jlo3597890iqoqj4c0p3ibeljdn80i.apps.googleusercontent.com',
        'discoveryDocs': [discoveryUrl],
        'scope': SCOPE
    }).then(function () {
      GoogleAuth = gapi.auth2.getAuthInstance();

      // Listen for sign-in state changes.
      GoogleAuth.isSignedIn.listen(updateSigninStatus);

      // Handle initial sign-in state. (Determine if user is already signed in.)
      var user = GoogleAuth.currentUser.get();
      setSigninStatus();

      // Call handleAuthClick function when user clicks on
      //      "Sign In/Authorize" button.
      $('#sign-in-or-out-button').click(function() {
        handleAuthClick();
      });
      $('#revoke-access-button').click(function() {
        revokeAccess();
      });
    });
  };

Oauth2.prototype.handleAuthClick =function() {
    if (GoogleAuth.isSignedIn.get()) {
      // User is authorized and has clicked "Sign out" button.
      GoogleAuth.signOut();
    } else {
      // User is not signed in. Start Google auth flow.
      GoogleAuth.signIn();
    }
};

Oauth2.prototype.revokeAccess =function() {
    GoogleAuth.disconnect();
};

Oauth2.prototype.setSigninStatus =function() {
    var user = GoogleAuth.currentUser.get();
    var isAuthorized = user.hasGrantedScopes(SCOPE);
    if (isAuthorized) {
      $('#sign-in-or-out-button').html('Sign out');
      $('#revoke-access-button').css('display', 'inline-block');
      $('#auth-status').html('You are currently signed in and have granted ' +
          'access to this app.');
    } else {
      $('#sign-in-or-out-button').html('Sign In/Authorize');
      $('#revoke-access-button').css('display', 'none');
      $('#auth-status').html('You have not authorized this app or you are ' +
          'signed out.');
    }
};

Oauth2.prototype.updateSigninStatus=function() {
    setSigninStatus();
};

how do I trigger it with a button?

So, since you are using jQuery then take a look at the.HTML/CSS examples on the tutorials section:

https://developer.playcanvas.com/en/tutorials/?tags=ui

You will have to create the HTML elements your code targets in those functions #sign-in-or-out-button etc

I have made a 2dscreen with a button that trigger the script but i have got 1 error getAuthInstance is null. Any idea why?

If you use a 2D screen and Playcanvas UI elements then you need to refactor your code a bit. Instead of using jQuery click handlers you need to attach each method to each element click/touch handler. Study the following tutorial on how to execute your custom logic when a button is clicked:

https://developer.playcanvas.com/en/tutorials/ui-elements-buttons/