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

前端 未结 4 1041
[愿得一人]
[愿得一人] 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: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 :

    
    

    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

提交回复
热议问题