Testing whether a user is signed in to Google
Recently I've been in a couple of conversations where the idea of testing whether a user is logged in to Google came up. This can be helpful for tuning the experience when presenting sign-in options: you can highlight the Google+ Sign-In button on the basis the user was already signed-in to Google, so should just need to consent. It's also one way of responding to the fact that signed-in users typically are going across search using HTTPS, so you don't get information about the search terms a user used to reach you. By highlighting the benefits of signing in, the users may choose to do that, and hence give much more ability to personalise and so on
The (slightly arcane) method for doing this is checkSessionState. This is a bit of Google oAuth 2.0 plumbing that allows cheaply checking whether things have changed without round-tripping to the server in many cases. There is a session state, which is kind of a hash of various aspects of the user's signed in status, locally stored in the calling application's cookie/localstorage and another one on the Google hidden auth iframe's cookie/localstorage. By passing the application one over to the iframe, it can check they are the same. If they don't match, it will probably require a server check, but if they do we can be sure nothing has changed in the users's auth state.
Because the iframe is to Google, the value of the session state there can be updated if the user signs out in another tab, or takes some other auth effecting action. This is part of what the cookie-policy value in Google+ Sign-In is controlling: the scope of the app-side session state data storage.
While we generally can't use checkSessionState for checking much without an existing session hash, we can predict one special case value: null. Null indicates that the user is not signed in, so if the session state is equal to null, then we know the user isn't logged in to Google (though if it's false, we don't know anything further about them). Below is a little example:
All we do here is load the plusone.js client asynchronously, with a callback that fires our checkSessionState call on load.
As part of one discussion though, I was introduced to another method of checking state I was not previously familiar with. The Google OpenID system has an extension to allow for this type of checking as well. In this case, we construct a URL with a return address of our current page, include the magic parameter openid.ui.mode=x-has-session and set the mode to checkid_immediate. This second parameter ensures the user is immediately returned, and the first will only be echoed back to us if the user has a valid Google session - if its there, we're signed in, if not, we're not!