15

Below is the code I am using to login with google. I have an element on login.php with id authorize-button. When clicked it logs in just fine.

I have a logout link in my header file. When I click the logout it calls gapi.auth.signOut(); then it destroys session and redirects back to login.php

This happens as far as I can tell but then it just logs the user right back into our site with google. This is a pain as some of our users switch from google to facebook logins.

Thanks in advance for any help.

function handleClientLoad() {
    gapi.client.setApiKey(apiKey);
    window.setTimeout(checkAuth, 1);
}

function checkAuth() {
    gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}

function handleAuthResult(authResult) {
    var authorizeButton = document.getElementById('authorize-button');


    if (authResult && !authResult.error) {
        //authorizeButton.style.visibility = 'hidden';
        makeApiCall();
    } else {
        //authorizeButton.style.visibility = '';
        authorizeButton.onclick = handleAuthClick;
    }
}

function handleAuthClick(event) {
    gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
    return false;
}

function signOut() {
    gapi.auth.signOut();
}


function makeApiCall() {

    gapi.client.load('oauth2', 'v2', function() {
        var request = gapi.client.oauth2.userinfo.get();

        request.execute(function(logResponse) {

            var myJSON = {
                "myFirstName": logResponse.given_name,
                "myLastName": logResponse.family_name,
                "name": logResponse.name,
                "socialEmailAddress": logResponse.email
            };

            gapi.client.load('plus', 'v1', function() {

                var request = gapi.client.plus.people.get({
                    'userId': 'me'
                });
                request.execute(function(logResponse2) {
                    //alert(JSON.stringify(logResponse));
                    myJSON['profilePicture'] = logResponse2.image.url;
                    myJSON['socialId'] = logResponse2.id;
                    //alert(JSON.stringify(myJSON));
                    $.ajax({
                        type: "POST",
                        url: "includes/login-ajax.php",
                        data: "function=googleLogin&data=" + JSON.stringify(myJSON),
                        dataType: "html",
                        success: function(msg) {

                            if (msg == 1) {

                                //window.location = "settings.php";
                            }
                        }
                    });
                });
            });
        });
    });
}
Vinayak Garg
  • 6,518
  • 10
  • 53
  • 80
jcopeland
  • 181
  • 1
  • 1
  • 7

3 Answers3

31

Make sure you have set your cookie-policy to a value other than none in your sign-in button code. For example:

function handleAuthClick(event) {
  gapi.auth.authorize(
    {
      client_id: clientId, 
      scope: scopes, 
      immediate: false, 
      cookie_policy: 'single_host_origin'
    },
    handleAuthResult);
  return false;
}

Note that sign out will not work if you are running from localhost.

class
  • 8,621
  • 29
  • 30
  • 2
    Thanks for the answer so much. I spent a lot of time to figure out why It doesn't work for me. The problem was that I used localhost. – Andrei Kaigorodov Mar 04 '14 at 16:03
  • It's still not working. I have a logout link that links to a php page. I have the following in that page. – jcopeland Mar 04 '14 at 18:01
  • @jcopeland Just to double-check one more time, are you running locally or from the web and do you have cookiepolicy set? Next, what happens when you open up the browser's console and directly execute gapi.auth.signOut? – class Mar 05 '14 at 18:22
  • 14
    +1 - I didn't know sign out wouldn't work running from localhost. Been banging my head for an hour. Thanks! (I wish Google would document that on their site) – Rob Whiteside Mar 06 '14 at 07:59
  • 1
    how does one test the `signOut()` then? – Bryan P Jan 28 '16 at 08:00
  • 4
    Test `signOut()` from a test web server that is not localhost, one easy way is to use [ngrok](https://ngrok.com/). – class Jan 28 '16 at 09:34
  • December 2019 and I used the same code from [Google gapi docs](https://developers.google.com/identity/sign-in/web/sign-in#sign_out_a_user) and it works just fine on localhost, so I think they fixed that. – Lucas Andrade Dec 18 '19 at 14:46
  • You should edit that localhost tidbit and move it to the top - what a lifesaver! – Almost_Ashleigh Feb 14 '20 at 16:39
1

Weird issue, but solved my problem by rendering the signin button (hidden) even if the user is authenticated.

See full question/answer here https://stackoverflow.com/a/19356354/353985

Community
  • 1
  • 1
redochka
  • 12,345
  • 14
  • 66
  • 79
  • 1
    This solved your issue because rendering the signin button initiates the callback routine, which must be called before the signout function will work. You can accomplish the same thing by including a reference to your callback function in a meta tag: , where "signinCallback" is the name of your javascript function that checks if the user is signed in or out. – Blair Connolly Apr 17 '15 at 23:43
  • You are right about the callback routine. I will definitely try the meta way. – redochka Apr 18 '15 at 11:21
1

I came across the same issue today. I have search for solution the whole. The only reliable solution that worked for me is through revoke as explained here

I stored access_token in session which is needed during revoke

Below is my code you may find it useful

      function logout() {
         var access_token = $('#<%=accessTok.ClientID %>').val();
         var provider = $('#<%=provider.ClientID %>').val();
    if (access_token && provider) {
        if (provider == 'GPLUS') {
            var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' +
                access_token;

            // Perform an asynchronous GET request.
            $.ajax({
                type: 'GET',
                url: revokeUrl,
                async: false,
                contentType: "application/json",
                dataType: 'jsonp',
                success: function (nullResponse) {
                    // Do something now that user is disconnected
                    // The response is always undefined.
                },
                error: function (e) {
                    // Handle the error
                    // console.log(e);
                    // You could point users to manually disconnect if unsuccessful
                    // https://plus.google.com/apps
                }
            });
        }
        else if (provider == 'FB') {
            FB.getLoginStatus(function (response) {
                if (response.status === 'connected') {
                    FB.logout();
                }
            });
        }
    } else {

    }
}
Naga
  • 2,368
  • 3
  • 23
  • 33
  • I'm experiencing this as well, and I am tearing my hair out. If you think about it, its actually a major security exposure on googles part. – MarzSocks Apr 01 '17 at 13:31
  • after 3yrs came across same issue again & found my answer, gapi.auth.signOut() is not logging out & should have if this is synchronous at least as per their documentation, wonder why was this not accepted as this seems only working solution. – Naga May 26 '17 at 18:59
  • this work around that seems to be working earlier not working anymore, not sure if there is way to allow user to logout from app like fb does, would rather take gplus out from preferred logins – Naga May 26 '17 at 19:41