Search code examples
javascriptgoogle-apigoogle-api-clientgoogle-api-javascript-client

How can you detect that you are logged out with the Google login API?


I am using the Google login client API for JavaScript. The site I am working on has two relevant pages. It has a login page, and it has a user profile page. The login page obviously has a Google login button on it. You should only be able to view your profile page when you are logged in. When a user goes to their profile page without being logged in, it should redirect them to the login page.

Here is an approach I have tried that did not work:

// This does not work because this event is only fired when the user logs in or logs out, but not when the user is already logged out.
gapi.auth2.init().isSignedIn.listen(function(state) {
    if(!state) location.href = "/login/";
});

I have also tried detecting the login status of the user when the script loads, but that did not work either. It always redirected to the login page because the Google API can never log the user in by the time the script is done loading.

Additionally, I am trying not to use setInterval or setTimeout in my code, though, if that is my only valid option, please inform me.

By the way, I have heard multiple times that I can just set a variable when the user logs in, and then simply redirect to the login page if the variable is false. When would I check for the value of said variable? This will not work because it requires me to set a specific delay with setTimeout. Google's loading time can vary greatly, so I am not going to use that.


Solution

  • I figured out that you can use this simple expression that returns either true or false depending on whether the user is logged into Google on your website.

    gapi.auth2.init().isSignedIn.get()