Tuesday, 4 February 2020

User Authentication with Google Sign-in Button and Google APIs

Original basic Google Sign-in button:
https://developers.google.com/identity/sign-in/web/sign-in

The flow above doesn't fire event when user is not signed in, the following flow shows how to get events for both:
  • Not yet signed in, and 
  • Signed in.
1) Create a project and credentials for project
https://console.developers.google.com/apis/credentials

2) Create the front page, for example, index.html

3) Add meta tag to the front page with credentials in step 1:
<meta name="google-signin-client_id" 
content="XXX.apps.googleusercontent.com"/>

4) Add a tag to index.html for Google Sign-in button to be inserted inside
<div class="g-signin2" data-onsuccess="on_logged_in"></div>

5) Add the function to handle on-logged-in event
function on_logged_in(User){
  var Profile = User.getBasicProfile();
  var Email   = Profile.getEmail();
  var Name    = Profile.getName();
  console.log(Email,Name);
}

6) Load Google APIs (gapi) library and set events
//Global status for scripts run before gapi
var Gready = false;
var Email  = null;

//Use this lock, better than gaccount_readiness()
var Gready_Unlock,Gready_Lock = 
new Promise(Rs=> { Gready_Unlock=Rs; });

//jQuery on document ready
$(()=>{
  await $.getScript("https://apis.google.com/js/platform.js");

  //Load Auth2 component of GAPIs
  gapi.load("auth2",()=>{
    
    //Event for both not-yet signed in, and signed in
    gapi.auth2.init().currentUser.listen(User=>{      
      var Profile = User.getBasicProfile();    
      ...
      Email  = Profile.getEmail();
      Gready = true;
      Gready_Unlock();
    });

    //Event for signed-in status change
    gapi.auth2.init().isSignedIn.listen(Status=>{
      console.log("Is signed in:",Status);
    });
  });
});

7) Scripts run before gapi, wait for gapi ready
async function gaccount_readiness(){
  var Unlock,Lock=new Promise(Resolve=>{ Unlock=Resolve; });

  setTimeout(function check_gaccount(){
    if (Gready==true){
      Unlock();
      return;
    }

    setTimeout(check_gaccount,0);
  },0);

  await Lock;
}

//Use this:
await gaccount_readiness();
//Or use this:
await Gready_Lock; //Better

console.log(Email);

No comments:

Post a Comment