How to manage google sign-in session (Google Sign-In JavaScript client)

5.6k views Asked by At

im trying to implement google sign-in using their new API : https://developers.google.com/identity/sign-in/web/

Sign-in and Sign-out work fine. My problem is that i dont know how to manage a session on other pages without a server side.

So i tried this code - https://developers.google.com/identity/sign-in/web/session-state

And it doesnt work well for me. I dont want to have the google sign in button in every page. If i remove the "auth2.attachClickHandler.." part the whole code doesnt work.

All i want is to indicate in other pages (not in the page with the google button) if a user is still connected to or not. Can you help me?

EDIT: I tried the following code suggested in the answers but i get an error that says: " Uncaught TypeError: Cannot read property 'init' of undefined"

Code:

var auth2 = gapi.auth2.init({
client_id : 'ID.apps.googleusercontent.com'
});
auth2.then(function() {
var isSignedIn = auth2.isSignedIn.get();
var currentUser = auth2.currentUser.get();
if (isSignedIn) {
    console.log("signed in");
    // User is signed in.
    // Pass currentUser to onSignIn callback.
 } else {
    console.log("NOT signed in");
    // User is not signed in.
    // call auth2.attachClickHandler
    // or even better call gapi.signin2.render
    }
}); 
1

There are 1 answers

3
Jarosław Gomułka On

You can load gapi.auth2 on all pages and call:

var auth2 = gapi.auth2.init(...);
auth2.then(function() {
  var isSignedIn = auth2.isSignedIn.get();
  var currentUser = auth2.currentUser.get();
  if (isSignedIn) {
    // User is signed in.
    // Pass currentUser to onSignIn callback.
  } else {
    // User is not signed in.
    // call auth2.attachClickHandler
    // or even better call gapi.signin2.render
  }
});

In this solution sign in button is displayed only when user is not signed in.