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

前端 未结 4 991
[愿得一人]
[愿得一人] 2020-12-15 22:25

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:

相关标签:
4条回答
  • 2020-12-15 22:44

    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.

    0 讨论(0)
  • 2020-12-15 22:50

    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

    0 讨论(0)
  • 2020-12-15 22:51

    To check is user Signed-in use:

    gapi.auth2.getAuthInstance().isSignedIn.get()
    
    0 讨论(0)
  • 2020-12-15 22:59

    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

    0 讨论(0)
提交回复
热议问题