How to check if user is logged in or not with “Google Sign In” (OAuth 2.0)

I am implementing Google log in for the first time as described here and here.

I am using HTML with Javascript.

The problem that needs solving is as follows: How can I, after the initial login, on a different page (say a landing page, or portal that the user sees after logging in), check if the user is logged in? Is there a service I can call to check the user’s login in status with my app key or something similar?
I assume I would have to include the google API on each page.

Login Page Code:

Script In Head (Code from Google’s tutorial listed above):

<head>
....
<script src="https://apis.google.com/js/platform.js" async defer></script>

<script>
function onSignIn(googleUser) 
{
  var profile = googleUser.getBasicProfile();
  console.log('ID: ' + profile.getId()); 
  console.log('Name: ' + profile.getName());
  console.log('Image URL: ' + profile.getImageUrl());
  console.log('Email: ' + profile.getEmail());

  alert(profile.getName());   
}

function logout()
{
    alert('logging out');
    var auth2 = gapi.auth2.getAuthInstance();
        auth2.signOut().then(function () {
        console.log('User signed out.');
        });
}
...
</head> 

Code In Body (1st line from Google’s tutorial listed above, 2nd line to trigger logout test)

<body>
...
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<div onmousedown="logout()">Logout</div>
...
</body>

Is there some way I can include the google API on another page, and then call some check login status function? Or another way to concretely tell if the user is logged in or out?

You do not need to store anything on local storage. The library allows you to check if the user is logged in or not using the isSignedIn.get() on the auth2 of the gapi object.

Load the JavaScript library, make sure you are not deferring the load :

<script src="https://apis.google.com/js/platform.js"></script>

Then initialize the library and check if the user is logged in or not

var auth2;
var googleUser; // The current user

gapi.load('auth2', function(){
    auth2 = gapi.auth2.init({
        client_id: 'your-app-id.apps.googleusercontent.com'
    });
    auth2.attachClickHandler('signin-button', {}, onSuccess, onFailure);

    auth2.isSignedIn.listen(signinChanged);
    auth2.currentUser.listen(userChanged); // This is what you use to listen for user changes
});  

var signinChanged = function (val) {
    console.log('Signin state changed to ', val);
};

var onSuccess = function(user) {
    console.log('Signed in as ' + user.getBasicProfile().getName());
    // Redirect somewhere
};

var onFailure = function(error) {
    console.log(error);
};

function signOut() {
    auth2.signOut().then(function () {
        console.log('User signed out.');
    });
}        

var userChanged = function (user) {
    if(user.getId()){
      // Do something here
    }
};

Don’t forget to change the app id

You can stringify a custom userEntity object and store it in sessionStorage where you can check it anytime you load a new page. I have not tested the following but it should work (doing something similar with WebAPI tokens in the same way)

Read More:   how can I get the current url using protractor?

function onSignIn(googleUser) 
{
  var profile = googleUser.getBasicProfile();
  console.log('ID: ' + profile.getId()); 
  console.log('Name: ' + profile.getName());
  console.log('Image URL: ' + profile.getImageUrl());
  console.log('Email: ' + profile.getEmail());
  
  var myUserEntity = {};
  myUserEntity.Id = profile.getId();
  myUserEntity.Name = profile.getName();
  
  //Store the entity object in sessionStorage where it will be accessible from all pages of your site.
  sessionStorage.setItem('myUserEntity',JSON.stringify(myUserEntity));

  alert(profile.getName());   
}

function checkIfLoggedIn()
{
  if(sessionStorage.getItem('myUserEntity') == null){
    //Redirect to login page, no user entity available in sessionStorage
    window.location.href="https://stackoverflow.com/questions/38083568/Login.html";
  } else {
    //User already logged in
    var userEntity = {};
    userEntity = JSON.parse(sessionStorage.getItem('myUserEntity'));
    ...
    DoWhatever();
  }
}

function logout()
{
  //Don't forget to clear sessionStorage when user logs out
  sessionStorage.clear();
}

Of course, you can have some internal checks if the sessionStorage object is tampered with. This approach should work with modern browsers like Chrome and Firefox.

To check is user Signed-in use:

gapi.auth2.getAuthInstance().isSignedIn.get()

Adding on to Joseph’s answer above, you can then get information about the user by calling auth2.currentUser.get().getBasicProfile().

    if (auth2.isSignedIn.get()) {
        googleUserProfile = auth2.currentUser.get().getBasicProfile()
        console.log('ID: ' + googleUserProfile.getId());
        console.log('Full Name: ' + googleUserProfile.getName());
        console.log('Given Name: ' + googleUserProfile.getGivenName());
        console.log('Family Name: ' + googleUserProfile.getFamilyName());
        console.log('Image URL: ' + googleUserProfile.getImageUrl());
        console.log('Email: ' + googleUserProfile.getEmail());
    }

From the docs: https://developers.google.com/identity/sign-in/web/people

according to the link from Phyrik post (https://developers.google.com/identity/sign-in/web/people) –

google stopped supporting the Sign-In Javascript web auth API:

We are discontinuing the Google Sign-In JavaScript Platform Library for web. The library will be unavailable for download after the March 31, 2023 deprecation date. Instead, use the new Google Identity Services for Web.
By default, newly created Client IDs are now blocked from using the older Platform Library, existing Client IDs are unaffected. New Client IDs created before July 29th, 2022 can set plugin_name to enable use of the Google Platform Library.


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts