使用Google登录检查已登录的Google用户

时间:2015-12-16 18:36:17

标签: javascript authentication

我正在使用Google Sign-in库。

如果我在我的网页上使用Google的provided sign in button,它会在我采取任何行动之前快速更改状态以显示我已登录。

是否可以在不使用Google默认按钮的情况下检测此已登录状态?

主要问题是他们的按钮不允许检查已登录帐户的托管域。

2 个答案:

答案 0 :(得分:2)

我尝试使用GoogleAuth.currentUser.get()函数来获取用户,但正如documentation注释:

  

在新初始化的GoogleAuth实例中,尚未设置当前用户。使用currentUser.listen()方法或GoogleAuth.then()来获取初始化的GoogleAuth实例。

如上所述使用GoogleAuth.then(onInit, onFailure)可以正确检索用户的登录状态。

/**
 * The Sign-In client object.
 */
var auth2;

/**
 * Initializes the Sign-In client.
 */
var initClient = function() {
  gapi.load('auth2', function(){
    /**
     * Retrieve the singleton for the GoogleAuth library and set up the
     * client.
     */
    auth2 = gapi.auth2.init({
        client_id: CLIENT_ID,
        scope: 'profile'
    });

    // Called once auth2 has finished initializing
    auth2.then(checkForLoggedInUser, onFailure);

  });
};

function checkForLoggedInUser() {
  var user = auth2.currentUser.get();
  var profile = user.getBasicProfile();
  console.log('Email: ' + profile.getEmail());
}

答案 1 :(得分:0)

您可以使用GoogleAuth.isSignedIn.get()方法:

// 1. Make gapi.auth2 available (using gapi.load("auth2", ...))
// 2. Initialize the library (using gapi.init({ ... }))
const isSignedIn = gapi.auth2.getAuthInstance().isSignedIn.get();
如果用户已登录Google,则

isSignedIntrue,否则为false