Google Sign-in User Changed Listener

782 Views Asked by At

When user lands on page, the Google auth is loaded and initiated. The Google Sign-in API provides a listener function that's triggered if the user changes (GoogleAuth.currentUser.listen()). The expected behavior for the feature that I want to implement involves watching for users logging into gmails within other tabs in the browser.

const userChanged = user => {
  if (user) {
    console.log('CHANGED TO USER: ', user);
  }
};

const loadGoogleAuth = () => {
  window.gapi.load('auth2', () => {
    const gapiAuth = window.gapi.auth2;
    gapiAuth.init({
      client_id: '<YOUR-CLIENT-ID>.apps.googleusercontent.com',
      cookie_policy: 'none', //my hunch is this could be affecting listener capabilities?
      scope: 'profile email openid',
    });
    const authInstance = gapiAuth.getAuthInstance();
    const element = document.getElementById('googleSignIn');
    authInstance.attachClickHandler(
      element,
      {},
      googleUser => {
        console.log(`Signed in: ${googleUser.getBasicProfile().getName()}`);
      },
      error => {
        console.log('Sign-in error', error);
      }
    );
    authInstance.currentUser.listen(userChanged);
  });
};

const withLifeCycles = lifecycle({
  componentDidMount() {
    if (window.gapi) {
      loadGoogleAuth();
    }
  },
});

This is working, but only for the first gmail that the user signs in with or the gmail that is already signed in before the user lands on the page. In other words, if I log in with Gmail A, it detects the user change but it won't detect Gmail B if I log out of Gmail A and log into Gmail B afterwards. However, it will detect relogins for Gmail A subsequently and not for any other gmail addresses. Is it possible for the listener function to detect sign-ins on any gmail address or only for the firs gmail that is detected?

1

There are 1 best solutions below

0
JozefS On

You need to listen to signed-in changes too. That way you will detect that user signed out from account A and signed in to B.

auth2.isSignedIn.listen(signinChanged)

see https://developers.google.com/identity/sign-in/web/listeners