Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 722
jordan Avatar asked Jun 28 '16 18:06

jordan


People also ask

Does sign in with Google use OAuth?

Google Sign-In manages the OAuth 2.0 flow and token lifecycle, simplifying your integration with Google APIs. A user always has the option to revoke access to an application at any time.

How can I tell if someone logged in Auth0?

The SPA SDKs have getTokenSilently which performs a silent authentication in a hidden iframe to check if the user has a valid session. If they do, tokens will be returned, if they have been logged out, you will get a “Login required” error which would indicate the user no longer has a session with Auth0.


Video Answer


2 Answers

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

like image 167
Joseph Avatar answered Oct 02 '22 23:10

Joseph


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)

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='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.

like image 24
Ozan Gunceler Avatar answered Oct 02 '22 21:10

Ozan Gunceler